1

I have written this code in eclipse:

String[] s = {"a","b"}; String d = "a"; System.out.println(s[0]==d);

and it is giving "true" as output.

"==" checks for object reference, if both object refer to same object, but here in this case object "d" refers to different object and "s[0]" to different, then how come they are equal.

1 Answers1

0

"a" will have been created in the string pool used by the JVM.

As an optimisation only one instance of that string will have been created. Java can do this since strings are immutable. That's why the references are referencing the same underlying object, so in this particular instances, the references compare equal.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483