This repository provides examples and documentation for Java's logical operators, focusing on how to evaluate multiple conditions efficiently.
- Introduction
- Logical Operators
- Multiple Conditions
- Short-Circuit Evaluation
- Example Scenarios
- Improvements
- Contributing
When writing conditional logic in Java, we often need to evaluate multiple conditions at once. This repository demonstrates how to use logical operators effectively instead of relying on nested if statements.
Java provides two binary logical operators that work on two conditions:
- Returns
true
only when both conditions are true - Returns
false
when at least one condition is false - Evaluates left to right and stops at the first
false
condition (short-circuit)
if ((thereIsPetrolInCar == true) && (thereIsExtraTime == true) && (cashInHand >= 300)) {
System.out.println("I will go to Las Vegas");
}
- Returns
true
when at least one condition is true - Returns
false
only when all conditions are false - Evaluates left to right and stops at the first
true
condition (short-circuit)
if ((thereIsPetrolInCar == true) || (thereIsExtraTime == true) || (cashInHand >= 300)) {
System.out.println("I will go to Las Vegas");
}
- Reverses the boolean value of a condition
!true
becomesfalse
!false
becomestrue
// These two conditions are equivalent
if (marks > 60) {
System.out.println("Pass.");
}
if (!(marks <= 60)) {
System.out.println("Pass.");
}
Using logical operators allows you to test multiple conditions simultaneously, making your code:
- More readable
- More concise
- More efficient through short-circuit evaluation
The process where evaluation stops as soon as the result is determined:
- For
&&
: Stops at the firstfalse
since the result will befalse
- For
||
: Stops at the firsttrue
since the result will betrue
This behavior improves performance, especially when later conditions are expensive to compute.
public class TripPlanner {
public static void main(String[] args) {
int dollarsToSpare = 350;
boolean interestedInLuckAndFun = true;
boolean interestedInHistory = false;
if (dollarsToSpare > 300) {
if (interestedInLuckAndFun && !interestedInHistory) {
System.out.println("I will go to Las Vegas.");
} else if (!interestedInLuckAndFun && interestedInHistory) {
System.out.println("I will visit Hoover Dam.");
} else if (!interestedInLuckAndFun && !interestedInHistory) {
System.out.println("I will visit Area 51 and observe some aliens.");
} else {
System.out.println("Not a valid option.");
}
} else {
System.out.println("I will go to my parent's place. No diversions.");
}
}
}
See IMPROVEMENTS.md for suggested enhancements to the code examples.