Skip to main content

Logical Operators

Java Operators: Logical Operators

In Java, logical operators are used to build compound logical expressions, that is, expressions involving two or more variables or conditions. These operators are particularly useful in controlling the flow of a program based on a set of conditions.

There are three types of logical operators in Java:

  1. Logical AND (&&)
  2. Logical OR (||)
  3. Logical NOT (!)

1. Logical AND (&&)

The Logical AND operator (&&) returns true if both operands are true. If one or both operands are false, it returns false.

// Example
boolean a = true;
boolean b = false;

System.out.println(a && b); // Output: false

In the above example, since b is false, the whole expression a && b becomes false.

2. Logical OR (||)

The Logical OR operator (||) returns true if at least one of the operands is true. If both operands are false, it returns false.

// Example
boolean a = true;
boolean b = false;

System.out.println(a || b); // Output: true

In the above example, since a is true, the whole expression a || b becomes true.

3. Logical NOT (!)

The Logical NOT operator (!) is a unary operator, meaning it only requires one operand. It reverses the logical state of the operand. If the condition is true, it returns false, and if the condition is false, it returns true.

// Example
boolean a = true;

System.out.println(!a); // Output: false

In the above example, since a is true, the whole expression !a becomes false.

Short-Circuiting

It's important to note that Java supports short-circuiting with its logical operators. This means if the left operand of a logical AND (&&) operation is false, Java won't check the right operand because it knows the result will be false regardless. Similarly, if the left operand of a logical OR (||) operation is true, Java won't check the right operand because it knows the result will be true regardless.

This can be particularly useful for preventing errors in your code. For example, you might want to check if an array is empty and if the first element of the array is null. In this case, you would want to make sure the array isn't empty before trying to access its first element.

if (array.length > 0 && array[0] == null) {
// Do something
}

In the above code, if the array is empty, Java won't try to access the first element of the array, thus preventing an error.

That's all about logical operators in Java. They're powerful tools for controlling the flow of your programs based on multiple conditions. Keep practicing with them and you'll soon become proficient at writing complex logical expressions.