Understanding Logical Operators: && (AND) vs. || (OR) in Java

Modified on Mon, 9 Sep at 12:09 PM

The && (AND) and || (OR) operators are fundamental for working with boolean logic.


Logical Operators

Logical operators are used to perform logical operations on boolean expressions, returning a boolean result (true or false). The most common logical operators are:

  • && (Logical AND)
  • || (Logical OR)

&& (Logical AND) Operator

The && operator returns true only if both conditions are true. If either of the conditions is false, the entire expression evaluates to false. It's often used when you need to check if multiple conditions are all true.


Example:

int a = 10;
int b = 20;
if (a > 5 && b > 15) {
    System.out.println("Both conditions are true.");
} else {
    System.out.println("One or both conditions are false.");
}


In this case, a > 5 is true and b > 15 is true, so the && operation returns true, and the message "Both conditions are true." is printed.


Truth Table for &&:


A

B

A && B

false

false

false

false

true

false

true

false

false

true

true

true


|| (Logical OR) Operator


The || operator returns true if at least one of the conditions is true. If both conditions are false, the entire expression evaluates to false. It's useful when you need to check if any one of multiple conditions is true.


Example:

int a = 10;
int b = 5;
if (a > 5 || b > 15) {
    System.out.println("At least one condition is true.");
} else {
    System.out.println("Both conditions are false.");
}


Here, a > 5 is true, but b > 15 is false. Since at least one condition is true, the || operation returns true, and the message "At least one condition is true." is printed.


Truth Table for ||:


A

B

A || B

false

false

false

false

true

true

true

false

true

true

true

true


Visualization

Imagine the && operator as two gates that both need to be open for the signal (true) to pass through. If either gate is closed (false), the signal cannot pass.


For the || operator, think of it as two gates where the signal can pass through if at least one gate is open. The signal is blocked only if both gates are closed.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article