How to convert string to byte array and vice versa in Java

How to convert string to byte array and vice versa in Java

Sometimes we have to convert String variable into a Byte array format, for example, in encryption or to display base 64 encoded data as text. In this article we will learn how to convert string to byte array and vice versa in Java with example program.

Java program to convert string to byte array

StringToByteArray.java

Output

Java program to convert byte array to string

Output

It can be noted from the output that byte array cannot be converted to string using toString() method of the byte array object. Also note that, while converting byte array to string, the original character encoding of the text from which byte array was created should be used for converting back to string. If you use a different character encoding, you will not get the original String back. Always provide character encoding while converting bytes to character. Here is a list of supported encoding.

You can read Core Java Volume 1 – Fundamentals or Core Java for Impatient by Cay S. Horstmann to learn more about converting bytes to characters in Java.

That’s all about how to convert string to byte array and byte array to string in Java. If you have any doubts post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.