Convert String to Byte Array or Byte Array to String in Java

Sometimes we need to convert Strings into Bytes because of several reasons like, to save content to the file, sending data over a network or it can be any other reason. So in this tutorial we’ll see how we can convert string to byte array or byte array to string in Java.

Convert String to Byte Array in Java

Method 1: Using String.getBytes()

Output:

Platform’s encoding = [B@387c703b

Contents of byte Array = [84, 104, 101, 32, 67, 114, 97, 122, 121, 32, 80, 114, 111, 103, 114, 97, 109, 109, 101, 114]

Explanation:

In above program, we have used String Class’s getBytes() method to convert String to Bytes and after then we’ve used toString (it converts an object to string) method of Array Class.

Note: If we don’t use a specific character encoding it will use platform’s default encoding. So the Byte object can be different according to the platform (Window, Linux) but the content in that Byte object will be the same after decoding on the same platform.

If you want to specify the character encoding to get the same byte object then you can pass the encoding to getBytes(“encoding”) method. 

Example:

 byte[] b = str.getBytes(“UTF-8”);

or

byte[] b = str.getBytes(Charset.forName(“UTF-8”));

or

byte[] b = str.getBytes(StandardCharsets.UTF_8);

But it will throw an Exception so either catch it or use throws Exception.

Method 2: By Typecasting

Other way is get the same result as above is typecasting. We’ll get the ascii value of each character in the String and will append it into a Byte Array.

Here is the example:

Output:

[ 84, 104, 101, 32, 67, 114, 97, 122, 121, 32, 80, 114, 111, 103, 114, 97, 109, 109, 101, 114 ]

Explanation:

In above program, we’ve declared a byte Array as the same size of String’s length. After that we’re getting each character using charAt() method one by one inside a for loop and assigning it to byte array after typecasting character to byte.

Convert Byte Array to String in Java

Method 1: By Passing Byte Object to String’s Constructor

Output:

Bytes to String = The Crazy Programmer

Explanation:

So by just passing a Bytes object to String’s constructor we can convert it into String.

Method 2: By Typecasting

Output:

String: The Crazy Programmer

Explanation:

In above program, we have a byte array. After that we have created a new empty string, typecasting each of the element from the byte array to char and append it into the string.

So I hope you’ve understood the concept of converting String to Bytes and vice versa. If you’ve any problem related with this article then please let us know in comment box.

Leave a Reply

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