Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if (boolean == false) vs. if (!boolean) [duplicate]

Possible Duplicate:
Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

In this NotePadProvider sample code, I noticed that the author chose the form:

    if (values.containsKey(NoteColumns.CREATED_DATE) == false) {
        values.put(NoteColumns.CREATED_DATE, now);
    }

Over:

    if (!values.containsKey(NoteColumns.CREATED_DATE)) {
        values.put(NoteColumns.CREATED_DATE, now);
    }

Is there any advantage in the first form over the more logical one?

like image 345
ateiob Avatar asked Aug 06 '12 16:08

ateiob


People also ask

What does if (! boolean mean?

It's the logical negation operator. The ! operator computes logical negation of its operand. That is, it produces true, if the operand evaluates to false, and false, if the operand evaluates to true.

Can you use == with Booleans?

Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".

Is the same as == false?

To add clarity, the == is a comparison operator. By the rule of order of operations parentheses are processed first. So the boolean expression (false or true) evaluates to True. Then the expression is evaluated as false == true.

What happens if a boolean statement is false?

Notice that the boolean in the if-test (true or false) happens to be the same as the value we want to return. If the test value is true, we return true. If the test value is false, we return false. So just return the test value directly!


3 Answers

Apart from "readability", no. They're functionally equivalent.

("Readability" is in quotes because I hate == false and find ! much more readable. But others don't.)

like image 173
Ry- Avatar answered Sep 22 '22 21:09

Ry-


Mostly READABILITY. When reading others code, it is much more intuitive to read as NOT CONTAINS KEY !values.containsKey(NoteColumns.CREATED_DATE) instead of reading CONTAINS KEY IS FALSE (values.containsKey(NoteColumns.CREATED_DATE) == false).

like image 35
devang Avatar answered Sep 22 '22 21:09

devang


This is a style choice. It does not impact the performance of the code in the least, it just makes it more verbose for the reader.

like image 26
Woot4Moo Avatar answered Sep 21 '22 21:09

Woot4Moo