Pitfall - Using to test a boolean

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Pitfalls - language syntax:
* Pitfall - Using to test a boolean

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
108 Pitfalls - language syntax
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap