Concept Explanation
Imagine a self-driving car.
- IF the light is red, THEN stop.
- ELSE IF the light is yellow, THEN slow down.
- ELSE (it must be green), THEN go.
Decisions in Java work exactly the same way using boolean logic.
Syntax or Core Structure
int speed = 80;
if (speed > 100) {
System.out.println("Emergency Braking!");
} else if (speed > 70) {
System.out.println("Slow down a bit.");
} else {
System.out.println("Perfect speed.");
}
Ternary Operator (The Shortcut)
For simple "Either/Or" decisions, use this shorthand: variable = (condition) ? expressionTrue : expressionFalse;
String result = (age >= 18) ? "Adult" : "Minor";
Common Mistakes
- The Double Equals: Using
if (x = 10). This assigns 10 to x! Useif (x == 10). - String Comparison: Using
if (name == "John"). In Java, you MUST use.equals()for strings:if (name.equals("John")). - Hanging Else: Forgetting curly braces for single-line if-statements. It's safer to always use
{ }.
Practice Exercises
- The Grade Calculator: Write a program that takes a score (0-100) and prints A, B, C, D, or F.
- The Leap Year: Research the rules for a Leap Year and write an
ifstatement to check if a year variable is a leap year. - The Password Switch: Compare a
guessedPasswordString with acorrectPasswordusing.equals()and print "Access Granted" or "Denied".