I have declared a String variable in Kotlin as like.
var str: String
The Kotlin document contradict for mutability concept. As per document... var is mutable.
But for String it define as immutable.
So please clarify contradiction...
Actually, String variable
is mutable, but String Value
is Immutable.
Appreciate with @cricket_007
Let me Describe deeply what happened behind When you declare variable.
val string1 = "abcd"
val string2 = "abcd"
As Shown above image and Declaration.
-String pool is a special storage area in The Heap Memory.
-When a string is created
and if the string already exists
in the pool, the reference of the existing string will be returned
, instead of creating a new object and returning its reference.
-If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
-Now with above our example Value Assign to Variable String1 now we can use this variable.
also we can change the value
string1.renameTo("Hi This Is Test")
So What happen at behind in memory ?
->yes,
if "Hi This Is Test" this string available it will return a reference to "string1"
else it Create new space and give reference To "string1"
Actually, that's Why String called immutable.
Reference - Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With