Not Operator (!)

A Not operator is represented by an exclamation mark (!). Technically, it’s a unary prefix operator, which means that you use it with one operand, and you code it immediately in front of that operand.

The Not operator reverses the value of a Boolean expression. Thus, if the expression is true, Not changes it to false. If the expression is false, Not changes it to true.

For example:

!(i = 4)

This expression evaluates to true if i is any value other than 4. If i is 4, it evaluates to false. It works by first evaluating the expression (i = 4). Then it reverses the result of that evaluation.

tip.eps Don’t confuse the Not logical operator (!) with the Not Equal relational operator (!=). Although these operators are sometimes used in similar ways, the Not operator is more general. I could have written the preceding example like this:

i != 4

The result is the same. The Not operator can be applied to any expression that returns a true-false result, however, not just to an equality test.

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.