Charsets and Encoding
A Java String holds characters, but files, sockets and databases hold bytes, and a charset is the rule that converts between them. This page shows the bytes that common charsets produce and how UTF-8 lays them out, reproduces and repairs garbled text, uses strict decoders, explains the defaults that changed in Java 18, and handles characters split across byte boundaries.
Contents
Characters, code points and bytes
Unicode gives every character a number called a code point, written U+0041 for A€
Inside the JVM, a Stringchar
| Charset | Bytes per character | Covers | Typical use |
|---|---|---|---|
| US-ASCII | 1 | 128 characters: English letters, digits, punctuation | Protocols and identifiers |
| ISO-8859-1 (Latin-1) | 1 | The first 256 code points | Old Western European files; HTTP/1.1 headers |
| windows-1252 | 1 | Latin-1 with printable characters such as € | Files from older Windows programs |
| UTF-8 | 1 to 4 | All of Unicode; ASCII stays one byte | The default everywhere today: files, the web, JSON |
| UTF-16, UTF-16BE, UTF-16LE | 2 or 4 | All of Unicode | Windows APIs, Java and JavaScript internals |
| UTF-32 | 4 | All of Unicode | Rare; fixed width |
| API | Since | Best for |
|---|---|---|
s.getBytes(charset)new String(bytes, charset) | Java 6 (Charset | Small, complete pieces of text |
StandardCharsets.UTF_8 | Java 7 | Naming a charset without a checked exception |
InputStreamReaderOutputStreamWriter | Java 1.1 | Streams of bytes, such as sockets |
Files.readStringFiles.writeString | Java 11 | Whole files |
CharsetEncoderCharsetDecoder | Java 1.4 | Strict error handling, buffers, byte limits |
| UTF-8 as the default charset | Java 18 (JEP 400) | Code that does not pass a charset |
The programs were compiled and run on JDK 21 with -Dstdout.encoding=UTF-8
The same characters in different charsets
The program encodes one character from each size class of UTF-8: Aé€
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
public class BytesAndChars {
public static void main(String[] args) {
HexFormat hex = HexFormat.ofDelimiter(" ");
Charset[] charsets = {StandardCharsets.US_ASCII, StandardCharsets.ISO_8859_1,
Charset.forName("windows-1252"), StandardCharsets.UTF_8,
StandardCharsets.UTF_16BE, StandardCharsets.UTF_16, Charset.forName("UTF-32")};
// One character from each "size class" of UTF-8
String[] samples = {"A", "\u00E9", "\u20AC", "\uD834\uDD1E"};
String[] names = {"A U+0041", "e-acute U+00E9", "euro U+20AC", "G clef U+1D11E"};
for (int i = 0; i < samples.length; i++) {
System.out.printf("%-16s chars=%d%n", names[i], samples[i].length());
for (Charset cs : charsets) {
byte[] b = samples[i].getBytes(cs);
System.out.printf(" %-12s %2d bytes %s%n",
cs.name(), b.length, hex.formatHex(b));
}
}
// Decoding with the same charset restores the text; a missing character becomes '?'
String word = "caf\u00E9 \u20AC";
byte[] latin1 = word.getBytes(StandardCharsets.ISO_8859_1);
System.out.println("ISO-8859-1 round trip: "
+ new String(latin1, StandardCharsets.ISO_8859_1));
byte[] utf8 = word.getBytes(StandardCharsets.UTF_8);
System.out.println("UTF-8 round trip: " + new String(utf8, StandardCharsets.UTF_8));
}
}
Output:
A U+0041 chars=1
US-ASCII 1 bytes 41
ISO-8859-1 1 bytes 41
windows-1252 1 bytes 41
UTF-8 1 bytes 41
UTF-16BE 2 bytes 00 41
UTF-16 4 bytes fe ff 00 41
UTF-32 4 bytes 00 00 00 41
e-acute U+00E9 chars=1
US-ASCII 1 bytes 3f
ISO-8859-1 1 bytes e9
windows-1252 1 bytes e9
UTF-8 2 bytes c3 a9
UTF-16BE 2 bytes 00 e9
UTF-16 4 bytes fe ff 00 e9
UTF-32 4 bytes 00 00 00 e9
euro U+20AC chars=1
US-ASCII 1 bytes 3f
ISO-8859-1 1 bytes 3f
windows-1252 1 bytes 80
UTF-8 3 bytes e2 82 ac
UTF-16BE 2 bytes 20 ac
UTF-16 4 bytes fe ff 20 ac
UTF-32 4 bytes 00 00 20 ac
G clef U+1D11E chars=2
US-ASCII 1 bytes 3f
ISO-8859-1 1 bytes 3f
windows-1252 1 bytes 3f
UTF-8 4 bytes f0 9d 84 9e
UTF-16BE 4 bytes d8 34 dd 1e
UTF-16 6 bytes fe ff d8 34 dd 1e
UTF-32 4 bytes 00 01 d1 1e
ISO-8859-1 round trip: café ?
UTF-8 round trip: café €
is the byte 0x41 in every single-byte charset and in UTF-8, which is why ASCII text survives most charset mistakes.A is one byte, 0xE9, in Latin-1 and windows-1252, but two bytes, C3 A9, in UTF-8. US-ASCII cannot represent it, soé silently wrote 0x3F, a question mark.getBytes is missing from Latin-1 but is 0x80 in windows-1252. Text labelled Latin-1 that contains euro signs was almost always written as windows-1252.€- The G clef is 2 chars in Java but 4 bytes in UTF-8, 4 in UTF-16BE (D8 34 DD 1E, the surrogate pair) and 4 in UTF-32. In single-byte charsets the whole pair became one
.? without an order suffix writes a byte order mark, FE FF, before the text, so evenUTF-16 takes 4 bytes.A andUTF-16BE write none.UTF-16LE- The last two lines show the loss: after a Latin-1 round trip, the euro sign is a question mark for good. UTF-8 round-trips any text.
How UTF-8 lays out the bits
UTF-8 is a variable-length code, and knowing its layout explains most encoding errors. The program implements the rules by hand for the same four code points and checks the result against the JDK, then looks at byte order marks.
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HexFormat;
public class Utf8Layout {
public static void main(String[] args) {
int[] codePoints = {0x41, 0xE9, 0x20AC, 0x1D11E};
for (int cp : codePoints) {
byte[] mine = encode(cp);
byte[] jdk = new String(Character.toChars(cp)).getBytes(StandardCharsets.UTF_8);
StringBuilder bits = new StringBuilder();
for (byte b : mine) {
String s = Integer.toBinaryString(b & 0xFF);
bits.append("0".repeat(8 - s.length())).append(s).append(' ');
}
System.out.printf("U+%05X %-36s same as JDK: %b%n",
cp, bits, Arrays.equals(mine, jdk));
}
// Byte order marks
HexFormat hex = HexFormat.ofDelimiter(" ");
System.out.println("\"A\" in UTF-16: "
+ hex.formatHex("A".getBytes(StandardCharsets.UTF_16)));
byte[] withBom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'h', 'i'};
String decoded = new String(withBom, StandardCharsets.UTF_8);
System.out.printf("UTF-8 with BOM: %d chars, first is U+%04X, equals(\"hi\"): %b%n",
decoded.length(), (int) decoded.charAt(0), decoded.equals("hi"));
String stripped = decoded.startsWith("\uFEFF") ? decoded.substring(1) : decoded;
System.out.println("after removing U+FEFF, equals(\"hi\"): " + stripped.equals("hi"));
}
// The UTF-8 rules: 1 to 4 bytes, with the code point's bits spread over them
static byte[] encode(int cp) {
if (cp < 0x80) {
return new byte[] {(byte) cp};
} else if (cp < 0x800) {
return new byte[] {(byte) (0xC0 | cp >> 6), (byte) (0x80 | cp & 0x3F)};
} else if (cp < 0x10000) {
return new byte[] {(byte) (0xE0 | cp >> 12), (byte) (0x80 | cp >> 6 & 0x3F),
(byte) (0x80 | cp & 0x3F)};
}
return new byte[] {(byte) (0xF0 | cp >> 18), (byte) (0x80 | cp >> 12 & 0x3F),
(byte) (0x80 | cp >> 6 & 0x3F), (byte) (0x80 | cp & 0x3F)};
}
}
Output:
U+00041 01000001 same as JDK: true
U+000E9 11000011 10101001 same as JDK: true
U+020AC 11100010 10000010 10101100 same as JDK: true
U+1D11E 11110000 10011101 10000100 10011110 same as JDK: true
"A" in UTF-16: fe ff 00 41
UTF-8 with BOM: 3 chars, first is U+FEFF, equals("hi"): false
after removing U+FEFF, equals("hi"): true
- Code points below 0x80 are one byte starting with
, so ASCII is unchanged.0 - Longer sequences start with a lead byte that says how many bytes follow:
for two,110 for three,1110 for four. Every following byte starts with11110 and carries 6 bits of the code point. For10 , U+00E9 is binary 11 101001, which becomesé 00011110 101001.10 - Because lead bytes and continuation bytes look different, a decoder can tell when a sequence is broken, which is how it detects that bytes are not valid UTF-8. A single-byte charset cannot detect anything: every byte is some character.
- Some Windows tools write a UTF-8 byte order mark, EF BB BF. Java's UTF-8 decoder keeps it as the character U+FEFF, so the decoded text has 3 characters and is not equal to
. Strip a leading U+FEFF yourself when reading files that may have one."hi"
Mojibake: garbled text, and when it can be repaired
Decoding bytes with the wrong charset produces garbled text, called mojibake. The test string has three accented letters and a euro sign, so every UTF-8 sequence length except 4 appears in it.
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class Mojibake {
public static void main(String[] args) {
String original = "na\u00EFve r\u00E9sum\u00E9 \u20AC5";
byte[] utf8 = original.getBytes(StandardCharsets.UTF_8);
// UTF-8 bytes decoded as a single-byte charset: each multi-byte char becomes 2 or 3
String asLatin1 = new String(utf8, StandardCharsets.ISO_8859_1);
String asCp1252 = new String(utf8, Charset.forName("windows-1252"));
System.out.println("original: " + original + " (" + original.length() + ")");
System.out.println("read as ISO-8859-1: "
+ visible(asLatin1) + " (" + asLatin1.length() + ")");
System.out.println("read as windows-1252: " + asCp1252 + " (" + asCp1252.length() + ")");
// This kind of damage can be undone: encode back with the wrong charset, decode right
String repaired = new String(asLatin1.getBytes(StandardCharsets.ISO_8859_1),
StandardCharsets.UTF_8);
System.out.println("repaired: "
+ repaired + " equals: " + repaired.equals(original));
// Single-byte bytes decoded as UTF-8 are invalid and become U+FFFD: lost for good
byte[] latin1 = "r\u00E9sum\u00E9".getBytes(StandardCharsets.ISO_8859_1);
String replaced = new String(latin1, StandardCharsets.UTF_8);
System.out.println("Latin-1 read as UTF-8: " + replaced.replace("\uFFFD", "<U+FFFD>"));
byte[] again = replaced.getBytes(StandardCharsets.UTF_8);
System.out.println("bytes after the round trip: " + again.length + " (was " + latin1.length
+ "), original bytes recoverable: false");
// Encoding a character the charset does not have gives '?'
System.out.println("euro as US-ASCII: "
+ new String("\u20AC5".getBytes(StandardCharsets.US_ASCII), StandardCharsets.US_ASCII));
}
// Shows invisible C1 control characters (U+0080 to U+009F) as <XX>
static String visible(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
sb.append(c >= 0x80 && c <= 0x9F ? String.format("<%02X>",
(int) c) : String.valueOf(c));
}
return sb.toString();
}
}
Output:
original: naïve résumé €5 (15)
read as ISO-8859-1: naïve résumé â<82>¬5 (20)
read as windows-1252: naïve résumé €5 (20)
repaired: naïve résumé €5 equals: true
Latin-1 read as UTF-8: r<U+FFFD>sum<U+FFFD>
bytes after the round trip: 10 (was 6), original bytes recoverable: false
euro as US-ASCII: ?5
- UTF-8 bytes read as Latin-1 turn each 2-byte letter into two characters, such as
foré , and the 3-byte euro sign into three. The 15-character text became 20 characters. In Latin-1 the byte 0x82 is an invisible control character, shown here asé ; windows-1252 shows it as<82> , giving the familiar‚ .€ - This direction can be repaired, because Latin-1 maps every byte to exactly one character and back. Encoding the garbled text as Latin-1 gives the original UTF-8 bytes, and decoding those as UTF-8 restores the original text.
- The other direction loses data. In Latin-1 bytes,
is the lone byte 0xE9, which is invalid UTF-8, soé replaced it with U+FFFD, the replacement character. The original byte is gone, and encoding the result again gives 10 bytes instead of the original 6.new String with a charset that lacks a character writesgetBytes , also without any error.?
Strict encoding and decoding
new String(bytes, cs)getBytes(cs)CharsetDecoderCharsetEncoder
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnmappableCharacterException;
public class StrictCoding {
public static void main(String[] args) {
byte[] bad = {'o', 'k', ' ', (byte) 0xE9, ' ', 'e', 'n', 'd'}; // 0xE9 alone is not UTF-8
for (CodingErrorAction action : new CodingErrorAction[] {CodingErrorAction.REPLACE,
CodingErrorAction.IGNORE, CodingErrorAction.REPORT}) {
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(action)
.onUnmappableCharacter(action);
try {
String text = decoder.decode(ByteBuffer.wrap(bad)).toString();
System.out.printf("decode %-8s -> [%s]%n",
action, text.replace("\uFFFD", "<FFFD>"));
} catch (MalformedInputException e) {
System.out.printf("decode %-8s -> MalformedInputException, length %d at byte %d%n",
action, e.getInputLength(), indexOfBad(bad));
} catch (CharacterCodingException e) {
System.out.println("decode " + action + " -> " + e);
}
}
// Encoders: check before writing to a legacy system
CharsetEncoder ascii = StandardCharsets.US_ASCII.newEncoder();
System.out.println("canEncode(\"price 5\"): " + ascii.canEncode("price 5"));
System.out.println("canEncode(\"price \u20AC5\"): " + ascii.canEncode("price \u20AC5"));
try {
ascii.encode(CharBuffer.wrap("price \u20AC5"));
} catch (UnmappableCharacterException e) {
System.out.println("strict encode: UnmappableCharacterException, length "
+ e.getInputLength());
} catch (CharacterCodingException e) {
System.out.println("strict encode: " + e);
}
byte[] lossy = "price \u20AC5".getBytes(StandardCharsets.US_ASCII);
System.out.println("String.getBytes instead: "
+ new String(lossy, StandardCharsets.US_ASCII));
}
static int indexOfBad(byte[] b) {
for (int i = 0; i < b.length; i++) {
if ((b[i] & 0xFF) >= 0x80) {
return i;
}
}
return -1;
}
}
Output:
decode REPLACE -> [ok <FFFD> end]
decode IGNORE -> [ok end]
decode REPORT -> MalformedInputException, length 1 at byte 3
canEncode("price 5"): true
canEncode("price €5"): false
strict encode: UnmappableCharacterException, length 1
String.getBytes instead: price ?5
inserts U+FFFD, which is whatCodingErrorAction.REPLACE does.new String drops the bad byte, leaving two spaces, which hides the problem completely.IGNORE throwsREPORT , a subclass ofMalformedInputException , with the length of the bad sequence. The exception does not say where the bad byte is; the program finds it with a scan for the first non-ASCII byte, at offset 3.IOException checks whether a target charset can represent the text before you write it to a legacy system. A new encoder reports by default, soCharsetEncoder.canEncode threwencode for the euro sign, whileUnmappableCharacterException wrotegetBytes .? andFiles.readString also use reporting decoders, whileFiles.newBufferedReader replaces. TheInputStreamReaderreading text files page has a table of which API does what.
Default charsets and Java 18
Methods that take no charset, such as getBytes()new String(bytes)new FileReader(file)new PrintStream(out)
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class Defaults {
public static void main(String[] args) throws IOException {
// Since Java 18 (JEP 400) the default charset is UTF-8 on every platform
System.out.println("Charset.defaultCharset(): " + Charset.defaultCharset());
for (String key : new String[] {"file.encoding", "native.encoding", "stdout.encoding",
"sun.jnu.encoding"}) {
System.out.printf("%-17s %s%n", key, System.getProperty(key));
}
Path file = Files.createTempFile("greeting", ".txt");
Files.writeString(file, "Gr\u00FC\u00DFe, \u4E16\u754C", StandardCharsets.UTF_8);
System.out.println("10 chars, bytes on disk: " + Files.size(file));
System.out.println("read as UTF-8: "
+ Files.readString(file, StandardCharsets.UTF_8));
try {
Files.readString(file, StandardCharsets.US_ASCII);
} catch (IOException e) {
System.out.println("read as US-ASCII: " + e.getClass().getSimpleName());
}
Files.delete(file);
// Names: lookups are case-insensitive and accept aliases
System.out.println("forName(\"latin1\"): " + Charset.forName("latin1"));
System.out.println("forName(\"utf8\"): " + Charset.forName("utf8"));
System.out.println("isSupported(\"EBCDIC-XY\"): " + Charset.isSupported("EBCDIC-XY"));
System.out.println("available charsets: " + Charset.availableCharsets().size());
}
}
Output:
Charset.defaultCharset(): UTF-8
file.encoding UTF-8
native.encoding UTF-8
stdout.encoding UTF-8
sun.jnu.encoding UTF-8
10 chars, bytes on disk: 15
read as UTF-8: Grüße, 世界
read as US-ASCII: MalformedInputException
forName("latin1"): ISO-8859-1
forName("utf8"): UTF-8
isSupported("EBCDIC-XY"): false
available charsets: 173
- Since Java 18 (JEP 400),
andCharset.defaultCharset() are UTF-8 on every operating system. Before, they came from the operating system's locale, which was usually windows-1252 on Western Windows machines. Code that relied on the default worked on Linux and garbled text on Windows.file.encoding , added in Java 17, keeps the operating system's charset for code that really needs it. Running withnative.encoding brings back the pre-18 behaviour during a migration.-Dfile.encoding=COMPAT , listed as a standard property in thestdout.encoding documentation of current JDKs, is the charset ofSystem.getProperties , which still follows the console. On a console that is not UTF-8, printing non-ASCII text showsSystem.out , which is why these programs set? .-Dstdout.encoding=UTF-8 is used for file names.sun.jnu.encoding- The file holds 10 characters in 15 bytes:
andü take 2 bytes each and the two Chinese characters 3 each. Reading it as US-ASCII threwß .MalformedInputException accepts aliases such asCharset.forName andlatin1 , and ignores case. This JDK supports 173 charsets, but only the six inutf8 are guaranteed on every Java platform.StandardCharsets
Even with UTF-8 as the default, pass the charset explicitly. It documents intent and keeps code correct on older JVMs.
Characters split across byte boundaries
Network reads and buffers deliver bytes in chunks that ignore character boundaries, and database columns are often limited in bytes rather than characters. The test text has three euro signs, each 3 bytes, so 4-byte chunks and small byte limits are sure to land inside one.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
public class ByteBoundaries {
public static void main(String[] args) throws IOException {
String text = "\u20AC10 \u20AC20 \u20AC30"; // each euro sign is 3 bytes
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
System.out.println(text.length() + " chars, " + bytes.length + " bytes");
// Wrong: decoding each 4-byte chunk on its own cuts characters in half
StringBuilder wrong = new StringBuilder();
InputStream in = new ByteArrayInputStream(bytes);
byte[] chunk = new byte[4];
int n;
while ((n = in.read(chunk)) > 0) {
wrong.append(new String(chunk, 0, n, StandardCharsets.UTF_8));
}
System.out.println("chunk by chunk: " + wrong.toString().replace("\uFFFD", "?")
+ " equals: " + wrong.toString().equals(text));
// Right: a Reader keeps the unfinished bytes until the rest arrives
StringBuilder right = new StringBuilder();
try (Reader r = new InputStreamReader(new ByteArrayInputStream(bytes),
StandardCharsets.UTF_8)) {
char[] buf = new char[4];
while ((n = r.read(buf)) > 0) {
right.append(buf, 0, n);
}
}
System.out.println("with a Reader: "
+ right + " equals: " + right.toString().equals(text));
// Truncate to a byte limit, such as a database column size, without breaking a char
for (int limit : new int[] {8, 9, 10}) {
String cut = truncateUtf8(text, limit);
System.out.printf("first %2d bytes: %-10s (%d bytes)%n", limit, cut,
cut.getBytes(StandardCharsets.UTF_8).length);
}
byte[] naive = java.util.Arrays.copyOf(bytes, 8);
System.out.println("naive 8-byte cut: "
+ new String(naive, StandardCharsets.UTF_8).replace("\uFFFD", "?"));
}
// The encoder stops before a character that does not fit in the buffer
static String truncateUtf8(String s, int maxBytes) {
CharsetEncoder enc = StandardCharsets.UTF_8.newEncoder();
CharBuffer chars = CharBuffer.wrap(s);
enc.encode(chars, ByteBuffer.allocate(maxBytes), true);
return s.substring(0, chars.position());
}
}
Output:
11 chars, 17 bytes
chunk by chunk: €10 ??20 €30 equals: false
with a Reader: €10 €20 €30 equals: true
first 8 bytes: €10 (6 bytes)
first 9 bytes: €10 € (9 bytes)
first 10 bytes: €10 €2 (10 bytes)
naive 8-byte cut: €10 ?
- Decoding each 4-byte chunk with
broke the second euro sign, whose bytes were split between two chunks, into two replacement characters.new String - An
keeps the incomplete bytes of a character until the next read supplies the rest, so the same 4-byte reads produced the correct text. Always decode a stream with aInputStreamReader or aReader , never chunk by chunk.CharsetDecoder lets atruncateUtf8 fill a byte buffer of the limit's size. The encoder never writes part of a character, so with 8 bytes it stopped after 6, before the euro sign that would not fit.CharsetEncoder- Cutting the byte array at 8 instead left two bytes of a euro sign, which decode to a replacement character. A database may reject such a value or store it corrupted.
Rules for working with charsets
| Situation | Do this |
|---|---|
| Converting text to bytes or back | Pass StandardCharsets.UTF_8 |
| Reading a file from an older Windows program | Try windows-1252 |
| Bad bytes must not pass silently | A CharsetDecoderCodingErrorAction.REPORTFiles.readString |
| Text arriving as a stream | InputStreamReadernew String |
| Limit in bytes, such as a column size | Truncate with a CharsetEncoderByteBuffer |
| Text read as Latin-1 that should have been UTF-8 | Repair with new String(s.getBytes(ISO_8859_1), UTF_8) |
| Files that may start with a BOM | Remove a leading U+FEFF after decoding |
Console shows ? | Run with -Dstdout.encoding=UTF-8 |
For how a String