Software Sue

Link to Simply Sue
Link to Sustainability Sue
location: software/java/boolean operators Skip navigation : Home  

Java: Boolean Operators


SymbolLong name
&logical AND
&&conditional AND
|logical OR
||condition OR
!logical negation (NOT)

Conditional AND and Logical AND

Conditional AND Logical AND
&&falsetrue &falsetrue
falsefalsefalse falsefalsefalse
Truefalsetrue true falsetrue

The difference between && and & is that the conditional && will not bother to evaluate the right-hand operand if the left-hand operand is false, since the result is already determined in this case to be false. This can make the code a bit faster when the left-hand operand is false. There are occasions when you'll want to be sure that the right-hand operand is evaluated. For instance if the right-hand expression involves calling a method that modifies some variables somewhere else.

Conditional OR and Logical OR

Conditional OR Logical OR
||falsetrue |falsetrue
falsefalsetrue false falsetrue
truetruetrue true truetrue

The OR operators, | and ||, apply when you have two conditions and you want a true result if either or both of them are true. The conditional OR, ||, has a similar effect to the conditional AND, in that it omits the evaluation of the right-hand operand when the left-hand operand is true.

Bitwise operators and logical operators

Don't confuse the bitwise operators &, |, and !, with the logical operators that look the same. Which type of operator you're using in any particular instance is determined by the type of the operands that you use it with. The bitwise operators apply to integer types and produce an integer result. The logical operators apply to operands that have boolean values and produce a result of type boolean-true or false. You can use both bitwise and logical operators in an expression if it's convenient to do so.