Why is String immutable in Java?

Immutable means the object can not be changed after it is created. Methods like toUpperCase() give a new String. The reasons Java designed it this way:

  • String pool: equal literals share one object, which saves memory.
  • Security: strings are used for file names, URLs and passwords, and nobody can change them after the check.
  • Thread safety: many threads can share a string without any lock.
  • Hash code caching: a string keeps its hash code, so it is fast as a key in a HashMap.
public class Main {
    public static void main(String[] args) {
        String s = "java";
        s.concat(" 25");              // the result is lost
        System.out.println(s);
        s = s.concat(" 25");          // keep the new object
        System.out.println(s);
    }
}
Output

java
java 25


Learn more about the similar topics:
Tutorials
Java Strings
Java String Methods
Java StringBuilder and Text Blocks
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Interview Questions & Answers
What is the difference between == and equals() in Java?
Why is String immutable in Java?
What is the difference between String, StringBuilder and StringBuffer?
What is the string pool in Java and what does intern() do?