Video in progress

What unexpected problems can the fact that the default charset became UTF-8 in Java 18 (JEP 400) cause when upgrading a large system?

Every FileReader, new String(bytes) and getBytes() with no charset specified now uses UTF-8 and not the OS setting. Files on Windows or on servers with an old Linux locale, exchanges with legacy systems, and some tests give different results. Console output depends on a separate setting.

📖 Answer

In Java 17 and earlier, Charset.defaultCharset() came from the OS: usually UTF-8 on Linux, windows-1251 or windows-1252 on Windows, and US-ASCII in some Docker images because of the POSIX locale. In Java 18+ it's UTF-8 everywhere.

Where it breaks:

  • code that reads files that run on Windows or come from Windows (CSV exports, bank registries) without specifying a charset. Cyrillic text that used to be read correctly with windows-1251 now becomes ? or �;
  • exchange with a legacy system over a socket or a file: the encoding on its side hasn't changed;
  • hashes/signatures: an HMAC or checksum computed from text.getBytes() now comes from different bytes, so the signature doesn't match;
  • tests: tests that used to pass in CI (Linux, UTF-8) and fail on a developer's Windows machine now behave the other way around.

System.out doesn't depend on the default charset: it depends on stdout.encoding (a Java 19+ property) and the console. So the "garbled letters" problem in logs is a separate issue.

How I prepare:

  1. Find them. Search for calls without a charset: new String(byte[]), getBytes(), FileReader, FileWriter, InputStreamReader(in), Scanner(file), PrintStream. Error Prone's DefaultCharset check does this automatically.
  2. Make them explicit. StandardCharsets.UTF_8 everywhere, or another charset on purpose:
Files.readString(path, Charset.forName("windows-1251")); // a bank registry: by contract
  1. A temporary rollback. During the migration, -Dfile.encoding=COMPAT brings back the old behavior, but it's only a bridge, not a permanent solution.
  2. An early check. Running on Java 17 with -Dfile.encoding=UTF-8 and running the tests ahead of time shows the problems before you move to 18.

The long-term rule: every bytes-to-text conversion with the outside world is done with the charset stated explicitly, and documented as part of the contract.