Using ‘==’ instead of .equals for Java strings [duplicate]

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 single String instance, so it works with String literals, but not with strings generated at runtime.

For instance, "Foo" == "Foo" might work, but "Foo" == new String("Foo") won’t, because new String("Foo") creates a new String 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 the equals method, and not the == operator, if you want to check for contents equality.

Leave a Comment