StandardCharsets: Common Encodings
You'll learn how to access Java's predefined, guaranteed-available character encodings through the StandardCharsets class.
The Problem with Charset by Name
In previous lessons, you've seen how to specify encodings like "UTF-8" or "US-ASCII" as strings. But there's a hidden danger: typos. If you write "UTF8" (missing the hyphen) or "utf-8" (wrong case in some contexts), you might get an UnsupportedEncodingException at runtime—an error that could have been caught at compile time.
Enter StandardCharsets
Java provides the StandardCharsets class (introduced in Java 7) with constant fields for the most common character encodings. These are guaranteed to be available on every JVM, and since they're compile-time constants, you'll catch mistakes immediately.
The most important constants:
StandardCharsets.UTF_8– The universal encoding you should use by defaultStandardCharsets.US_ASCII– Basic 7-bit ASCII (128 characters)StandardCharsets.ISO_8859_1– Latin-1, covering Western European charactersStandardCharsets.UTF_16,UTF_16BE,UTF_16LE– Various UTF-16 variants
Using StandardCharsets in Practice
Instead of passing a string:
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("file.txt"),
"UTF-8" // risky string literal
);
Use the constant:
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("file.txt"),
StandardCharsets.UTF_8 // type-safe, always available
);
Analogy: It's like using an enum instead of a magic string—the compiler enforces correctness, and you get autocomplete support from your IDE.
Key Takeaway: Always prefer StandardCharsets constants over string-based charset names—they're type-safe, guaranteed to exist, and prevent runtime encoding errors from typos.