+ 7

Why string is immutable in java?

2nd Feb 2020, 2:39 PM
Amit
Amit - avatar
4 Answers
2nd Feb 2020, 2:49 PM
Seb TheS
Seb TheS - avatar
+ 6
https://www.journaldev.com/802/string-immutable-final-java https://www.baeldung.com/java-string-immutable
2nd Feb 2020, 3:52 PM
Rstar
Rstar - avatar
+ 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.
2nd Feb 2020, 4:48 PM
Avinesh
Avinesh - avatar
+ 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.
2nd Feb 2020, 6:45 PM
D_Stark
D_Stark - avatar