Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java String getBytes() method
Syntax and Examples



Introduction

The getBytes() method in Java is a powerful tool for converting a String into an array of bytes. This is crucial when you need to work with strings at a lower level, like sending data over networks, writing to files that require specific encodings, or interacting with external APIs.

Syntax


public byte[] getBytes()

public byte[] getBytes(Charset charset)

public void getBytes(int srcBegin,
          int srcEnd,
          byte[] dst,
          int dstBegin)

Let's break down each variation:

  • getBytes(): Uses the platform’s default character encoding.
  • getBytes(Charset charset): Uses the specified charset to encode the string into bytes.
  • getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin): Encodes a portion of the string (from index srcBegin to srcEnd exclusive) and writes it into an existing byte array dst starting at index dstBegin.

Parameters Table

Parameter Description
charset The Charset to use for encoding the string. If null, the platform's default charset is used.
srcBegin The beginning index of the substring to encode (inclusive).
srcEnd The ending index of the substring to encode (exclusive).
dst The destination byte array where the encoded bytes will be written.
dstBegin The starting index in the dst array to write the encoded bytes.

Return Value

The method returns a byte[] containing the byte representation of the string.

Examples

Example 1: Using Default Encoding

This example demonstrates how to convert a String into an array of bytes using the default character encoding of your system. The exact encoding depends on your operating system and Java configuration.


import java.nio.charset.Charset;

public class GetBytesExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        byte[] byteArray = str.getBytes();

        System.out.println("Byte array: ");
        for (byte b : byteArray) {
            System.out.print(b + " ");
        }
        System.out.println();
    }
}

Byte array: 
72 101 108 108 111 44 32 87 111 114 108 100 33 

Explanation: The `getBytes()` method without any arguments uses the default character encoding. The output shows the numerical values of each byte in the resulting array.

Example 2: Using UTF-8 Encoding

This example demonstrates how to convert a String into an array of bytes using the UTF-8 character encoding, which is a widely used and versatile encoding.


import java.nio.charset.Charset;

public class GetBytesUTF8Example {
    public static void main(String[] args) {
        String str = "你好,世界!"; // Hello, World! in Chinese
        byte[] byteArray = str.getBytes("UTF-8");

        System.out.println("Byte array (UTF-8): ");
        for (byte b : byteArray) {
            System.out.print(b + " ");
        }
        System.out.println();
    }
}

Byte array (UTF-8): 
228 189 160 229 165 189 231 149 231 142 228 189 160 

Explanation: We explicitly specified the UTF-8 encoding using `str.getBytes("UTF-8")`. The resulting byte array now represents the Chinese characters in UTF-8 format.

Example 3: Writing to an Existing Byte Array

This example demonstrates how to use the third overload of getBytes() to encode a portion of a string and write it directly into an existing byte array. This can be useful for constructing messages or data packets.


import java.nio.charset.Charset;

public class GetBytesToByteArrayExample {
    public static void main(String[] args) {
        String str = "This is a test string.";
        byte[] byteArray = new byte[20]; // Allocate space for the substring

        str.getBytes(0, 4, byteArray, 0); // Encode the first 4 characters into byteArray starting at index 0

        System.out.println("Byte array: ");
        for (byte b : byteArray) {
            System.out.print(b + " ");
        }
        System.out.println();
    }
}

Byte array: 
84 72 73 73 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

Explanation: We extracted the first four characters (T, h, i, s) of the string and wrote them into the byteArray. Note that the rest of byteArray is filled with default values (zeroes in this case).



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M