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 or U+20AC for €. A charset, or encoding, is the rule that turns code points into bytes and back. The same text has different bytes in different charsets, and nothing in the bytes says which charset was used, so the reader must know it.

Inside the JVM, a String is a sequence of UTF-16 code units: char values of 16 bits. Code points above U+FFFF, such as most emoji, need two of them, a surrogate pair. Since Java 9 (JEP 254, compact strings) a string whose characters all fit in Latin-1 is stored with one byte per character, but that is invisible to your code. Charsets matter only at the edges, where text becomes bytes for a file, a socket, a database or a hash.

Common charsets
CharsetBytes per characterCoversTypical use
US-ASCII1128 characters: English letters, digits, punctuationProtocols and identifiers
ISO-8859-1 (Latin-1)1The first 256 code pointsOld Western European files; HTTP/1.1 headers
windows-12521Latin-1 with printable characters such as € in 0x80 to 0x9FFiles from older Windows programs
UTF-81 to 4All of Unicode; ASCII stays one byteThe default everywhere today: files, the web, JSON
UTF-16, UTF-16BE, UTF-16LE2 or 4All of UnicodeWindows APIs, Java and JavaScript internals
UTF-324All of UnicodeRare; fixed width
Java APIs that convert between text and bytes
APISinceBest for
s.getBytes(charset), new String(bytes, charset)Java 6 (Charset overloads)Small, complete pieces of text
StandardCharsets.UTF_8 and friendsJava 7Naming a charset without a checked exception
InputStreamReader, OutputStreamWriterJava 1.1Streams of bytes, such as sockets
Files.readString, Files.writeStringJava 11Whole files
CharsetEncoder, CharsetDecoderJava 1.4Strict error handling, buffers, byte limits
UTF-8 as the default charsetJava 18 (JEP 400)Code that does not pass a charset

The programs were compiled and run on JDK 21 with -Dstdout.encoding=UTF-8, so the console shows non-ASCII output correctly.

The same characters in different charsets

The program encodes one character from each size class of UTF-8: A (1 byte), é (2), € (3), and the musical G clef U+1D11E (4), which lies outside the Basic Multilingual Plane just like most emoji.

Java
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:

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é €
  • A is the byte 0x41 in every single-byte charset and in UTF-8, which is why ASCII text survives most charset mistakes.
  • é is one byte, 0xE9, in Latin-1 and windows-1252, but two bytes, C3 A9, in UTF-8. US-ASCII cannot represent it, so getBytes silently wrote 0x3F, a question mark.
  • € 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 ?.
  • UTF-16 without an order suffix writes a byte order mark, FE FF, before the text, so even A takes 4 bytes. UTF-16BE and UTF-16LE write none.
  • 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.

Java
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:

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 0, so ASCII is unchanged.
  • Longer sequences start with a lead byte that says how many bytes follow: 110 for two, 1110 for three, 11110 for four. Every following byte starts with 10 and carries 6 bits of the code point. For é, U+00E9 is binary 11 101001, which becomes 11000011 10101001.
  • 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 "hi". Strip a leading U+FEFF yourself when reading files that may have one.

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.

Java
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:

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 <82>; windows-1252 shows it as ‚, 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 new String 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.
  • getBytes with a charset that lacks a character writes ?, also without any error.

Strict encoding and decoding

new String(bytes, cs) and getBytes(cs) always replace bad input silently. When data quality matters, a CharsetDecoder or CharsetEncoder can be told what to do instead. The input bytes contain a lone 0xE9 between ASCII words, a typical leftover of a Latin-1 file in a UTF-8 system.

Java
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:

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
  • CodingErrorAction.REPLACE inserts U+FFFD, which is what new String does. IGNORE drops the bad byte, leaving two spaces, which hides the problem completely.
  • REPORT throws MalformedInputException, a subclass of IOException, 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.
  • CharsetEncoder.canEncode checks whether a target charset can represent the text before you write it to a legacy system. A new encoder reports by default, so encode threw UnmappableCharacterException for the euro sign, while getBytes wrote ?.
  • Files.readString and Files.newBufferedReader also use reporting decoders, while InputStreamReader replaces. The reading 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) and new PrintStream(out), use the default charset. The program prints the defaults and the system properties behind them, then reads a UTF-8 file with the right and a wrong charset.

Java
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:

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), Charset.defaultCharset() and file.encoding 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.
  • native.encoding, added in Java 17, keeps the operating system's charset for code that really needs it. Running with -Dfile.encoding=COMPAT brings back the pre-18 behaviour during a migration.
  • stdout.encoding, listed as a standard property in the System.getProperties documentation of current JDKs, is the charset of System.out, which still follows the console. On a console that is not UTF-8, printing non-ASCII text shows ?, which is why these programs set -Dstdout.encoding=UTF-8. sun.jnu.encoding is used for file names.
  • 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.
  • Charset.forName accepts aliases such as latin1 and utf8, and ignores case. This JDK supports 173 charsets, but only the six in StandardCharsets are guaranteed on every Java platform.

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.

Java
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:

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 new String broke the second euro sign, whose bytes were split between two chunks, into two replacement characters.
  • An InputStreamReader 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 a Reader or a CharsetDecoder, never chunk by chunk.
  • truncateUtf8 lets a CharsetEncoder 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.
  • 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

Choosing the right charset handling
SituationDo this
Converting text to bytes or backPass StandardCharsets.UTF_8 explicitly
Reading a file from an older Windows programTry windows-1252 rather than ISO-8859-1
Bad bytes must not pass silentlyA CharsetDecoder with CodingErrorAction.REPORT, or Files.readString
Text arriving as a streamInputStreamReader with a charset, never new String per chunk
Limit in bytes, such as a column sizeTruncate with a CharsetEncoder into a sized ByteBuffer
Text read as Latin-1 that should have been UTF-8Repair with new String(s.getBytes(ISO_8859_1), UTF_8)
Files that may start with a BOMRemove a leading U+FEFF after decoding
Console shows ? for non-ASCII outputRun with -Dstdout.encoding=UTF-8 on a UTF-8 terminal

For how a String stores characters and code points, see characters in a string; for writing files, see writing a text file.