I know that Java system treats a string as an immutable type because a string is always initialized with its fixed length. Another reason is Java want to make any strings in many safe threads, which is unmodified by any users. However, because I really want to learn a complete checklist of why Java's string is immutable, so I wonder if there are any other reasons along those above?
Asked
Active
Viewed 44 times
0
-
Here, [let me google that for you](https://www.google.com/search?q=why+are+java+strings+immutable&ie=utf-8&oe=utf-8) – crashmstr Feb 03 '16 at 06:21
-
Possible duplicate of [Why is String immutable in Java?](http://stackoverflow.com/questions/22397861/why-is-string-immutable-in-java) – Marcinek Feb 03 '16 at 06:30
1 Answers
1
One other reason is efficiency: If strings were mutable, every call to Class.getName
, System.getProperty
or basically any method that returns a string would always have to make a fresh copy. If they didn’t, you could do the following:
"".getClass().setCharAt(11, 'p')
And from that point on, the java.lang.String
class would be called java.lang.Spring
.

Roland Illig
- 40,703
- 10
- 88
- 121