Java String getBytes() example

In this guide, you will learn about the String getBytes() method in Java programming and how to use it with an example.

1. String getBytes() Method Overview

Definition:

The getBytes() method in Java's String class is used to encode a given String into a sequence of bytes using the platform's default charset, returning the resulting byte array.

Syntax:

There are two overloaded getBytes() methods:
1. str.getBytes()
2. str.getBytes(charset)

Parameters:

- No parameter for the first syntax.

- charset: A string defining the charset to be used to encode the string.

Key Points:

- The returned byte array length is the length of the character sequence multiplied by a number based on the charset used.

- If the charset is not supported, it throws an UnsupportedEncodingException.

- Useful when interfacing with systems that require byte data rather than strings, such as file I/O or network communication.

2. String getBytes() Method Example

public class GetBytesExample {
    public static void main(String[] args) {
        String sample = "Java";

        try {
            // Using default charset
            byte[] byteArray1 = sample.getBytes();
            System.out.println("Default charset encoded byte array: " + java.util.Arrays.toString(byteArray1));

            // Using UTF-8 charset
            byte[] byteArray2 = sample.getBytes("UTF-8");
            System.out.println("UTF-8 encoded byte array: " + java.util.Arrays.toString(byteArray2));

            // Using an unsupported charset
            byte[] byteArray3 = sample.getBytes("UnsupportedCharset");
            System.out.println("UnsupportedCharset encoded byte array: " + java.util.Arrays.toString(byteArray3));
        } catch (UnsupportedEncodingException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Default charset encoded byte array: [74, 97, 118, 97]
UTF-8 encoded byte array: [74, 97, 118, 97]
Error: Unsupported charset

Explanation:

In the example:

1. We first encode the string "Java" using the default charset. This often produces the same result as UTF-8 for English alphanumeric characters, as seen in the output.

2. Next, we encode "Java" using the "UTF-8" charset explicitly. The resulting byte array is shown.

3. Finally, we intentionally attempt to encode the string using an unsupported charset named "UnsupportedCharset". This leads to an exception, which is caught and displayed.

Related Java String Class method examples

Comments