What Is Character Encoding?
You'll learn: How character encoding bridges the gap between the text humans read and the binary data computers store.
The Fundamental Problem
Computers don't store letters, emoji, or punctuation marks—they store bytes (sequences of 0s and 1s). Character encoding is the mapping system that translates human-readable characters into byte sequences and back again.
Think of it like a bilingual dictionary: the character 'A' might map to byte value 65 in one encoding (ASCII), while the character 'é' requires multiple bytes in UTF-8. Without agreeing on which "dictionary" to use, the same bytes can be interpreted completely differently.
Why Encoding Matters for Text I/O
When you write text to a file or read from one, Java must:
- Encode characters into bytes (writing)
- Decode bytes back into characters (reading)
If you write with one encoding (say, UTF-8) but read with another (say, ISO-8859-1), you get mojibake—garbled text where "café" becomes "café". This is why specifying Charset explicitly in InputStreamReader and OutputStreamWriter is critical.
Common Encoding Systems
- ASCII: Maps 128 basic English characters (A-Z, digits, punctuation) to single bytes
- UTF-8: Variable-length encoding supporting all Unicode characters (1-4 bytes per character)—the modern standard
- UTF-16: Uses 2 or 4 bytes per character (Java's internal char representation)
- ISO-8859-1: Single-byte encoding for Western European languages
The same byte sequence [195, 169] represents "é" in UTF-8, but "é" in ISO-8859-1. The encoding is the key to interpreting the bytes correctly.
Key Takeaway: Character encoding is the essential translation layer between text and bytes—mismatching encodings when reading and writing causes data corruption, which is why you must always specify encoding explicitly in Java I/O operations.