Java String getBytes() Method (original) (raw)

Last Updated : 29 Nov, 2024

In Java, the **getBytes() method of the String class converts a string into an array of bytes. This method is useful for encoding the strings into binary format, which can then be used for file I/O, network transmission, or encryption. It can be used with the default character set or with a specified charset.

**Example:

The below example shows how the getBytes() method converts a string into bytes using the platform’s default character set.

Java `

// Java program to demonstrate the getBytes() // with default charset public class GetBytes {

public static void main(String[] args) {
  
    // Define a string
    String s = "GeeksforGeeks";

    // Convert the string to a byte array
    byte[] ba = s.getBytes();

    for (byte b : ba) {
        System.out.print(b + " "); 
    }
}

}

`

Output

71 101 101 107 115 102 111 114 71 101 101 107 115

**Explanation: In the above example, the **getBytes()**method converts each character of the string into its corresponding ASCII value in bytes. The for-each loop is used to print each byte in the array.

**Syntax of getBytes() Method

public byte[] **getBytes();

**Return Type: Returns a newly created byte array that contains the encoded sequence of bytes.

Example of String getBytes() Method Using Specified Charset in Java

Now let us implement and accept the charset according to which string has to be encoded while conversion into bytes. There are many charset defined in the Charset class.

Java `

// Java Program to Demonstrate // Working of getByte() Method import java.nio.charset.StandardCharsets;

public class GetBytes {

public static void main(String[] args) {
  
    String s = "Geeks for Geeks";

    // Convert the string to a byte array 
    // using UTF-8
    byte[] ba1 = s.getBytes(StandardCharsets.UTF_8);

    // Convert the string to a byte array 
    // using UTF-16
    byte[] ba2 = s.getBytes(StandardCharsets.UTF_16);

    System.out.println("Byte Array (UTF-8): " + java.util.Arrays.toString(ba1));
    System.out.println("Byte Array (UTF-16): " + java.util.Arrays.toString(ba2));
}

}

`

Output

Byte Array (UTF-8): [71, 101, 101, 107, 115, 32, 102, 111, 114, 32, 71, 101, 101, 107, 115] Byte Array (UTF-16): [-2, -1, 0, 71, 0, 101, 0, 101, 0, 107, 0, 115, 0, 32, 0, 102, 0, 111, 0, 114, 0, 32, 0...

Explanation: In the above example, we have used different charsets to see how characters are encoded into bytes. TheUTF-8** encodes characters using variable-length bytes. The UTF-16 uses two bytes for most characters.