Convert byte[] Array to String and Vice-versa

Learn to convert byte[] array to String and convert String to byte[] array in Java with examples. Conversion between byte array and string may be used in many cases including IO operations, generate secure hashes etc.

Until it is absolute necessary, DO NOT convert between string and byte array. They both represent different data; and are there to serve specific purposes i.e. strings are for text, byte[] is for binary data.

1. Java convert byte[] array to String

1.1. String constructor – new String(byte[])

To convert a byte array to String, you can use String class constructor with byte[] as constructor argument.

byte[] bytes = "hello world".getBytes();

//Convert byte[] to String
String s = new String(bytes);

System.out.println(s);

Output:

hello world

1.2. Base64 class in Java 8

Since Java 8, we have Base64 class is available.

As you might be aware of – Base64 is a way to encode binary data, while UTF-8 and UTF-16 are ways to encode Unicode text data. So if you need to encode arbitrary binary data as text, Base64 is the way to go.

byte[] bytes = "hello world".getBytes();

//Convert byte[] to String
String s = Base64.getEncoder().encodeToString(bytes);

System.out.println(s);

Output:

hello world

2. Java convert String to byte[]

2.1. String.getBytes() method

To convert from string to byte array, use String.getBytes() method. Please note that this method uses the platform’s default charset.

//String
String string = "howtodoinjava.com";

//Convert string to byte[]
byte[] bytes = string.getBytes();

2.2. Base64 class in Java 8

Base64.getDecoder().decode() method converts a string to byte array.

//String
String string = "howtodoinjava.com";

//Base64 Decoded
byte[] bytes = Base64.getDecoder().decode(string);

3. Summary

We should focus on type of input data when working with conversion between byte[] array and String in Java.

  1. Use String class when you input data is string or text content.
  2. Use Base64 class when you input data is byte array.

Drop me your questions in comments section.

Happy Learning !!

Leave a Reply

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial