3

I am new to Scala but I know Java. Thus, as far as I understand, the difference is that == in Scala acts as .equals in Java, which means we are looking for the value; and eq in Scala acts as == in Java, which means we are looking for the reference address and not value.

However, after running the code below:

    val greet_one_v1 = "Hello"
    val greet_two_v1 = "Hello"
    println(
            (greet_one_v1 == greet_two_v1),
            (greet_one_v1 eq greet_two_v1)
    )


    val greet_one_v2 = new String("Hello")
    val greet_two_v2 = new String("Hello")
    println(
            (greet_one_v2 == greet_two_v2),
            (greet_one_v2 eq greet_two_v2)
    )

I get the following output:

(true,true)
(true,false)

My theory is that the initialisation of these strings differs. Hence, how is val greet_one_v1 = "Hello" different from val greet_one_v2 = new String("Hello")? Or, if my theory is incorrect, why do I have different outputs?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66

1 Answers1

0

As correctly answered by Luis Miguel Mejía Suárez, the answer lies in String Interning which is part of what JVM (Java Virtual Machine) does automatically. To initiate a new String it needs to be initiated explicitly like in my example above; otherwise, Java will allocate the same memory for same values for optimisation reasons.