Search code examples
kotlinobjectmemoryshared-memoryequality

Do objects share the same memory address by default


what does this behavior mean?

var string1 = "hello"
var string2 = "hello"
println(string1 == string2) // return true
println(string1 === string2) // return true

since

equality: determines if two objects contain the same state. (==)

identity: determines whether two objects share the same memory address. (===)

do they share the same memory address?


Solution

  • The short answer is YES, they share the same memory address.

    Next description is applicable for Kotlin/JVM. When you declare a new string, there are some interesting things that happen behind the scenes. This is a basic string declaration. We create a new string variable called string1 and give it a value:

    var string1 = "hello"
    

    It will allocate space in the memory for the literal value hello. This area in memory is called the string constant pool. It's like a pool of string values that are available to other parts of the program. Now, if you created another variable, say string2, and ALSO gave it a value of hello Kotlin re-uses the value that's already in the pool. The string constant pool sits inside a section of memory is called the heap. This is a part of memory that is used for run-time operations, working with classes and objects. Think of a heap like a patch of garden soil you can easily take dirt and plants from as you plant a garden. Kotlin places these new objects there. If you create a hundred more objects, Kotlin will create a hundred more literals atop the heap.

    I would use Referential equality (===) only to check whether variables pointing to the same object or not.