Emoji show why encoded size is not the same as codePointCount or UTF-16 length().
java
import java.nio.charset.StandardCharsets;
public class GetBytesLength {
public static void main(String[] args) {
String text = "Hi😀";
byte[] utf8 = text.getBytes(StandardCharsets.UTF_8);
System.out.println("length() = " + text.length());
System.out.println("UTF-8 bytes = " + utf8.length);
}
}
Output
length() = 4
UTF-8 bytes = 6
How It Works
Map the string.H and i are one UTF-16 unit each; 😀 is a surrogate pair → length() 4.
Encode as UTF-8. Letters stay 1 byte each; the emoji becomes 4 bytes.
Total bytes. 1 + 1 + 4 = 6.
Pick the right metric. Use byte length for buffers/files; use code points for “character” limits.
Example 3 — Encode Then Decode
Round-trip with the same charset. Decoding with a different encoding can corrupt text— see also String.format when you only need a display string, not bytes.
java
import java.nio.charset.StandardCharsets;
public class GetBytesRoundTrip {
public static void main(String[] args) {
String original = "Café 😀";
byte[] data = original.getBytes(StandardCharsets.UTF_8);
String back = new String(data, StandardCharsets.UTF_8);
System.out.println(back);
System.out.println("same = " + original.equals(back));
}
}
Output
Café 😀
same = true
How It Works
Start with Unicode text. Includes accented letters and an emoji.
Encode to UTF-8 bytes. Safe, portable binary form.
Decode with UTF-8.new String(data, UTF_8) rebuilds the text.
Compare.equals is true when encode/decode charsets match.
Frequently Asked Questions
getBytes() encodes a string into a byte array.
The platform default charset. Prefer an explicit charset instead.
UTF-8 is portable and standard for files, APIs, and network data.
A byte[] with the encoded characters.
Calling getBytes on null throws NullPointerException.