String Immutability in Java Explained with Examples

0

1. String Immutability in Java

In Java, Strings are immutable.

Immutable means the value of a String cannot be changed after the String object is created.

If any modification is performed, Java creates a completely new String object instead of changing the existing one.


2. Why String Immutability is Used

Java uses immutable Strings to improve security, memory optimization, and performance.

  • a. Makes String objects secure
  • b. Helps String Pool memory optimization
  • c. Prevents accidental data modification
  • d. Makes Strings thread-safe
  • e. Improves caching and performance

3. Where String Immutability is Used

Immutable Strings are important in many real-world systems.

  • a. Database connection URLs
  • b. File paths
  • c. Usernames and passwords
  • d. Network connections
  • e. Web application configurations
  • f. Security-sensitive applications

4. Understanding String Immutability

Once a String object is created, its internal value cannot be modified.


4.1 Basic Example

public class Main {
    public static void main(String[] args) {

        String text = "Java";

        text.concat(" Programming");

        System.out.println(text);
    }
}

The output remains "Java" because concat() does not change the original object.


4.2 Storing the New String

To keep the updated value, the new String must be stored again.


public class Main {
    public static void main(String[] args) {

        String text = "Java";

        text = text.concat(" Programming");

        System.out.println(text);
    }
}

Here, concat() creates a new object and the variable now points to the updated String.


Most String methods return a new String object instead of modifying the existing object.


5. Memory Representation of Immutable Strings

When a String changes, Java creates another object in memory.


5.1 Step-by-Step Working

public class Main {
    public static void main(String[] args) {

        String name = "Java";

        name = name + " Language";

        System.out.println(name);
    }
}

The program works in multiple steps internally.

  • a. "Java" object is created
  • b. Java creates a new object "Java Language"
  • c. Variable name starts pointing to the new object
  • d. Old object becomes unused

5.2 Original Object Never Changes

The first String object always remains unchanged in memory.

This behavior is the main concept behind immutability.


6. Internal Working of Immutable Strings

Internally, Java stores String characters in a special structure.

The String class does not provide methods that directly modify this internal data.


6.1 Immutable Design

The String class is designed in such a way that its internal value remains fixed after object creation.


public final class String {

    private final byte[] value;

}

The internal character storage is final, so it cannot be modified directly after initialization.


Because Strings are immutable, Java can safely reuse String objects from the String Pool.


7. Advantages of String Immutability


7.1 Improved Security

Immutable Strings help protect sensitive information.

For example, database URLs and file paths cannot be changed accidentally after creation.


7.2 Better Memory Optimization

Because Strings cannot change, Java safely stores and reuses String literals from the String Pool.


public class Main {
    public static void main(String[] args) {

        String s1 = "Java";
        String s2 = "Java";

        System.out.println(s1 == s2);
    }
}

Both variables refer to the same object from the String Pool.


7.3 Thread Safety

Immutable objects are naturally thread-safe because their values cannot change.

Multiple threads can use the same String object without synchronization issues.


7.4 Safe Hashing

Strings are commonly used as keys in collections like HashMap.

Immutability ensures the hash value remains stable.


import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        HashMap map = new HashMap<>();

        map.put("Java", 100);

        System.out.println(map.get("Java"));
    }
}

If Strings were mutable, changing the key could break HashMap searching.


8. Performance Impact of Immutable Strings

Creating many new String objects repeatedly can reduce performance.


8.1 Problem with Repeated Concatenation

public class Main {
    public static void main(String[] args) {

        String result = "";

        for(int i = 1; i <= 5; i++) {
            result = result + i;
        }

        System.out.println(result);
    }
}

Every concatenation creates a new String object in memory.


Repeated String modification inside loops can create many unnecessary objects.


8.2 Better Alternative Using StringBuilder

For frequent modifications, Java provides StringBuilder.


public class Main {
    public static void main(String[] args) {

        StringBuilder builder = new StringBuilder();

        for(int i = 1; i <= 5; i++) {
            builder.append(i);
        }

        System.out.println(builder);
    }
}

StringBuilder modifies the same object instead of creating multiple new objects.


9. Common Beginner Mistakes


9.1 Assuming Original String Changes

public class Main {
    public static void main(String[] args) {

        String language = "Java";

        language.toUpperCase();

        System.out.println(language);
    }
}

The output remains "Java" because the returned String was not stored.


9.2 Creating Too Many Temporary Strings

Many beginners use + repeatedly inside loops.

This creates unnecessary temporary objects and reduces performance.


9.3 Confusing Reference Change with Object Change

A variable can point to another String object, but the original object itself never changes.


public class Main {
    public static void main(String[] args) {

        String text = "Java";

        text = "Python";

        System.out.println(text);
    }
}

The variable now points to a new object, while the old object still exists in memory until garbage collection.


10. Important Points to Remember

  • a. Strings are immutable in Java
  • b. String modification creates new objects
  • c. Original String objects never change
  • d. Immutability improves security and memory optimization
  • e. String Pool works efficiently because of immutability
  • f. StringBuilder is better for repeated modifications

String immutability is one of the most important concepts in Java because it affects memory usage, security, thread safety, and application performance. Understanding how immutable Strings behave helps developers write optimized, safe, and efficient Java programs.

Post a Comment

0Comments
Post a Comment (0)