Decision Making: if, else if, switch
Site Admin
· 11 Sep 2026
· 9 views
if and else
int marks = 72;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 70) {
System.out.println("Grade B");
} else {
System.out.println("Keep practising!");
}The condition inside the parentheses must produce a boolean. If it is true the block runs, otherwise control moves to the next else if or else.
Nested if
int age = 19;
boolean hasId = true;
if (age >= 18) {
if (hasId) {
System.out.println("Entry allowed");
} else {
System.out.println("ID required");
}
}switch Statement
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Another day");
}The break stops the switch from falling through to the next case. Java 14 added the arrow form which removes the need for break:
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
default -> System.out.println("Another day");
}When to Use Which
- Use
if/elsefor ranges (e.g. scores 70-89) and complex conditions. - Use
switchfor exact equality against a fixed set of values.
Key Points
- Conditions must be boolean expressions.
- Always
break(or use arrow syntax) to avoid fall-through. defaulthandles every unlisted value.