String to Bytes
The getBytes( ) method of String is used to encode the string into a sequence of bytes using the platform’s default charset(UTF-8) and store the result into a new byte array. For example:
Another Forms of getBytes Method
Other forms of getBytes() are also available. These are:
These methods are used to encode the string into a sequence of bytes using the given charset or named charset and store the result into a new byte array. If the named charset does not support, then an UnsupportedEncodingException is thrown. For example:
Program
Program Source
import java.io.UnsupportedEncodingException; public class Javaapp { public static void main(String[] args) throws UnsupportedEncodingException { String str = "ABCDEFGH"; byte bytearray[] = str.getBytes(); System.out.println("Platform Default Encoding"); for (int i = 0; i < bytearray.length; i++) { System.out.print(bytearray[i] + ", "); } System.out.println(); byte bytearray2[] = str.getBytes("UTF-16BE"); System.out.println("UTF-16 Big Endian Encoding"); for (int i = 0; i < bytearray2.length; i++) { System.out.print(bytearray2[i] + ", "); } } }