Java String Handling

Convert String to Byte array in Java example

Convert String to Byte array in Java example shows how to convert string to byte array using getBytes method of String class. Example also shows how to encode string to UTF-8 byte array.

How to convert String to byte array in Java?

Use getBytes method of String class to convert String to byte array.

getBytes method encodes the string into bytes using 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, behavior of this method is unspecified. It is always suggested to specify character set while converting string to byte array to avoid undesirable results.

How to encode String to UTF-8 byte array?

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

This method encodes the string to given character set, stores the result in 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,

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.