Java Character Encodings: UTF-8, Charsets and the Default Encoding
Understand how Java turns characters into bytes: how UTF-8 and UTF-16 encode code points, byte order marks, the Charset class and StandardCharsets, mojibake and strict decoders, UTF-8 as the default since Java 18, file.encoding and the stdout, stderr and stdin encodings, and reading code points.
kvi5hnuCode Sprout team member11 min readOn this page
Every time text crosses the boundary between a Java program and the outside world, through a file, a socket, the console or a byte array, characters must become bytes or bytes must become characters. The rules for that conversion are a character encoding, which Java represents as a Charset. Get it wrong and José turns into José. This article explains the common encodings, how to name them in Java, what the defaults are, and how to read text that contains characters beyond the basic ones.
Code points and encodings
Unicode assigns every character a number, its code point, written U+ followed by hex digits: A is U+0041, é is U+00E9, € is U+20AC and 😀 is U+1F600. Code points go up to U+10FFFF, so they need 21 bits. An encoding is a way to package these numbers into bytes.
UTF-8
UTF-8 encodes each code point in one to four bytes:
| Code points | Bytes | Bit pattern |
|---|---|---|
| U+0000 to U+007F | 1 | 0xxxxxxx |
| U+0080 to U+07FF | 2 | 110xxxxx 10xxxxxx |
| U+0800 to U+FFFF | 3 | 1110xxxx 10xxxxxx 10xxxxxx |
| U+10000 to U+10FFFF | 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
The x positions hold the bits of the code point. The design has nice properties. ASCII text is unchanged, one byte per character, which makes English text compact. A byte starting with 10 is always a continuation byte, so a program can resynchronize after an error. And bytes from multi-byte sequences never look like ASCII characters such as / or ". UTF-8 is the encoding of the web, of most source code and of nearly all modern files.
UTF-16
UTF-16 uses one 16-bit unit for code points up to U+FFFF, and two units, a surrogate pair, for the rest. The first unit comes from the range U+D800 to U+DBFF (a high surrogate), the second from U+DC00 to U+DFFF (a low surrogate), and together they carry the 20 bits of (code point − 0x10000). Java strings use UTF-16 internally, which is why "😀".length() is 2: the emoji is one code point but two chars.
Since UTF-16 units are two bytes, there are two byte orders. Big-endian puts the more significant byte first (U+2122 becomes 21 22). Little-endian reverses them (22 21). A file may start with a byte order mark (BOM), the character U+FEFF, which reads as FE FF in big-endian and FF FE in little-endian and so reveals the order. Java's UTF_16 charset writes a big-endian BOM when encoding and honors a BOM when decoding. UTF_16BE and UTF_16LE use a fixed order and no BOM.
Legacy encodings
Before Unicode took over, each region had its own encodings covering a limited set of characters. ISO 8859-1 (Latin-1) is one byte per character for Western European languages. Windows-1252 is a close relative. Shift_JIS is a variable-length encoding for Japanese. You still meet these in old files and systems.
There's no reliable way to detect the encoding of a byte sequence automatically. The encoding must come from somewhere else: a protocol header such as HTTP's Content-Type, a declaration inside the file such as XML's <?xml ... encoding="..."?>, or an agreement. When in doubt, use UTF-8 and document it.
The Charset class
A java.nio.charset.Charset object represents an encoding. The StandardCharsets class has constants for the encodings every Java implementation must support:
UTF_8, UTF_16, UTF_16BE, UTF_16LE, ISO_8859_1 and US_ASCII. Since Java 22, UTF_32, UTF_32BE and UTF_32LE are there as well.
For other encodings, look them up by name with Charset.forName("Shift_JIS"), or with Charset.forName(name, fallback) (Java 18), which returns a fallback instead of throwing. Charset.availableCharsets() returns a sorted map of all encodings the JVM supports.
Pass a Charset wherever you convert between bytes and text:
var str = new String(bytes, StandardCharsets.ISO_8859_1);
byte[] data = str.getBytes(StandardCharsets.UTF_8);
var reader = new InputStreamReader(in, StandardCharsets.UTF_8);
Many older methods also accept the encoding name as a String. Prefer the Charset overloads with StandardCharsets constants. A typo in a constant is a compile-time error, and a typo in a string is an UnsupportedEncodingException at runtime.
Mojibake and malformed input
Decoding with the wrong charset produces garbage known as mojibake. The UTF-8 bytes of José are 4A 6F 73 C3 A9. Read as ISO 8859-1, each byte becomes its own character, giving José. Seeing à followed by another accented character is a telltale sign of UTF-8 decoded as Latin-1.
When encoding, characters that don't exist in the target charset are replaced, usually by ?. When decoding, invalid byte sequences become the replacement character U+FFFD (�). new String(...) and getBytes always do this silently. To detect bad data instead, use a CharsetDecoder with CodingErrorAction.REPORT, which throws a MalformedInputException:
CharBuffer chars = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes));
Files.readString and Files.readAllLines behave strictly too: they throw MalformedInputException if a file isn't valid in the given charset, typically when someone opens a Latin-1 file as UTF-8.
Default encodings
If you don't pass a charset, a default is used. Methods in java.nio.file, such as Files.readString, have always defaulted to UTF-8. Many older APIs use the default charset instead:
- the reader and writer classes in
java.io, such asInputStreamReader,FileReaderandPrintWriter new String(byte[])andString.getBytes()ScannerandFormatterURLEncoderandURLDecoder
Up to Java 17, the default charset was the operating system's native encoding. That was UTF-8 on Linux and macOS, but usually an archaic code page such as Windows-1252 on Windows, so the same program wrote different bytes on different systems. Since Java 18 (JEP 400), the default charset is UTF-8 everywhere.
Some related system properties:
native.encoding(Java 17) reports the operating system's encoding, whatever the default is.file.encodingselects the default charset. It'sUTF-8by default. Setting it toCOMPATon the command line (java -Dfile.encoding=COMPAT ...) restores the old native-encoding behavior for legacy applications. It must be set at startup. Changing it later withSystem.setPropertyhas no effect.stdout.encodingandstderr.encoding(Java 19) are used bySystem.outandSystem.err, which arePrintStreams that must encode characters. They default to the console's encoding, which on Windows may be an old code page such as cp437. Set them toUTF-8when redirecting output to a file.stdin.encoding(Java 25) is used for decodingSystem.inby theIOandConsoleclasses.Scanner(System.in)still uses the default charset unless you pass one.
Run java -XshowSettings:properties -version and look for the properties ending in .encoding to see your settings. The demo prints Charset.defaultCharset(), which is UTF-8 on Java 18 and later unless COMPAT is in effect.
Reading character input
Parsers for JSON, XML or your own formats usually read input one character at a time. Use a BufferedReader for efficiency and call read(), which returns a char (a UTF-16 code unit) or -1. If you care about whole code points, combine surrogate pairs yourself:
int ch = reader.read();
if (ch != -1 && Character.isHighSurrogate((char) ch)) {
int ch2 = reader.read();
if (ch2 != -1 && Character.isLowSurrogate((char) ch2))
ch = Character.toCodePoint((char) ch, (char) ch2);
else
throw new MalformedInputException(1);
}
The Character class classifies code points according to Unicode rules: isLetter, isDigit, isUpperCase, isLowerCase, isSpaceChar and, since Java 21, isEmoji and related methods. Others follow Java's own rules: isJavaIdentifierStart, isJavaIdentifierPart and isWhitespace. To turn code points back into a string, use StringBuilder.appendCodePoint, which appends one or two chars as needed.
A complete example
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
public class Solution {
static String hex(byte[] bytes) {
return HexFormat.ofDelimiter(" ").withUpperCase().formatHex(bytes);
}
// reads one code point from a reader, combining surrogate pairs
static int readCodePoint(Reader reader) throws IOException {
int ch = reader.read();
if (ch == -1 || !Character.isHighSurrogate((char) ch)) return ch;
int ch2 = reader.read();
if (ch2 == -1 || !Character.isLowSurrogate((char) ch2)) throw new MalformedInputException(1);
return Character.toCodePoint((char) ch, (char) ch2);
}
public static void main(String[] args) throws IOException {
String jose = "José";
System.out.println("UTF-8: " + hex(jose.getBytes(StandardCharsets.UTF_8)));
System.out.println("UTF-16BE: " + hex(jose.getBytes(StandardCharsets.UTF_16BE)));
System.out.println("UTF-16LE: " + hex(jose.getBytes(StandardCharsets.UTF_16LE)));
System.out.println("UTF-16: " + hex(jose.getBytes(StandardCharsets.UTF_16)) + " (starts with a BOM)");
System.out.println("ISO-8859-1: " + hex(jose.getBytes(StandardCharsets.ISO_8859_1)));
// bytes per character in UTF-8
for (String s : List.of("A", "é", "€", "😀"))
System.out.println(s + " U+" + Integer.toHexString(s.codePointAt(0)).toUpperCase()
+ " -> UTF-8 " + hex(s.getBytes(StandardCharsets.UTF_8)) + ", chars: " + s.length());
// decoding with the wrong charset gives mojibake
byte[] utf8 = jose.getBytes(StandardCharsets.UTF_8);
System.out.println("UTF-8 bytes read as ISO-8859-1: " + new String(utf8, StandardCharsets.ISO_8859_1));
// characters that don't exist in the target charset become '?'
System.out.println("€ in US-ASCII: " + new String("Price: 5€".getBytes(StandardCharsets.US_ASCII), StandardCharsets.US_ASCII));
// a strict decoder reports malformed input instead of replacing it
byte[] bad = { 'o', 'k', (byte) 0xC3 };
System.out.println("lenient decoding: " + new String(bad, StandardCharsets.UTF_8).replace("�", "<U+FFFD>"));
try {
StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bad));
} catch (CharacterCodingException e) {
System.out.println("strict decoding: " + e.getClass().getSimpleName());
}
// Java doesn't strip a UTF-8 byte order mark
byte[] withBom = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'h', 'i' };
String text = new String(withBom, StandardCharsets.UTF_8);
System.out.println("length with BOM: " + text.length() + ", starts with \\uFEFF: " + text.startsWith("\uFEFF"));
if (text.startsWith("\uFEFF")) text = text.substring(1);
System.out.println("after stripping: " + text);
// looking up charsets
System.out.println("forName(\"Shift_JIS\"): " + Charset.forName("Shift_JIS").name());
System.out.println("windows-1252 available: " + Charset.availableCharsets().containsKey("windows-1252"));
try {
Charset.forName("default");
} catch (UnsupportedCharsetException e) {
System.out.println("forName(\"default\"): UnsupportedCharsetException");
}
System.out.println("default charset: " + Charset.defaultCharset());
// reading code points from a reader
Reader reader = Reader.of("a€😀");
int cp;
var sb = new StringBuilder();
while ((cp = readCodePoint(reader)) != -1)
sb.append("U+").append(Integer.toHexString(cp).toUpperCase())
.append(Character.isEmoji(cp) ? "(emoji) " : " ");
System.out.println("code points: " + sb.toString().trim());
System.out.println("rebuilt: " + new StringBuilder().appendCodePoint(0x1F600).appendCodePoint('!'));
}
}
UTF-8: 4A 6F 73 C3 A9
UTF-16BE: 00 4A 00 6F 00 73 00 E9
UTF-16LE: 4A 00 6F 00 73 00 E9 00
UTF-16: FE FF 00 4A 00 6F 00 73 00 E9 (starts with a BOM)
ISO-8859-1: 4A 6F 73 E9
A U+41 -> UTF-8 41, chars: 1
é U+E9 -> UTF-8 C3 A9, chars: 1
€ U+20AC -> UTF-8 E2 82 AC, chars: 1
😀 U+1F600 -> UTF-8 F0 9F 98 80, chars: 2
UTF-8 bytes read as ISO-8859-1: José
€ in US-ASCII: Price: 5?
lenient decoding: ok<U+FFFD>
strict decoding: MalformedInputException
length with BOM: 3, starts with \uFEFF: true
after stripping: hi
forName("Shift_JIS"): Shift_JIS
windows-1252 available: true
forName("default"): UnsupportedCharsetException
default charset: UTF-8
code points: U+61 U+20AC U+1F600(emoji)
rebuilt: 😀!
The demo uses HexFormat (Java 17) to show the bytes. Notice the BOM FE FF in front of the UTF_16 encoding, and the four bytes and two chars of the emoji.
Common questions
How do I convert a file from Windows-1252 (or Latin-1) to UTF-8?
Decode with the old charset and encode with the new one: Files.writeString(target, Files.readString(source, Charset.forName("windows-1252")), StandardCharsets.UTF_8). For huge files, do the same line by line with a reader and a writer.
How many bytes does a string take in UTF-8?
text.getBytes(StandardCharsets.UTF_8).length. It differs from text.length(), which counts UTF-16 chars: "José" has 4 chars but 5 UTF-8 bytes, and "😀" has 2 chars but 4 bytes. Database column limits and protocol headers are often given in bytes, so this matters.
Why does the Windows console show ? or garbage for non-ASCII output?
The console uses an old code page such as 437 or 850, and characters it cannot display are replaced. Switch the console to UTF-8 with chcp 65001 and run Java with -Dstdout.encoding=UTF-8, or use Windows Terminal, which handles UTF-8 well. Writing to files with an explicit UTF-8 charset avoids the problem entirely.
Can I find out a file's encoding by looking at it?
Only heuristically. A BOM identifies UTF-8, UTF-16 and UTF-32 for certain. Strictly decoding as UTF-8 without errors makes UTF-8 very likely, because random legacy text is rarely valid UTF-8. Beyond that, guessing libraries such as ICU's CharsetDetector give a probability, not a guarantee.
Should I still pass StandardCharsets.UTF_8 now that it is the default?
Yes, in code that others will run or maintain. It documents the format, it protects you when someone starts the JVM with -Dfile.encoding=COMPAT, and it keeps the code correct on Java versions before 18.
Is a Java char a character?
Not always. A char is a UTF-16 code unit. Characters outside the Basic Multilingual Plane, such as most emoji, need two chars, and what users see as one character can consist of several code points. Count code points with codePointCount, and grapheme clusters with BreakIterator (article 75).
API reference
java.nio.charset.Charset
| Method | Description |
|---|---|
static Charset forName(String name), forName(String name, Charset fallback) (Java 18) | the charset with the given name or alias |
static SortedMap<String, Charset> availableCharsets() | all supported charsets by canonical name |
static Charset defaultCharset() | the default charset (UTF-8 since Java 18, unless COMPAT) |
String name(), Set<String> aliases() | the canonical name and its aliases |
CharsetEncoder newEncoder(), CharsetDecoder newDecoder() | configurable encoders and decoders |
java.nio.charset.StandardCharsets
| Constant | Encoding |
|---|---|
UTF_8, UTF_16, UTF_16BE, UTF_16LE | Unicode transformation formats |
UTF_32, UTF_32BE, UTF_32LE (Java 22) | 32-bit Unicode |
ISO_8859_1, US_ASCII | Latin-1 and 7-bit ASCII |
java.lang.String
| Method | Description |
|---|---|
String(byte[] bytes, Charset charset), String(byte[] bytes, int offset, int length, Charset charset) | decode bytes; invalid input becomes U+FFFD |
byte[] getBytes(Charset charset) | encode; unmappable characters are replaced |
java.lang.Character
| Method | Description |
|---|---|
static boolean isHighSurrogate(char ch), isLowSurrogate(char ch) | whether ch is the first or second half of a surrogate pair |
static int toCodePoint(char high, char low) | combines a surrogate pair into a code point |
static boolean isLetter(int codePoint), isDigit(int), isUpperCase(int), isLowerCase(int), isSpaceChar(int), isEmoji(int) (Java 21) | Unicode classifications |
static boolean isJavaIdentifierStart(int), isJavaIdentifierPart(int), isWhitespace(int) | Java-language classifications |
Summary
- An encoding maps Unicode code points to bytes. UTF-8 uses 1 to 4 bytes and keeps ASCII unchanged. UTF-16, which Java uses internally, uses one or two 16-bit units in big- or little-endian order.
- A BOM can mark UTF-16 byte order. Java doesn't strip a UTF-8 BOM, so remove a leading
\uFEFFyourself. - Use
Charsetobjects, preferablyStandardCharsetsconstants. The encoding of bytes can't be detected reliably, so it must be known. - The wrong charset produces mojibake. Lenient conversions replace bad data silently, while
CharsetDecoderwithREPORTand theFilesread methods throwMalformedInputException. - Since Java 18 the default charset is UTF-8.
native.encoding,file.encoding, thestdout,stderrand (Java 25)stdinencoding properties control the rest. - When reading characters, combine surrogate pairs into code points, and build strings with
appendCodePoint.
Practice Questions
How many bytes does "naïve €" take in UTF-8, and why?
- The letters
n,a,v,eand the space are ASCII and take one byte each (5 bytes).ï(U+00EF) is in the two-byte range and€(U+20AC) in the three-byte range. That's 5 + 2 + 3 = 10 bytes, which"naïve €".getBytes(StandardCharsets.UTF_8).lengthconfirms.
A user sees "München" instead of "München". What happened?
Text encoded in UTF-8 was decoded as ISO 8859-1 or Windows-1252. ü is C3 BC in UTF-8, and in Latin-1 those two bytes are à and ¼. Decode the bytes with StandardCharsets.UTF_8.
Your CSV parser fails to match the first column header "id" in a file exported from a spreadsheet program, although it looks correct. What's a likely cause?
The file starts with a UTF-8 byte order mark. Java's decoder keeps it, so the first header is "\uFEFFid", not "id". Strip a leading \uFEFF from the first line.
Why did new String(bytes) behave differently on Windows and Linux with Java 11 but not with Java 21?
Without a charset argument it uses the default charset. With Java 11 that was the platform encoding, typically Windows-1252 on Windows and UTF-8 on Linux. Since Java 18 the default is UTF-8 everywhere. Passing an explicit Charset avoids the issue in every version.
How do you make sure a program fails loudly instead of silently inserting U+FFFD when reading invalid UTF-8?
Decode with a CharsetDecoder configured with onMalformedInput(CodingErrorAction.REPORT), which throws MalformedInputException, or read files with Files.readString or Files.readAllLines, which report malformed input by default.
Previous: Java Text Input and Output: PrintWriter, BufferedReader and Saving Objects as Text
Next: Java DataInput and DataOutput: Reading and Writing Binary Data
Related reading
- Java Text Input and Output: PrintWriter, BufferedReader and Saving Objects as Text
- Java I/O Filters: Buffered, Data and Pushback Streams
- Java I/O Streams: Reading and Writing Bytes
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Primitive Streams: IntStream, LongStream and DoubleStream

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.