Java Language Pitfall - Using '==' to test a boolean


Example

Sometimes a new Java programmer will write code like this:

public void check(boolean ok) {
    if (ok == true) {           // Note 'ok == true'
        System.out.println("It is OK");
    }
}

An experienced programmer would spot that as being clumsy and want to rewrite it as:

public void check(boolean ok) {
    if (ok) {
       System.out.println("It is OK");
    }
}

However, there is more wrong with ok == true than simple clumsiness. Consider this variation:

public void check(boolean ok) {
    if (ok = true) {           // Oooops!
        System.out.println("It is OK");
    }
}

Here the programmer has mistyped == as = ... and now the code has a subtle bug. The expression x = true unconditionally assigns true to x and then evaluates to true. In other words, the check method will now print "It is OK" no matter what the parameter was.

The lesson here is to get out of the habit of using == false and == true. In addition to being verbose, they make your coding more error prone.


Note: A possible alternative to ok == true that avoids the pitfall is to use Yoda conditions; i.e. put the literal on the left side of the relational operator, as in true == ok. This works, but most programmers would probably agree that Yoda conditions look odd. Certainly ok (or !ok) is more concise and more natural.