β Javaπ
Day 6
Conditional Statements in Java
if, if-else, else-if ladder, nested if, and switch statements in Java.
π―
Learning objectives
- βWrite branching logic using if / else-if / else
- βChoose between if-else ladder and switch
- βUse switch expressions (Java 14+) for concise code
π‘ Key points
- Condition must evaluate to boolean β Java rejects `if (1)` (unlike C).
- if-else-if runs top to bottom, stops at first true branch.
- switch works with int, char, String, enum β from Java 14+, also as an expression.
- Braces are optional for single statement but always use them β safer.
π» Code examples(4)
#1if / else if / else
javaint marks = 72;
if (marks >= 90) {
System.out.println("A+");
} else if (marks >= 75) {
System.out.println("A");
} else if (marks >= 60) {
System.out.println("B");
} else {
System.out.println("Needs work");
}
Output
B
First branch that evaluates to true wins. Order matters β put stricter conditions first.
#2Classic switch
javaint day = 3;
switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
case 3: System.out.println("Wed"); break;
default: System.out.println("Other");
}
Output
Wed
break stops fall-through. Miss a break β execution continues into the next case (common bug).
#3Switch expression (Java 14+)
javaString name = switch (day) {
case 1 -> "Mon";
case 2 -> "Tue";
case 3 -> "Wed";
default -> "Other";
};
Arrow form β no break needed, returns a value, safer. Modern preferred style.
#4Nested if
javaint age = 20;
boolean hasId = true;
if (age >= 18) {
if (hasId) {
System.out.println("Allowed");
} else {
System.out.println("ID required");
}
}
Combine with && when possible: if (age >= 18 && hasId). Flatter is cleaner.
π― Practice
Q1. Will `if (x = 5)` compile in Java?+
No. `x = 5` is assignment returning int, but if requires boolean. Java catches this at compile time (unlike C).
Q2. What happens if you omit break in a switch case?+
Fall-through β execution continues into the next case until it hits a break or the switch ends.
Q3. Rewrite using ternary: if (x > 0) sign = 1; else sign = -1;+
int sign = (x > 0) ? 1 : -1;
π Notes
When to prefer switch over if-else
Use switch when comparing a single variable against many constant values (day names, menu options, enum states). Use if-else when conditions involve ranges (marks >= 60) or multiple variables.
Common trap
if (score = 100) { ... } // β won't compile in Java
if (score == 100) { ... } // β
correct
Java saves you here β same bug in C/C++ silently passes.