June 22, 2022

How to Convert String to Byte Array in Java

This post shows how you can convert String to a byte array (Byte[]) in Java.

Options for converting String to byte array in Java

String class in Java has a getBytes() method to encode String into a sequence of bytes. This method has two overloaded variants too where you can pass the charset to be used for encoding.

  • byte[] getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
  • byte[] getBytes(String charsetName) throws UnsupportedEncodingException- Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
  • byte[] getBytes(Charset charset)- Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

Using getBytes() method

This example shows how you can convert String to byte array in Java using the getBytes() method.

import java.util.Arrays;

public class StringToByteArr {
  public static void main(String[] args) {
    String str = "This is a test String";
    // converting to byte[]
    byte[] b = str.getBytes();
    System.out.println("String as Byte[]- " + Arrays.toString(b));
  }
}
Output
String as Byte[]- [84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 32, 83, 116, 114, 105, 110, 103]

When the byte array is printed it shows the ASCII code for the characters in the String.

If you want to specify the charset to be used when converting String to Byte[] in Java you can use the overloaded getBytes() method. If you used the one where charset name is passed as String you do need to catch the exception UnsupportedEncodingException.

So better to use the second overloaded method where charset instance is passed.

Following program shows both the ways; passing charset name as String and where charset instance is passed.

public class StringToByteArr {
  public static void main(String[] args) {
    String str = "This is a test String";
    try{
      byte[] b = str.getBytes("UTF-16");
      System.out.println("String as Byte[]" + b);
      
    }catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    byte[] byteArr;
    // Using the charSet instance
    byteArr = str.getBytes(Charset.forName("UTF-16"));
    byteArr = str.getBytes(StandardCharsets.UTF_16);
  }
}

As you can see from the program when you are passing the charset instance that can be done in two ways.

byteArr = str.getBytes(Charset.forName("UTF-16"));

Second one byteArr = str.getBytes(StandardCharsets.UTF_16); can be used Java 7 onward.

That's all for the topic How to Convert String to Byte Array in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment