Java String.getBytes
Encode text into bytes before storing it or passing it to a byte-oriented service.
A simple example
String.getBytes
- Start with "é"
- Do this Encode in UTF-8
- Result 2 bytes
class Main {
public static void main(String[] args) throws Exception {
System.out.println("é".getBytes(java.nio.charset.StandardCharsets.UTF_8).length);
}
}
2
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.javaMeasure 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.
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);
}
}
5
The final letter occupies two UTF-8 bytes, giving five bytes for four letters.
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.
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)));
}
}
[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?
What to watch for
Specify UTF-8 for a portable format. The deprecated range-copy overload discards information for many characters.