Ignoring backward-compatibility constraints, would there be any real advantage to changing Java's String implementation from one final class with an internal `byte coder` field into a sealed hierarchy such as `public sealed class String permits Latin1String, Utf16String`? The subclasses could represent the different internal encodings and potentially avoid storing the coder field in every String instance. I'm wondering whether that could improve memory usage, enable better pattern matching or JIT optimizations, or make the implementation easier to maintain.
5 Answers
Probably not. String is already final, so callers already get the important guarantees: no subclassing, predictable behavior, and opportunities for aggressive optimization. Making the implementation a sealed hierarchy would not provide a useful public capability unless those subclasses were exposed, which would also leak an implementation detail that Java currently keeps private.
A better comparison is with runtimes that use several hidden internal string representations for optimization. Those representations can exist behind one public String abstraction without making users deal with multiple string types. Java already achieves much of that idea internally with compact strings, so exposing Latin1String and Utf16String would mostly add complexity rather than solve a problem for callers.
Sealed subclasses could make an exhaustive pattern switch possible, for example handling `Latin1String` and `Utf16String` without a default branch. That sounds neat, but it is a fairly thin benefit because the encoding is intentionally an internal implementation detail. Application code should generally care about characters and code points, not which storage format a particular String happens to use.
There are also compatibility problems. String has public constructors and is deeply embedded throughout the Java platform, so changing its concrete representation would be a much bigger undertaking than replacing an ordinary application class. Even if compatibility were ignored, the performance impact would need extensive testing because tiny costs in String operations affect almost every Java program.
The main theoretical benefit would be saving the coder field, since the subtype itself could identify whether the contents are Latin-1 or UTF-16. But that needs to be weighed against the cost of subtype checks, object layout, dispatch, and all the special handling required for the most frequently used class in Java. The existing compact-string design was measured carefully, and a field-based representation was found to be faster or otherwise preferable.

The compact-string representation arrived before sealed classes, so it is fair to wonder whether newer JVM optimizations could change the result. Still, String is so heavily special-cased that changing its design merely to use sealed classes would be unlikely to justify the engineering and compatibility costs.