How to Use Logical Operators in Java

104 35


Use the AND Operator


Use the AND operator, whose symbol is &&. In Java, && evaluates to true if and only if both of its operands -- the objects being manipulated -- evaluate to true.

Understand that its operands can be any expression that evaluates to a boolean value.

Note that this includes any comparison operator, such as greater than >, less than < or equal to ==, any method that returns a boolean or any boolean variable itself. Given "int a = 7; int b = 10;" then "a > 4 && b < 20" will evaluate to true.

Use the OR and NOT Operators


Use the OR operator, whose symbol is ||. It evaluates to true if either or both of its operands evaluate to true. The operands can be any expression that evaluates to a boolean. If we have "int a = 10;int b = 40;" then "a == 7 || b > a" will be true. Even though the first operand evaluates to false, the second will evaluate to true.

Consider using the exclusive OR operator, or XOR, whose symbol is ^. It evaluates to true if either but not both of its operands evaluates to true. Here the XOR operator is used as a logical boolean operator. Suppose "int a = 7;int b = 10;" then "b > a ^ b == 10". This will evaluate to false since both operands are true.

Reverse the result of a boolean expression in Java by using the logical NOT operator NOT, whose symbol is !. If its operand is true, the NOT expression will evaluate to false.

Use the NOT operator with parentheses and another boolean expression since the NOT operator binds very tightly (its operator precedence is very high). The exception is if it's paired with a single boolean variable. This example demonstrates the usage of the boolean NOT operator:

Given "int a = 7; int b = 10;" then "!(a == b)" will evaluate to true since a == b will be false, and the NOT operator will reverse it.
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.