Logical Operators: Combining Conditions
Sometimes, making a decision requires checking more than one thing at a time. For example, to go for a drive, you need both a car and a license. In Java, we use Logical Operators to connect multiple conditions.
1. The Big Three Operators
There are three main operators you will use to build complex logic:
| Operator | Name | Logic | Example |
|---|---|---|---|
&& |
AND | True only if both sides are true. | (age > 18 && hasID == true) |
|| |
OR | True if at least one side is true. | `(isWeekend |
! |
NOT | Reverses the result (True becomes False). | !(isGameOver) |
2. Short-Circuit Evaluation
Java is efficient. It uses "Short-Circuiting" to save time:
- With
&&: If the first part is False, Java doesn't even look at the second part (because the whole thing is already doomed to be false). - With
||: If the first part is True, Java skips the second part (because the condition is already satisfied).
3. Practical Examples
Using AND (&&)
Perfect for checking if a number falls within a specific range.
int score = 85;
if (score >= 80 && score <= 90) {
System.out.println("You got a B!");
}
Using OR (||)
Great for flexible requirements.
boolean isHacker = true;
boolean isDeveloper = false;
if (isHacker || isDeveloper) {
System.out.println("Access to the terminal granted.");
}
Using NOT (!)
Used to check if something is not happening.
boolean isRaining = false;
if (!isRaining) {
System.out.println("Let's go for a walk.");
}
💻 Full Practical Example: The Loan Eligibility Checker
Copy this code to see how multiple logical operators can work together to handle a complex decision:
import java.util.Scanner;
public class LoanChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.print("Enter your monthly income: $");
double income = input.nextDouble();
System.out.print("Do you have unpaid debts? (true/false): ");
boolean hasDebt = input.nextBoolean();
// Condition: Age must be 18+ AND income > 2000 AND must NOT have debt
if (age >= 18 && income > 2000 && !hasDebt) {
System.out.println("Congratulations! You are eligible .");
} else if (hasDebt) {
System.out.println("denied: Please clear your debts first.");
} else {
System.out.println("denied: You do not meet the income or age requirements.");
}
input.close();
}
}
⚠️ Order of Precedence
Just like math, logic has an order of operations:
!(Highest)&&||(Lowest)
Pro Tip: Always use Parentheses () to make your logic clear, even if they aren't strictly required. It makes your code much easier for others (and you) to read!
💡 Challenge: The Ultimate Login
Write a program that asks the user for a Username and a Password.
- Create a "Super User" check.
- The user gets access if:
- (Username is "admin" AND Password is "1234") OR (Username is "root" AND Password is "java77")
- Print "Access Granted" or "Invalid Credentials".