- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
eq method on String
Tue, 2011-06-28, 10:26
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
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