Equality NOW!

6 Feb

Equality NOW!

When is one item definitely NOT equal to another, even though they are both exactly the same?

When you’re programming in JAVA of course!

I’ve run into this many times, but for some reason today I stared at and wrestled with this problem for an hour straight before the “Oh YEAH!” clicked in, so I’m writing this post to help drive the point home for myself.

And you too, hopefully!

It seemed so simple:

return (elementText == "An email has been sent!");

If they’re equal, return TRUE, if not, FALSE. No biggie. But this is all I saw on every run:


junit.framework.AssertionFailedError: Fail report was submitted

Eh? Whazzat? The ensuing stack trace didn’t even mention the class the code was actually running from, so I looked in all the dustiest, darkest corners of my code (and the surrounding project) trying to find what strange, esoteric programming conundrum or race condition was causing this error.

It was staring me in the face the whole time, and I literally had to do that…STARE…at it for while before it hit me! This is probably the most common Java programming error of all time, and I’m ashamed to say it slapped me a good one this morning. Here’s what that code should look like:

return (elementText.contentEquals(
            "An email has been sent!"));

Nothing strange, nothing esoteric, nothing I haven’t encountered before. We use “==” for numbers and “.contentEquals()” for text. Easy! Grrrrr.

My only excuse is that with the intensity of this current project and deadlines looming, I immediately assumed that the problem was something dreadful I hadn’t encountered before. I was in the habit of seeing the offending method in the stack trace and this time there was nothing and, well, I PANICKED!

There it is, my confession. Kids don’t try this at home and end up a clown like me. I am now going to the (white?) board to write, “Not all equivalencies are ==” 100 times.

Advertisements

Comments are welcome!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: