+ 7
Why string is immutable in java?
5 Answers
+ 7
By using searchbar I found 2 questions with useful answers:
https://www.sololearn.com/Discuss/1005264/?ref=app
https://www.sololearn.com/Discuss/570524/?ref=app
+ 6
https://www.journaldev.com/802/string-immutable-final-java
https://www.baeldung.com/java-string-immutable
+ 5
Strings are immutable or final in java.
I will try to keep this simple-
They are 'immutable' because-
For eg- there are two users, user1 and user2 and both can can add a string to the string pool.
User1 writes-
String str = "hello";
// hello is stored in the string pool
User2 writes-
String str = "bye";
// Now 'hello' is replaced by 'bye' in the string pool.
Now the user1 comes and tries to retrieve the value of 'str' and is surprised to see the result because he stored 'hello' but it is giving him 'bye'.
So in order to avoid the above risk, Strings are made 'final' so that once it is created then you cannot alter it's value. One more reason is that they do not want the developer to override the methods and alter it's functionality.
+ 4
Once a string is created it can't be changed if you create another string and assign it to an existing variable the variable holding the reference will refer to a different object and the previous string will be garbage collected if not in use anywhere in the program.
+ 2
Use something like StringBuffer if you want to change it later.