Equals Rights: == != .equals

Here's an issue that crops up in Java programs quite often. It's 3 A.M., after your fourth cup of coffee, and you're trying to find the right logic to solve some complex programming problem. By now, you're almost incapable of thinking about String and Object references, because the pillow is calling. And then the worst happens....No, it's not a "Java" spill, but this:

String name = getName();
if (name == "Sleepy")   // oops!
{
   doSomething();
}

You quickly compile and test the code, and it seems to work. Finally! Time to go home and celebrate by snoring! Unfortunately, some time later, application testing uncovers an intermittent bug and traces it to exactly this section of code.

"What?" you say indignantly. ...

Get Wicked Cool Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.