Booleans & if…else
Programs make decisions: show a discount if the basket is big enough, reject a password that's too short, greet differently in the morning. if, else if and else run different code depending on whether a boolean condition is true.
if
void main() { int temperature = 31; if (temperature > 30) { System.out.println("It's hot today."); } System.out.println("Done."); }
It's hot today. Done.
The condition in parentheses must be a boolean expression. If it's true, the block runs; otherwise it's skipped.
if…else
void main() { double basket = 42.0; if (basket >= 50) { System.out.println("Free shipping!"); } else { System.out.println("Spend " + (50 - basket) + " more for free shipping."); } }
Spend 8.0 more for free shipping.
else if chains
void main() { int score = 73; String grade; if (score >= 90) { grade = "A"; } else if (score >= 75) { grade = "B"; } else if (score >= 60) { grade = "C"; } else { grade = "F"; } System.out.println("Grade: " + grade); }
Grade: C
Conditions are checked from the top, and only the first true branch runs. Order matters: if score >= 60 came first, every passing score would get a C.
Combining conditions
void main() { int age = 16; boolean withAdult = true; if (age >= 18 || withAdult) { System.out.println("Entry allowed"); } if (age >= 13 && age <= 19) { System.out.println("Teenager"); } if (!(age >= 18)) { System.out.println("Minor"); } }
Entry allowed Teenager Minor
Nested if
void main() { boolean loggedIn = true; boolean isAdmin = false; if (loggedIn) { if (isAdmin) { System.out.println("Admin dashboard"); } else { System.out.println("User dashboard"); } } else { System.out.println("Please log in"); } }
User dashboard
Deep nesting gets hard to read. Often a combined condition or an early return (lesson 20) flattens the logic.
Braces are optional — but use them
void main() { int stock = 0; if (stock > 0) System.out.println("Available"); System.out.println("Ships today"); }
Ships today
Without braces, only the first statement belongs to the if. The indentation suggests both lines are conditional, but "Ships today" always prints. Always using braces prevents this classic bug.
Comparing correctly
void main() { String answer = new String("yes"); double total = 0.1 + 0.2; System.out.println(answer == "yes"); System.out.println(answer.equals("yes")); System.out.println(total == 0.3); System.out.println(Math.abs(total - 0.3) < 1e-9); }
false true false true
Compare strings with equals, and compare doubles with a small tolerance rather than ==.
The conditional operator
void main() { int hour = 20; String greeting = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening"; System.out.println(greeting); }
Good evening
The ternary operator chooses between two values. Chaining them works but quickly becomes hard to read; a switch (next lesson) or if chain is often clearer.
Try it yourself
Classify a year as a leap year: divisible by 4, except centuries, unless divisible by 400.
2100 is not a leap year