Beginner
Control Flow: If-Else and Switch Statements
📂 Phase 1: Java Foundations (Days 1–5) · JavaControl flow statements let a program make decisions and execute different code paths based on conditions — the foundation of all program logic.
If-Else Statement
int marks = 75;
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 75) {
System.out.println("Grade: B");
} else if (marks >= 50) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
Nested If and Logical Combinations
int age = 20;
boolean hasID = true;
if (age >= 18) {
if (hasID) {
System.out.println("Entry allowed");
} else {
System.out.println("ID required");
}
} else {
System.out.println("Entry denied — underage");
}
The Switch Statement
Switch is a cleaner alternative to long if-else chains when comparing one variable against multiple fixed values.
int day = 3;
String dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
default: dayName = "Invalid day";
}
System.out.println(dayName); // Wednesday
Why break Matters
Without break, execution "falls through" to the next case automatically — sometimes intentional, but usually a bug.
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
}
The Ternary Operator
A compact shorthand for simple if-else assignments:
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
Interview tip: Since Java 14, switch can also be written as an expression with arrow syntax (case 3 -> "Wednesday";), removing the need for break entirely — worth mentioning if asked about modern Java features.