What is immutability mean in Java?

Immutability in Java means that once an object is created, its state cannot be modified. Any operation that appears to change the object actually creates a new object instead of altering the existing one. Immutable objects provide better security, thread safety, and reliability.

Key Points: • The state of an immutable object cannot be changed after creation. • Any modification results in the creation of a new object. • Immutable objects are inherently thread-safe because their state never changes. • Immutability helps prevent accidental data modification. • The String class is the most common example of an immutable class in Java.

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

Code Example:

public class Demo {

    public static void main(String[] args) {

        String str1 = "Java";

        String str2 = str1.concat(" Programming");

        System.out.println(str1);
        System.out.println(str2);
    }
}

Output:

Java Java Programming

Characteristics of an Immutable Class:

• Class is often declared final • Fields are private and final • No setter methods are provided • Fields are initialized through the constructor • Internal state cannot be modified after object creation

Benefits of Immutability:

• Thread safety • Better security • Easier debugging • Reliable object state • Safe sharing between multiple threads

Interview Tip: A concise interview answer is:

"Immutability means an object's state cannot be changed after it is created. Instead of modifying the existing object, Java creates a new object with the updated value. Immutable objects are thread-safe, secure, and easier to maintain."