Skip to content

Convert String to Byte array in Java example

Convert string to byte array in Java example shows how to convert string to a byte array using the getBytes method of the String class using the UTF-8 encoding.

How to convert string to byte array in Java?

Use the getBytes method of the String class to convert the string.

The getBytes method encodes the string into bytes using the default character set of the platform and returns the byte array.

Output

Important Note:

If the string cannot be encoded in the platform’s default character set, the behavior of this method is unspecified. It is always suggested to specify character set while converting to avoid undesirable results.

How to encode the string to UTF-8 byte array?

As given in the above example, getBytes method encodes the string to the default character set of the platform. It may produce undesirable results if the string cannot be converted to a byte array using the default character set. Use the getBytes method which accepts the character set parameter while converting the string.

This method encodes the string to the given character set, stores the result in a byte array and returns it. It replaces malformed characters and characters which cannot be mapped in the target character set with the default replacement.

Output

If you are using Java 7 or later version, you can use,

Instead of,

This example is a part of the String in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.