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 given charset, storing the result into a new byte array.

Syntax

public byte[] getBytes(Charset charset)                       

Parameters

charset Specify the Charset to be used to encode the String.

Return Value

Returns the resultant byte array.

Exception

NA.

Example:

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

import java.lang.*;
import java.nio.charset.Charset; 

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

    //printing the content of byte array
    System.out.print("UTF-16 Charset encoding:");
    for(byte i: Arr)
      System.out.print(" " + i);
  }
}

The output of the above code will be:

UTF-16 Charset encoding: -2 -1 0 72 0 69 0 76 0 76 0 79

❮ Java.lang - String