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.

Output

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.

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

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

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

3 Comments

  1. I need to to thank you for this wonderful read!! I absolutely enjoyed every little bit of it.
    I’ve got you saved as a favorite to check out new things you post…

  2. Ƭhis is my firѕt tіmе pay a quick visit at here аnd і am in fact happy to гead all at alоne pⅼace.

  3. I love what you guys are usually up too. This kind of clever work and coverage!
    Keep up the fantastic works guys I’ve included you guys to
    our blogroll.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.