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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.