Video in progress
What problems come with char, byte and text encoding (UTF-8) in Java?
In Java, char is a 16-bit UTF-16 code unit and byte is 8 bits. When you convert text to bytes and back without naming the encoding, the platform's default encoding is used, and Uzbek o', g' or emoji come out broken. Always pass StandardCharsets.UTF_8 explicitly.
📖 Answer
Code you see a lot:
byte[] bytes = text.getBytes(); // which encoding? (platform-dependent before Java 18)
String back = new String(bytes);
Files.readString(path); // this is UTF-8: fine
new InputStreamReader(socket.getInputStream()); // the default encoding
The right way:
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String back = new String(bytes, StandardCharsets.UTF_8);
new InputStreamReader(in, StandardCharsets.UTF_8);
Since Java 18 (JEP 400), the default encoding is UTF-8 on all platforms, but spelling it out is still a good habit: older JVMs and external systems can differ.
UTF-16 subtleties:
String s = "😀";
s.length(); // 2: two chars (a surrogate pair)
s.codePointCount(0, s.length()); // 1: one character
When you cut text with substring, an emoji can be split in half and broken.
Other places:
- in an HTTP response,
Content-Type: application/json; charset=UTF-8; - in the database,
UTF8(in MySQL,utf8mb4: plainutf8doesn't store emoji); - for Excel to open a CSV correctly, you may need a UTF-8 BOM.
When limiting data length, don't mix up bytes and characters: in some databases VARCHAR(100) is measured in bytes.
Sign up to mark studied questions and save your progress.