0

How String in java is immutable?

Suppose the followin piece of code: String s = "Abhi"; s = "Dimri"; we can do this java but according to this String is mutable but it is said that String is immutable.

28th Oct 2020, 6:53 AM
Abhishek Dimri
Abhishek Dimri - avatar
3 Answers
+ 3
s = "Dimri"; didn't change the string, but allocate a new string and assign it to s. Therefore if your program needs to change lots of strings, you should use StringBuilder or StringBuffer.
28th Oct 2020, 7:09 AM
CarrieForle
CarrieForle - avatar
+ 1
Immutable in the sense you can't do any operations on that... For ex, s="Abhi" You can't do s[0]='k' since string is immutable.. You can't perform any string operations.. Hope you understood
28th Oct 2020, 6:55 AM
sarada lakshmi
sarada lakshmi - avatar
+ 1
String is immutable, it means that the class is final so you cannot extend it. Now that been said, a string is made immutable because you might create multiple references to a single value and modification in one will modify all and it could be disastrous. In your case you have simply created 2 different strings in the String Constant Pool. The variable 's' initially refers to "Abhi" but in the next line you are creating a new string and using 's' to refer to that. Now 's' points to "Dimri" which means that String "Abhi" is lost now, never to be recovered and could only be destroyed during garbage collection.
28th Oct 2020, 8:45 AM
Avinesh
Avinesh - avatar