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 singleString
instance, so it works withString
literals, 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 newString
instance, and breaks any possible pointer equality.More importantly, most
Strings
you 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 theequals
method, and not the==
operator, if you want to check for contents equality.When you do this, you are actually creating string literals:
The compiler finds identical string literals and then optimizes by keeping one instance in the heap and making all the variables in the stack point to it. So doing an
==
will return true because they point to the same memory address.When you do this, you are creating string objects:
The instantiation will create unique space on the heap for each of these and the stack variables will point to those separate locations. Thus, these will be equal using
.equals()
because their values are the same, but they will not be equal using==
because they are different objects in the heap memory space.Example 1:
Example 2:
Seasoned Java developers rarely if ever use
new String(String)
, but the problem arises in other cases as well. For example:(Most String instances in a real-world applications are formed either by taking a substring of some other String, or by constructing it from an array of characters. Very few applications will only use String instances created as literals.)