Today we will learn how to convert String to byte array in java. We will also learn how to convert byte array to String in Java.

String to byte array

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform’s default charset. This method is overloaded and we can also pass Charset as argument.

Here is a simple program showing how to convert String to byte array in java.

Below image shows the output when we run the above program.

java-string-to-byte-array

We can also get the byte array using the below code.

However if we provide Charset name, then we will have to either catch UnsupportedEncodingException exception or throw it. Better approach is to use StandardCharsets class introduced in Java 1.7 as shown below.

That’s all the different ways to convert String to byte array in java.

Java byte array to String

Let’s look at a simple program showing how to convert byte array to String in Java.

Below image shows the output produced by the above program.

java-string-to-byte-array

Did you notice that I am providing char while creating the byte array?

It works because of autoboxing and char ‘P’ is being converted to 80 in the byte array. That’s why the output is the same for both the byte array to string conversion.

String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used to convert byte array to String in Java.

String class also has a method to convert a subset of the byte array to String.

Above code is perfectly fine and ‘str’ value will be ‘PAN’. That’s all about converting byte array to String in Java.

Reference: getBytes API Doc

By admin

Leave a Reply

%d bloggers like this: