Charset UTF-8 Byte Roundtrip

Encode the same string to UTF-8, UTF-16, and ISO-8859-1 and compare byte counts: UTF-8 roundtrips faithfully while unmappable chars degrade to ?.

JavaData Integrity

Code

snippet
import java.nio.charset.StandardCharsets;

public class ByteBoundary {

    public static void main(String[] args) {
        String label = "café 你好";

        // 同一字符串在不同 charset 下字节数完全不同
        byte[] utf8 = label.getBytes(StandardCharsets.UTF_8);
        byte[] utf16 = label.getBytes(StandardCharsets.UTF_16);
        System.out.println("chars: " + label.length()
                + " utf8: " + utf8.length + "B utf16: " + utf16.length + "B");

        // UTF-8 无损往返
        System.out.println("utf8 roundtrip: "
                + new String(utf8, StandardCharsets.UTF_8).equals(label));

        // ISO-8859-1 表达不了的字面量降级为 '?':编码即丢失,解码回不来
        byte[] latin1 = label.getBytes(StandardCharsets.ISO_8859_1);
        System.out.println("latin1 bytes: " + latin1.length);
        System.out.println("latin1 decoded: [" + new String(latin1, StandardCharsets.ISO_8859_1) + "]");
    }
}

How the snippet works

The working surface is the class ByteBoundary and the function main — everything else is wiring.

Using it

Running the file prints labeled results such as chars:, utf8 roundtrip:, latin1 bytes: — each operation’s effect is visible in the output.

Key statements

byte[] latin1 = label.getBytes(StandardCharsets.ISO_8859_1);
byte[] utf16 = label.getBytes(StandardCharsets.UTF_16);
byte[] utf8 = label.getBytes(StandardCharsets.UTF_8);

Interactive Tools for This Topic

FAQ

What does Charset UTF-8 Byte Roundtrip print when run?
Run it as a complete program — the output lines carry labels such as `chars:`, `utf8 roundtrip:`, `latin1 bytes:`.