Skip to lesson

Character sets and UTF-8

I'm on:

Showing steps for Windows. They are marked “On Windows” below.

A file holds only bytes, never letters. A character set (charset, or encoding) is the rule that turns characters into bytes when you write and bytes back into characters when you read; if the two sides use different rules, a ₹ or a Hindi name turns into garbage.

How characters become bytes

A character set maps characters to bytes. UTF-8 is the standard one that can store every language's characters, and it should be named explicitly when reading or writing text.

Every character has a number in Unicode, the worldwide list of characters: A is U+0041, ₹ is U+20B9, क is U+0915. A charset decides which bytes store that number in a file.

Four characters and their UTF-8 bytes: A takes 1 byte (41), e with an accent 2 bytes (C3 A9), the rupee sign 3 bytes (E2 82 B9) and a smiling face 4 bytes (F0 9F 98 80). One character can be several bytes.

Example 1 · Bytes per character in UTF-8

BytesPerCharDemo.javaJava
import java.nio.charset.StandardCharsets;
public class BytesPerCharDemo {    static String hex(byte[] bytes) {        StringBuilder sb = new StringBuilder();        for (byte b : bytes) {            if (sb.length() > 0) {                sb.append(' ');            }            sb.append(String.format("%02X", b & 0xFF));        }        return sb.toString();    }
    public static void main(String[] args) {        String[] samples = {"A", "é", "₹", "क"}; // A, é, ₹, क        String[] names = {"A", "e with accent", "rupee sign", "Hindi ka"};        for (int i = 0; i < samples.length; i++) {            byte[] utf8 = samples[i].getBytes(StandardCharsets.UTF_8);            System.out.printf("%-14s U+%04X -> %d byte(s): %s%n",                    names[i], samples[i].codePointAt(0), utf8.length, hex(utf8));        }    }}
Output
A              U+0041 -> 1 byte(s): 41
e with accent  U+00E9 -> 2 byte(s): C3 A9
rupee sign     U+20B9 -> 3 byte(s): E2 82 B9
Hindi ka       U+0915 -> 3 byte(s): E0 A4 95

What this code does

  • Every character has a Unicode number, written U+ and hex digits. getBytes(StandardCharsets.UTF_8) turns it into the bytes UTF-8 stores: 1 byte for English letters, 2 for é, 3 for ₹ and Hindi letters.
  • \u20B9 in the source is a Unicode escape: Java reads it as the character ₹. Escapes keep the .java file plain English text, so it compiles the same on every computer.

UTF-8 is the charset used by almost all modern systems. It uses 1 byte for English letters and digits, 2 bytes for letters like é, and 3 bytes for ₹ and Hindi letters. So the number of bytes in a file is often more than the number of characters.

UTF-8 versus the old Windows default character set

windows-1252 (also shown as Cp1252) is the old charset of English Windows. It uses exactly one byte per character, so it has room for only 256 characters: English letters, digits and some European letters like é.

Example 2 · windows-1252 has no rupee sign

OldCharsetDemo.javaJava
import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;
public class OldCharsetDemo {    public static void main(String[] args) {        Charset win = Charset.forName("windows-1252");        String fee = "Fee ₹500, café"; // Fee ₹500, café
        byte[] utf8 = fee.getBytes(StandardCharsets.UTF_8);        byte[] old = fee.getBytes(win);        System.out.println("Characters: " + fee.length());        System.out.println("UTF-8 bytes: " + utf8.length);        System.out.println("windows-1252 bytes: " + old.length);
        String back = new String(old, win);        System.out.println("Same text back? " + back.equals(fee));        System.out.println("Rupee became: " + back.charAt(4));        System.out.println("e with accent kept? " + (back.charAt(13) == 'é'));    }}
Output
Characters: 14
UTF-8 bytes: 17
windows-1252 bytes: 14
Same text back? false
Rupee became: ?
e with accent kept? true

What this code does

  • windows-1252 uses exactly one byte per character, so it can hold only 256 different characters. é is one of them; ₹ is not.
  • A character the charset cannot hold is silently replaced by ? when encoding with getBytes. The rupee sign is lost for good; reading the bytes back cannot bring it back.

It has no rupee sign and no Hindi, Tamil or other Indian scripts. When Java encodes such a character into windows-1252 with getBytes, it quietly writes ? instead, and the real character is lost.

Predict the output

Predict the decoded text

Same bytes, different charset. What does each snippet print?

Round 1 of 2

UTF-8 bytes read back as windows-1252.

byte[] bytes = "é".getBytes(StandardCharsets.UTF_8);
String text = new String(bytes, Charset.forName("windows-1252"));
System.out.println(bytes.length + " " + text);

Default charset rules: Java 17 versus Java 18 and later

The default charset is the one Java uses when you do not name one. On Java 17 and older, it followed the operating system: usually windows-1252 on English Windows and UTF-8 on macOS and Linux. From Java 18 (JEP 400), it is UTF-8 everywhere.

On Windows

On Windows the default charset depends on your Java version and your system code page. Check what your Java uses. With Java 17 or older, file.encoding is often Cp1252 (windows-1252), which breaks UTF-8 files.

Windows PowerShell
PS C:\Users\Priya\java-practice> java -XshowSettings:properties -version 2>&1 | Select-String "file.encoding|native.encoding"    file.encoding = UTF-8
    native.encoding = Cp1252
Output from Java 18 or newer: file.encoding is UTF-8, while native.encoding shows the Windows code page.

Example 3 · What is the default charset here?

DefaultCharsetDemo.javaJava
import java.nio.charset.Charset;
public class DefaultCharsetDemo {    public static void main(String[] args) {        System.out.println("Java version: " + System.getProperty("java.version"));        System.out.println("Default charset: " + Charset.defaultCharset());        System.out.println("native.encoding: " + System.getProperty("native.encoding"));    }}
Sample output
Java version: 21.0.7
Default charset: UTF-8
native.encoding: Cp1252

What this code does

  • This sample run is Java 21 on an English Windows laptop. On Java 17 on the same laptop, the second line says windows-1252. On macOS and Linux both versions usually say UTF-8.
  • native.encoding (Java 17 and later) is the operating system's own setting. Since Java 18 it no longer decides the default charset; it is there for programs that really need the old behaviour.

This matters for older APIs that use the default: FileReader, FileWriter, String.getBytes(), new String(bytes) and Scanner on a file without a charset. The Files text methods (readString, readAllLines, writeString, write) are different: they always use UTF-8 unless you pass another charset.

Code that "works on my laptop" and garbles text on a classmate's Windows machine with Java 17 is almost always a default-charset bug.

MalformedInputException and garbled Hindi or rupee symbols

Reading with the wrong charset fails in one of two ways. MalformedInputException (a subclass of IOException) is thrown when the bytes are not valid in the charset you asked for, for example a windows-1252 file read with Files.readString, which expects UTF-8.

Example 4 · MalformedInputException: the file is not UTF-8

MalformedDemo.javaJava
import java.io.IOException;import java.nio.charset.Charset;import java.nio.charset.MalformedInputException;import java.nio.file.Files;import java.nio.file.Path;
public class MalformedDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("products.txt");        Charset win = Charset.forName("windows-1252");        // An old billing program saved this file in windows-1252        Files.writeString(file, "Café latte 120\n", win);
        try {            Files.readString(file); // reads as UTF-8        } catch (MalformedInputException e) {            System.out.println("UTF-8 read failed: " + e.getClass().getSimpleName());        }
        String text = Files.readString(file, win);        System.out.println("windows-1252 read worked: " + text.equals("Café latte 120\n"));
        Files.delete(file);    }}
Output
UTF-8 read failed: MalformedInputException
windows-1252 read worked: true

What this code does

  • In windows-1252, é is the single byte E9. In UTF-8 that byte must start a 3-byte group, and the next byte does not fit, so readString throws MalformedInputException (a subclass of IOException).
  • Reading with the charset the file was really saved in gives the correct text. The error is a good thing: it stops your program from working with broken text.

Example 5 · Garbled text: UTF-8 bytes read as windows-1252

GarbledDemo.javaJava
import java.io.IOException;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.stream.Collectors;
public class GarbledDemo {    static String codes(String s) {        return s.codePoints()                .mapToObj(c -> String.format("U+%04X", c))                .collect(Collectors.joining(" "));    }
    public static void main(String[] args) throws IOException {        Path file = Path.of("price.txt");        Files.writeString(file, "₹250", StandardCharsets.UTF_8); // ₹250
        String wrong = Files.readString(file, Charset.forName("windows-1252"));        System.out.println("Expected 4 characters, got " + wrong.length());        System.out.println("Codes: " + codes(wrong));
        String right = Files.readString(file, StandardCharsets.UTF_8);        System.out.println("Read as UTF-8: " + codes(right));
        Files.delete(file);    }}
Output
Expected 4 characters, got 6
Codes: U+00E2 U+201A U+00B9 U+0032 U+0035 U+0030
Read as UTF-8: U+20B9 U+0032 U+0035 U+0030

What this code does

  • The three UTF-8 bytes of ₹ are each read as a separate windows-1252 character: â, ‚ and ¹. On screen the price shows as ₹250. No exception is thrown, because every byte means something in windows-1252.
  • This garbled text is called mojibake. Hindi read the same wrong way turns into runs like न. Reading with the right charset gives the 4 correct characters.

The quieter failure is garbled text, also called mojibake: UTF-8 bytes read as windows-1252 are all "valid", so no error appears, but ₹250 becomes ₹250 and Hindi becomes runs like न. The cure is the same in both cases: read with the charset the file was really saved in.

Fix the error

Fix the MalformedInputException

The file was saved by an old program in windows-1252. Pick the line that reads it correctly.

Reading an old file with the default UTF-8.

Path file = Path.of("cafe-old.txt");
List<String> lines = Files.readAllLines(file);
System.out.println(lines);

Error

Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1

Always passing StandardCharsets.UTF_8

StandardCharsets.UTF_8 is a ready-made constant for the UTF-8 charset, in java.nio.charset. Pass it to every method that turns text into bytes or bytes into text: Files.writeString(path, text, StandardCharsets.UTF_8), Files.readString(path, StandardCharsets.UTF_8), text.getBytes(StandardCharsets.UTF_8) and new String(bytes, StandardCharsets.UTF_8).

Example 6 · Always passing StandardCharsets.UTF_8

Utf8RoundTripDemo.javaJava
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class Utf8RoundTripDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("greeting.txt");        String greeting = "नमस्ते ₹500"; // नमस्ते ₹500
        Files.writeString(file, greeting, StandardCharsets.UTF_8);        String back = Files.readString(file, StandardCharsets.UTF_8);
        byte[] bytes = greeting.getBytes(StandardCharsets.UTF_8);        String fromBytes = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("Characters: " + greeting.length());        System.out.println("Bytes on disk: " + Files.size(file));        System.out.println("File round trip OK: " + back.equals(greeting));        System.out.println("Byte round trip OK: " + fromBytes.equals(greeting));
        Files.delete(file);    }}
Output
Characters: 11
Bytes on disk: 25
File round trip OK: true
Byte round trip OK: true

What this code does

  • The 6 Hindi characters take 3 bytes each (18), the space 1, ₹ 3 and 500 3: 25 bytes for 11 characters.
  • Both sides name the same charset, so the text comes back exactly, on Java 17 or 21, on Windows or Linux. getBytes and new String get the charset too, because without it they use the default.

The code then behaves the same on Java 17 and 21, on Windows and Linux, and the reader can see which encoding the file uses. For a file from old software, use Charset.forName("windows-1252") to read it, then save it as UTF-8.

Next step

Check your understanding

12 quick questions