Java.lang Package Classes

Java String - getBytes() Method



The java.lang.String.getBytes() method is used to encode this String into a sequence of bytes using the named charset, storing the result into a new byte array.

Syntax

public byte[] getBytes(String charsetName) 
                throws UnsupportedEncodingException                         

Parameters

charsetName Specify the name of a supported charset.

Return Value

Returns the resultant byte array.

Exception

Throws UnsupportedEncodingException, If the named charset is not supported.

Example:

In the example below, getBytes() method is used to encode the given String into a sequence of bytes using the given charset string.

import java.io.*;

public class MyClass {
  public static void main(String[] args) {
    String MyString = "HELLO";
    
    try{ 
      //encoding the string into a byte array
      String cs = "UTF-16BE";
      byte Arr[] = MyString.getBytes(cs);

      //printing the content of byte array
      System.out.print("UTF-16BE Charset encoding:");
      for(byte i: Arr)
        System.out.print(" " + i);
    }catch(UnsupportedEncodingException ex){
      System.out.println("Unsupported character set"+ex);
    }
  }
}

The output of the above code will be:

UTF-16BE Charset encoding: 0 72 0 69 0 76 0 76 0 79

❮ Java.lang - String