• Home
  • Java Logical Operators with Examples

Java Logical Operators with Examples

Logical operators in Java are used to perform logical operations on boolean expressions. There are three logical operators in Java: AND (&&), OR (||) and NOT (!).

The AND operator (&&) returns true if both operands are true, otherwise it returns false.

For example:

if (age > 18 && age < 25) {
System.out.println("Eligible for discount");
}

The OR operator (||) returns true if either operand is true, otherwise it returns false.

For example:

if (age < 18 || age > 60) {
System.out.println("Eligible for discount");
}

The NOT operator (!) reverses the boolean value of its operand.

For example:

if (age < 18 || age > 60 && isStudent)

It is important to note that the AND operator has a higher precedence than the OR operator. This means that in the following expression:

if (age < 18 || age > 60 && isStudent)

the AND operator (&&) is evaluated before the OR operator (||). This is because the AND operator has a higher precedence. To change the order of precedence, you can use parentheses. For example:

if ((age < 18 || age > 60) && isStudent)

In this example, the OR operator (||) is evaluated before the AND operator (&&).