I learned that it is from the devil to test String equality with ==
instead of String.equals()
, because every String was a reference to its own object.
But if i use something like
System.out.println("Hello" == "Hello");
it prints true.
Why?
It doesn't. It's still a bad thing to do - you'll still be testing reference equality instead of value equality.
If you're seeing == testing "work" now then it's because you genuinely have equal references. The most common reason for seeing this would probably be due to interning of String literals, but that's been in Java forever:
This is guaranteed by section 3.10.5 of the Java Language Specification:
It hasn't changed. However, the Java Compiler uses string.intern() to make sure that identical strings in source code compile to same String object. If however you load a String from a File or Database it will not be the same object, unless you force this using String.intern() or some other method.
It is a bad idea, and you should still use .equals()
Look, this is a tricky concept.
There is a difference between:
and
If your strings were objects, i.e.,
Then, two different objects would have been created in the String pool at two different memory locations and doing
would have resulted
false
.But since your
String b
andString c
are literals,results
true
. This is because two different objects were not created. And botha
andb
are pointing to same String in the stack memory.This is the difference. You are right,
==
compares for memory location. And that is the reason,In order to have two separate Strings with same values but at different locations in the
String pool
and NOTstack memory
, you need to create String objects as shown above.So,
you have to use
in case of objects.