Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is var str: String mutable or immutable?

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. var is mutable

But for String it define as immutable. String is immutable

So please clarify contradiction...

like image 286
RBK Avatar asked Jun 17 '17 01:06

RBK


1 Answers

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"

enter image description here

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

like image 197
Vishal Patel Avatar answered Oct 14 '22 23:10

Vishal Patel