Friday, 4 July 2025

Why is String Immutable in Java?

 In Java, the String class is immutable, means once a String object is created, it cannot be changed. Any operation that seems to modify a string (like concat(), replace(), etc.) will instead create a new String object.


✅ Reasons Why String is Immutable

1. ๐Ÿ” Security

  • Strings are widely used in sensitive areas, like:

    • Network connections (URL, Socket)

    • File paths

    • Database credentials

    • Class loading (Class.forName("com.example.MyClass"))

  • If String were mutable, malicious code could change values after validation.

Example:

java
String className = "com.bank.Account"; Class.forName(className); // If mutable, could be changed to malicious class

2. ๐Ÿงต Thread Safety

  • Immutable objects are inherently thread-safe.

  • Multiple threads can access the same String object without synchronization.


3. ๐Ÿ’พ String Pooling (Interning)

  • Java maintains a String pool in the heap memory.

  • Immutability allows safe sharing of strings in memory:

    java
    String a = "hello"; String b = "hello"; System.out.println(a == b); // true — both refer to the same object

If String were mutable, modifying a would affect b too — breaking pooling.


4. ๐ŸŽฏ Caching HashCode

  • String's hashCode() is used in HashMap, HashSet, etc.

  • Since the content doesn't change, the hash can be calculated once and cached, improving performance.


5. ♻️ Consistent Behavior

  • You can safely pass strings between methods without worrying they’ll change:

    java
    void printMessage(String msg) { System.out.println(msg); } printMessage("Hello"); // caller’s string remains unaffected

๐Ÿงช Internal Example

java
String s1 = "Java"; s1.concat(" Rocks!"); System.out.println(s1); // Output: Java // Why? Because concat() returns a new object, not modifying s1

❗ If You Want Mutability

Use StringBuilder or StringBuffer:

java
StringBuilder sb = new StringBuilder("Java"); sb.append(" Rocks!"); System.out.println(sb.toString()); // Java Rocks!

๐Ÿง  Summary

ReasonExplanation
SecurityPrevent tampering of sensitive strings
Thread SafetySafe for concurrent use without locking
String PoolingReuse strings efficiently
Hash CachingPerformance boost in collections
ReliabilityStrings behave consistently everywhere

--------------------------

๐Ÿ”น Guidelines to Create an Immutable Class in Java

To create an immutable class, follow these rules:

Declare the class as final
→ Prevents subclasses from modifying behavior.

Declare all fields as private final
→ Prevents direct modification after initialization.

Do not provide setter methods
→ Ensures that fields cannot be modified.

Initialize fields only through the constructor
→ Provides controlled initialization.

Ensure defensive copying of mutable objects
→ Prevents external modification of internal mutable objects.

Example:
public final class Immutable {
    private final int value;
    public Immutable(int value) {
        this.value = value;
    }
    // Factory method to return an instance
    public Immutable instance(int value) {
        if (this.value == value) {
            return this; // Return the same instance if the value is unchanged
        } else {
            return new Immutable(value); // Create a new instance if the value is different
        }
    }
    // Getter method to access value (without modifying it)
    public int getValue() {
        return value;
    }

    public static void main(String[] args) {
        Immutable im1 = new Immutable(10);
        Immutable im2 = im1.instance(10);
        Immutable im3 = im1.instance(100);

        System.out.println(im1); // Immutable@de6ced
        System.out.println(im2); // Immutable@de6ced
        System.out.println(im3); // Immutable@c17164

        System.out.println(im1 == im2); // true (same instance reused)
        System.out.println(im1 == im3); // false (new instance created)
    }
}

No comments:

Post a Comment