Video in progress

Strong Junior 🧱 OOP and SOLID

Why was the `String` class designed to be `final` and immutable?

For security, caching and thread-safety. String is used everywhere: as a key, a file path, a URL, a password. If it could be modified, or inherited from to break its behavior, the whole platform would be unreliable.

📖 Answer

The reasons:

  • String pool. Literals share one object: "uz" and "uz" are the same object. If one place could modify it, it would change everywhere else.
  • Hash cache. String.hashCode() is computed once and stored in an internal field, so it is fast as a HashMap key. If it weren't immutable, the cache would go wrong.
  • Security. The class loader, file paths and permission checks take a String. If the value could change after the check but before use, that is a hole.
  • Thread-safety. Threads can share it without synchronization.

Why is final needed? If you could inherit from an immutable class, someone could write MutableString extends String and pass it to code that expects a String. final makes this guarantee solid.

The practical consequence: s += x in a loop creates a new object every time, so use StringBuilder. Storing a password in a String is also discouraged: you can't wipe it from memory, which is why some APIs take a char[].