Possible Duplicate:
What makes reference comparison (==) work for some strings in Java?
I know this has been asked before, but in spite of recommendations to use .equals() instead of the == comparison operator, I found that == works all the time:
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true
Can anyone give me an example of the == operator failing?
This is because you’re lucky. The
==operator in Java checks for reference equality: it returns true if the pointers are the same. It does not check for contents equality. Identical strings found at compile-time are collapsed into a singleStringinstance, so it works withStringliterals, but not with strings generated at runtime.For instance,
"Foo" == "Foo"might work, but"Foo" == new String("Foo")won’t, becausenew String("Foo")creates a newStringinstance, and breaks any possible pointer equality.More importantly, most
Stringsyou deal with in a real-world program are runtime-generated. User input in text boxes is runtime-generated. Messages received through a socket are runtime-generated. Stuff read from a file is runtime-generated. So it’s very important that you use theequalsmethod, and not the==operator, if you want to check for contents equality.