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, generating 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. From byte[] to String
1.1. Using String Constructor
To convert a byte array to String
, you can use String
class constructor with byte[]
as the constructor argument.
byte[] bytes = "hello world".getBytes();
String s = new String(bytes);
1.2. Using Base64
Since Java 8, we have Base64 class available. As you might be aware that 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();
String s = Base64.getEncoder().encodeToString(bytes);
2. From String to byte[]
2.1. Using String.getBytes()
To convert from string to byte array, use String.getBytes() method. Please note that this method uses the platform’s default charset.
String string = "howtodoinjava.com";
byte[] bytes = string.getBytes();
2.2. Using Base64
The Base64.getDecoder().decode() method converts a string to a byte array.
String string = "howtodoinjava.com";
byte[] bytes = Base64.getDecoder().decode(string);
3. Summary
We should focus on the input data type when converting between byte[] array and String in Java.
- Use the String class when you input data in string or text content.
- Use Base64 class when you input data in a byte array.
Drop me your questions in the comments section.
Happy Learning !!
Comments