Java String getBytes() Method Example

1. Introduction

The Java String.getBytes() method is used to encode a string into a sequence of bytes and returns an array of bytes. This method is useful when you need to convert string data for external storage or transmission, particularly in a network or file operations. This tutorial will demonstrate how to use the getBytes() method.

Key Points

- getBytes() converts a string into a sequence of bytes using the platform's default charset unless specified otherwise.

- It returns a byte array.

- Useful for string manipulation in byte-oriented environments like file and network I/O.

2. Program Steps

1. Declare a string.

2. Convert the string to a byte array using getBytes().

3. Print the byte array.

3. Code Program

public class StringGetBytesExample {
    public static void main(String[] args) {
        // Declare a String
        String str = "Hello, Java!";
        // Get bytes from string
        byte[] byteArray = str.getBytes();
        // Print bytes
        System.out.print("Byte array: ");
        for (byte b : byteArray) {
            System.out.print(b + " ");
        }
    }
}

Output:

Byte array: 72 101 108 108 111 44 32 74 97 118 97 33

Explanation:

1. String str = "Hello, Java!": Declares and initializes a String variable str.

2. byte[] byteArray = str.getBytes(): Calls the getBytes() method on str to convert the string into a byte array.

3. Print statement inside a loop: Iterates over each byte in byteArray and prints it. The numbers represent the ASCII values of the characters in the string.


Comments