How to convert String to Byte array in java

Sometimes, we need to convert String to byte array. We can use getBytes() method of String to do it,

Method syntax:

String getBytes Example:

When you run above program, you will get below output:

There is one more overloaded method for getBytes

Method syntax:

It encodes String to specified charset format. You can read about charset from http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html

Lets encode above String in charSet UTF-16LE and UTF-16BE

When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

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