Double Equals for Comparisons

This is a holdover from C. It made its way into C++, and then Java used a lot of C++ syntax. The bug goes like this: Somewhere, you accidentally type a single equals sign instead of a double one when examining a boolean value:

boolean b = false;

if (b = true) {
// Always gets executed.

Instead of performing a comparison, as you’d hoped, you’re actually assigning true to the variable b. This assignment has an overall value of true, so the if always succeeds.

Some people suggest reversing the order of the comparison, so the literal value always comes first. This generates a compile-time error for if (true = b), so you’ll figure out what’s wrong and change it to if (true == b). Personally, I don’t like how this looks, so I just muddle through the old fashioned way, making darn sure I always use a double equals when I need it.

About bwilson 37 Articles
Mobile device specialist currently working as a system analyst, building out an IT infrastructure. I currently focus much of my work on relational databases as well as frameworks. The goal of my work is to continually improve processes and efficiencies.

Be the first to comment

Leave a Reply

Your email address will not be published.