String to Bytes

Java-String to Bytes

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:

String to Bytes


Another Forms of getBytes Method

Other forms of getBytes() are also available. These are:

String to Bytes

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:

String to Bytes


Program

String to Bytes

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] + ", ");
        }
    }
}

Leave a Comment