Text encodings
What you will learn
Text is not the same as bytes. A charset maps between encoded bytes and Unicode text. Java String indexing uses UTF-16 code units; UTF-8 bytes and code points may have different counts. Select an explicit encoding at I/O boundaries and reject malformed input when correctness matters.
- Measure bytes, UTF-16 units and code points separately.
- Decode UTF-8 with an explicit error policy.
- Use Scanner, Formatter, StringJoiner and Properties for limited text tasks.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Compare three text lengths
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { String s = "Aé😀"; byte[] bytes = s.getBytes(StandardCharsets.UTF_8); System.out.println(s.length()); System.out.println(s.codePointCount(0, s.length())); System.out.println(bytes.length); System.out.println(new String(bytes, StandardCharsets.UTF_8).equals(s)); }}Expected output:
437trueThe emoji uses two UTF-16 units and four UTF-8 bytes; é uses two UTF-8 bytes.
Encoding and decoding
StandardCharsets.UTF_8 identifies UTF-8. String.getBytes(charset) and the String byte-array constructor use replacement behavior for malformed or unmappable input. For strict decoding, use a CharsetDecoder with REPORT for malformed and unmappable input; for strict encoding, use a CharsetEncoder. ByteBuffer.wrap is a bounded byte-array view; the one-shot decode reads the remaining bytes. Streaming buffers require additional state handling, covered later. Never infer encoding by guessing a locale.
Text size is not display width
String.length counts UTF-16 units; codePointCount counts Unicode code points. A supplementary code point occupies two UTF-16 units. Neither count measures grapheme clusters or terminal columns. A UTF-8 BOM is a format-level decision, not a generic instruction to strip arbitrary characters.
Small text utilities
StringJoiner adds separators and optional delimiters, not escaping. Scanner tokenizes using a regex delimiter; hasNextInt tests the next token without consuming it. After nextInt, nextLine can read the remaining line including an empty remainder. Formatter uses an explicit Locale for repeatable output. Properties.load(Reader) reads characters; load(InputStream) uses ISO-8859-1 with Unicode escapes. Use setProperty/getProperty, not arbitrary Object keys; properties format is not JSON. Use a Reader when UTF-8 is intended, and enforce byte and character bounds before parsing.
Reject malformed UTF-8
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { byte[] bad = {(byte) 0xC3, 0x28}; var decoder = StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); try { decoder.decode(ByteBuffer.wrap(bad)); } catch (CharacterCodingException e) { System.out.println("invalid UTF-8"); } System.out.println(new String(bad, StandardCharsets.UTF_8).contains("\uFFFD")); }}Expected output:
invalid UTF-8trueA strict decoder reports the malformed sequence; the convenience constructor substitutes replacement text.
Read tokens and format a report
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var joiner = new StringJoiner(" | ", "[", "]"); try (var scanner = new Scanner("12 7 stop").useLocale(Locale.ROOT); var formatter = new Formatter(Locale.ROOT)) { while (scanner.hasNextInt()) joiner.add(Integer.toString(scanner.nextInt())); formatter.format("%s: %04d", scanner.next(), 19); System.out.println(joiner); System.out.println(formatter); } }}Expected output:
[12 | 7]stop: 0019The scanner consumes only integer tokens, then reads the label. The formatter pads an integer; neither utility serializes structured data.
Read properties as characters
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var props = new Properties(); try (var reader = new StringReader("title=café\ncount=3\n")) { props.load(reader); } System.out.println(props.getProperty("title")); System.out.println(Integer.parseInt(props.getProperty("count"))); System.out.println(props.getProperty("mode", "safe")); }}Expected output:
café3safeProperties retains strings; integer conversion and missing-key defaults are application choices.
Common mistakes
Do not use String.length as a byte limit. Do not silently replace malformed bytes in identifiers or signed data. Do not treat Scanner delimiters or StringJoiner as JSON/CSV escaping.
Practice
Strictly decode the UTF-8 bytes of café and print the decoded value and byte count. Reject byte arrays longer than 32 bytes.
Expected output:
café5Compare your answer with the manual practice criteria.
Official reading: CharsetDecoder · Properties. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text encodings — knowledge check
Original regex, text and structured data questions. Java 21-compatible scope.
What does String.length count?
How can malformed UTF-8 be rejected?
What does Properties.load(InputStream) use?
Does hasNextInt consume a token?
Does StringJoiner escape JSON?