-2

I have previously asked a question about comparing 2 strings and was told that I should always use .equals.

However, I do not understand why this then works:

 String y= "Mary";
 String x= "Mary";
 System.out.print(x==y);

This will print true, and I do not understand why.

E-Riz
  • 31,431
  • 9
  • 97
  • 134
Chevyb
  • 55
  • 3

1 Answers1

3

Because those two String(s) have the same reference identity, and that is because they came from the String intern pool. If you were to add a new String() to one of them, like so -

String y= "Mary";
String x= new String("Mary");
System.out.print(x==y);

You would get false.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249