Library contents

Java String.getBytes

Encode text into bytes before storing it or passing it to a byte-oriented service.

A simple example

String.getBytes

  1. Start with "é"
  2. Do this Encode in UTF-8
  3. Result 2 bytes
This single precomposed letter uses the bytes C3 and A9 in hexadecimal.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("é".getBytes(java.nio.charset.StandardCharsets.UTF_8).length);
    }
}
Output
2

Syntax

Java syntax
public void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
JDK 21 method signatures (4)
@Deprecated public void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
public byte[] getBytes(Charset charset)
public byte[] getBytes()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Measure an accented receipt in transit

A receipt contains a letter with an accent and must pass through a byte-limited interface. Measure its encoded representation so the transmission code reserves enough room for the complete text.

From the programString item = "café"
Result5
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String item = "café";
        System.out.println(item.getBytes(java.nio.charset.StandardCharsets.UTF_8).length);
    }
}
Output
5

The final letter occupies two UTF-8 bytes, giving five bytes for four letters.

Advertisements

Send a locker code as bytes

A small device accepts an encoded label with a byte limit. Work with its actual encoding to determine what will be transmitted when the text contains more than plain ASCII.

From the programString locker = "A1"
Result[65, 49]
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String locker = "A1";
        System.out.println(java.util.Arrays.toString(locker.getBytes(java.nio.charset.StandardCharsets.US_ASCII)));
    }
}
Output
[65, 49]

The receiver gets the ASCII codes for the letter A and digit one.

Count the bytes on a café tag

The word café ends in a precomposed accented character. Trace a UTF-8 round trip. How many bytes carry this label before it is decoded back to the original text?

Givencafé · UTF-8
Worked result5

What to watch for

Specify UTF-8 for a portable format. The deprecated range-copy overload discards information for many characters.

Documentation for String.getBytes