This page is no longer maintained — Please continue to the home page at www.scala-lang.org

eq method on String

1 reply
Alex Wouda
Joined: 2011-06-28,
User offline. Last seen 42 years 45 weeks ago.

Hi,

I dont understand why this occurs:

val s = "a"
val s1 = "a"

both yield a java.lang.String.
When I test for identity with s eq s1, the result is true.

When I initialize the val's with new, like val s = new String("a") the
eq method returns false.

Somehow the first attempt results in s and s1 pointing to the exact
same address? Or am I overlooking something?

regards,

Alex

Johannes Rudolph 2
Joined: 2010-02-12,
User offline. Last seen 42 years 45 weeks ago.
Re: eq method on String

Your observation is correct. That behavior comes from the JVM and is
the same as in Java.

You will find several articles explaining it when googling for "string
constant intern java".

On Sat, Jun 25, 2011 at 8:41 PM, Alex Wouda wrote:
> I dont understand why this occurs:
>
> val s = "a"
> val s1 = "a"
>
> both yield a java.lang.String.
> When I test for identity with s eq s1, the result is true.
>
> When I initialize the val's with new, like val s = new String("a") the
> eq method returns false.
>
> Somehow the first attempt results in s and s1 pointing to the exact
> same address? Or am I overlooking something?
>
>
> regards,
>
> Alex

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland