Reza Shoja
Reza Shoja

Reputation: 927

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?

Upvotes: 1

Views: 1136

Answers (3)

Sergio
Sergio

Reputation: 30655

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.

Upvotes: 1

Artem Botnev
Artem Botnev

Reputation: 2427

Yes, they share the same memory address. If we already have "hello", new "hello" won't be created by

var string2 = "hello"

If you created new string by constructor

var string2 = String("hello")

then

println(string1 === string2)

return false

Read about Java String Pool https://www.baeldung.com/java-string-pool

Upvotes: 0

Mayur Prajapati
Mayur Prajapati

Reputation: 627

I did some findings for your good question.

As in Kotlin's Reference, primitive types are treated same in == and === both.

But for custom objects, they work in a different way. == compares structure and === checks reference.

    fun main(args: Array<String>) {
    val v1 = Temp("world")
    val v2 = Temp("world")

    println(v1 == v2)// true
    println(v1 === v2)// false
    }


    data class Temp(var val1: String)

Upvotes: 0

Related Questions