Course contentsShow
← Java
Lesson 429 of 2,87010. Inheritance FundamentalsFree lesson

final Classes in the JDK: String and Wrappers

Examine why core classes like String, Integer, and Double are final and the consequences if they weren't.

final Classes in the JDK: String and Wrappers

What You'll Learn

You'll discover why critical Java classes like String, Integer, and Double are marked final and what chaos could ensue if they weren't.

Why String and Wrappers Are final

The Java Development Kit (JDK) marks several core classes as final to guarantee their behavior remains trustworthy and predictable. The most important examples are:

  • String – the class for text
  • Wrapper classes – Integer, Double, Boolean, Character, etc.

These classes are declared final, meaning no one can extend them. This isn't arbitrary—it's a deliberate security and reliability decision.

The Consequences If They Weren't final

Imagine if String could be subclassed. A malicious or careless programmer could create:

// This is NOT possible because String is final
public class EvilString extends String {
    // Could override equals() to always return true
    // Could change hashCode() behavior
    // Could break security checks
}

Security risks: Java's security model trusts that a String behaves like a String. File paths, passwords, and URLs rely on this. If you could override methods, you could break authentication or access controls.

Immutability guarantee: String is immutable. Subclasses could add mutable fields, violating assumptions throughout the JDK.

Performance optimizations: The JVM optimizes String and wrapper classes aggressively (string pooling, unboxing). Subclasses would break these optimizations.

The Same Logic for Wrappers

Classes like Integer and Double wrap primitive values. They're final to ensure:

  • Their numeric values remain consistent
  • Caching mechanisms (like Integer caching -128 to 127) work correctly
  • No subclass can add mutable state to these "value objects"

Key Takeaway: Core JDK classes like String and wrapper classes are final to preserve security, immutability guarantees, and performance optimizations—preventing subclasses from undermining the foundational contracts Java code depends upon.