Why is String immutable?

String is immutable in Java, which means that once a String object is created, its value cannot be changed. Any operation that appears to modify a String actually creates a new String object. This design improves security, performance, thread safety, and memory efficiency.

Key Points: • Immutability means the content of a String cannot be modified after creation. • String objects are safely shared through the String Pool because their values cannot change. • Immutable strings are inherently thread-safe and can be accessed by multiple threads without synchronization. • Immutability enhances security by preventing sensitive data such as file paths, database URLs, and network connections from being altered unexpectedly. • Hash codes can be cached because the String value never changes, improving the performance of collections like HashMap.

Example: When a String is modified using concatenation, Java creates a new object instead of changing the existing one.

Code Example:

public class Demo {

    public static void main(String[] args) {

        String str = "Java";

        str.concat(" Programming");

        System.out.println(str);

        str = str.concat(" Programming");

        System.out.println(str);
    }
}

Output:

Java Java Programming

Benefits of String Immutability:

• Improved security • Better thread safety • Efficient String Pool implementation • Reliable hash code caching • Simplified memory management

Interview Tip: A concise interview answer is:

"String is immutable in Java, meaning its value cannot be changed after creation. This design improves security, enables String Pool optimization, provides thread safety, and enhances performance through hash code caching and efficient memory management."