2
String x = "Hello!";

String y = "Hello!";

System.out.println( x == y );

How come this is still coming out true, aren't they referring to different locations in heap memory?

tkw83
  • 185
  • 1
  • 5
fal
  • 31
  • 1
  • 3
    **aren't they referring to different locations in heap memory?** No they both are compile time constant so the are in the string pool pointing to same memory – singhakash Oct 22 '15 at 18:29
  • 1
    Possible duplicate of [What makes reference comparison (==) work for some strings in Java?](http://stackoverflow.com/questions/9698260/what-makes-reference-comparison-work-for-some-strings-in-java) – Tom Oct 22 '15 at 18:36
  • The image in this answer helps you to understand the question : http://stackoverflow.com/a/17489410/1927832 – Suresh Atta Oct 22 '15 at 18:37

3 Answers3

2

The JVM stores String literals in a pool for reuse. more information here: Reusability of Strings in java?

Community
  • 1
  • 1
hair raisin
  • 2,618
  • 15
  • 13
2

This is covered in JLS 3.10.5 (and 15.28, which 3.10.5 references):

A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Community
  • 1
  • 1
yshavit
  • 42,327
  • 7
  • 87
  • 124
2

NO . They aren't referring to different locations. Since its a String literal, It will not create a new object for y , rather it will refer to the same object which is already created for x in the string pool.

Rahman
  • 3,755
  • 3
  • 26
  • 43