Control Flow
Conditional Control Statements
Complete lesson for Conditional Control Statements using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Conditional Control Statements
Section: Control Flow. if, if-else, else-if ladder, nested if, classic switch, Java 14+ switch expressions, and ternary — with flowcharts and real-life examples.
What are conditional statements?
- Conditional (decision-making) statements let a program choose different code paths based on a
booleancondition. - Main forms:
if,if-else,else ifladder, nestedif, classicswitch, switch expressions (Java 14+), and the ternary operator?:. - Unlike C/C++, Java does not treat numbers as true/false.
if (x)for anintdoes not compile — writeif (x != 0)if that is what you mean. - Use the flowchart image below to see how control flows for each if-style statement.
Flowcharts: if, if-else, else-if & nested if
Decision-making statements choose different Java blocks when a
boolean condition is true. The diagram below shows flowcharts, syntax,
and short examples for if, if-else,
else-if ladder, and nested if.
- if: run a block only when the condition is true.
- if-else: choose between two opposite outcomes.
- else-if ladder: check multiple ordered conditions (grades, fares).
- nested if: a second check that depends on the first (login then checkout).
if statement
- Runs a block only when the condition is
true; otherwise that block is skipped and the program continues. - Real-life example: ATM cash withdrawal — if balance is enough, allow withdraw; if not, skip this simple check.
- Real-life example: Phone unlock — if the PIN is correct, open the home screen.
| Part | Meaning | Real-life mapping |
|---|---|---|
if (condition) | Test a yes/no boolean | Is balance >= amount? |
| True block | Do the action | Dispense cash |
| No else | Skip when false | Stay on the same screen |
public class IfOnly {
public static void main(String[] args) {
int balance = 5000;
int amount = 2000;
if (balance >= amount) {
System.out.println("Withdrawal allowed");
}
}
} if-else statement
- Chooses exactly one of two paths: the true block or the false (
else) block. - Real-life example: Exam result — if marks >= 40 print Pass, else print Fail.
- Real-life example: Traffic light (simplified) — if the light is green, go; else stop.
public class IfElsePass {
public static void main(String[] args) {
int marks = 35;
if (marks >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
} else if ladder
- Checks conditions in order; the first true condition runs, then the ladder stops.
- Real-life example: Grading system — A / B / C / Fail based on marks ranges.
- Real-life example: Ticket pricing — child / adult / senior fares based on age.
public class GradeLadder {
public static void main(String[] args) {
int marks = 85;
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("Fail");
}
}
} Nested if statement
- An
ifinside anotherif— use it when a second check depends on the first. - Real-life example: Online order — if logged in, then if the cart is not empty, place the order.
- Real-life example: Loan check — if salary is high enough, then if credit score is good, approve.
public class NestedIfOrder {
public static void main(String[] args) {
boolean loggedIn = true;
int cartItems = 3;
if (loggedIn) {
if (cartItems > 0) {
System.out.println("Order placed");
} else {
System.out.println("Cart is empty");
}
} else {
System.out.println("Please log in");
}
}
} Classic switch (statement)
- Selects among many fixed choices of one discrete value. Selector types:
byte,short,char,intand their wrappers,String(Java 7+), and enums. long,float,double, andbooleancannot be switch selectors — use if/else for those.- Without
break, execution falls through to the next case — usually a bug, sometimes intentional. - Real-life example: Food-court menu — case 1 Pizza, case 2 Burger, case 3 Pasta, default Invalid.
public class MenuSwitch {
public static void main(String[] args) {
int choice = 2;
switch (choice) {
case 1:
System.out.println("Pizza");
break;
case 2:
System.out.println("Burger");
break;
case 3:
System.out.println("Pasta");
break;
default:
System.out.println("Invalid choice");
}
}
} Switch expressions (Java 14+)
- Arrow cases (
case 1 ->) do not fall through. A switch can produce a value you assign to a variable. yieldis used inside a block case to produce the value.defaultis required for an expression unless the enum is exhaustive.- Comma-separated labels (
case "SAT", "SUN" ->) share one arrow body.
| Style | Fall-through | Produces a value? |
|---|---|---|
switch statement + break | Yes, if you omit break | No (side effects only) |
switch expression + -> | No | Yes |
switch expression + { } / yield | No | Yes |
public class DayType {
public static void main(String[] args) {
String day = "SAT";
String kind = switch (day) {
case "SAT", "SUN" -> "weekend";
case "MON", "TUE", "WED", "THU", "FRI" -> "weekday";
default -> "unknown";
};
System.out.println(kind);
}
} Ternary operator (quick form)
- Compact if-else that yields a value:
condition ? valueIfTrue : valueIfFalse. Both branches must be assignment-compatible. - Real-life example: Display Open or Closed for a shop based on the current hour.
public class ShopHours {
public static void main(String[] args) {
int hour = 22;
String status = (hour >= 9 && hour < 21) ? "Open" : "Closed";
System.out.println(status);
}
} Which statement should you use?
- Pick the form that matches your decision shape — keep the code readable.
| Situation | Best choice | Real-life example |
|---|---|---|
| One optional action | if | Show a low-battery warning only when needed |
| Two opposite outcomes | if-else | Pass / Fail |
| Many ranges / ordered checks | else if ladder | Grades, ticket age bands |
| Decision inside another decision | Nested if | Login then checkout |
| Many fixed discrete options | switch | Menu / keypad / day of week |
| Simple value choice | Ternary ?: | Open / Closed label |
Advanced — Conditional Control Statements
Deeper rules for if / else if / nested if
- The condition must be
boolean(orBoolean). Non-zero integers are not automatically true. - Brace every block
{ }even for one line — that kills dangling-else bugs (elsealways binds to the nearest unmatchedif). - Order matters in an else-if ladder: put more specific / higher-priority checks first (
>= 90before>= 75). - Prefer early
returnin methods instead of deep nesting when it improves clarity. if (x = 5)does not compile: assignment ofintis not a boolean. Use==for comparison.
public class DanglingElse {
public static void main(String[] args) {
int n = 4;
if (n > 0) {
if (n % 2 == 0) {
System.out.println("positive even");
} else {
System.out.println("positive odd");
}
} else {
System.out.println("non-positive");
}
}
} switch in depth and pattern matching
caselabels must be compile-time constants (literals,finalconstants, enum constants).- Classic switch: stack labels to share a body (
case 6: case 7:). Arrow switch:case 6, 7 ->. - Java 16+ pattern matching:
if (obj instanceof String s)bindssonly when the test succeeds. - Java 21 adds switch pattern matching and record patterns; many interviews still start with classic + arrow switch.
- For ranges (marks >= 90), prefer else-if. Switch is best for exact matches.
public class YieldSwitch {
static String band(int marks) {
return switch (marks / 10) {
case 10, 9 -> "A";
case 8, 7 -> {
yield "B";
}
case 6, 5 -> "C";
default -> "Fail";
};
}
public static void main(String[] args) {
Object obj = "Java";
if (obj instanceof String s) {
System.out.println(s.length());
}
System.out.println(band(85));
}
} Real-life decision models (combined)
- ATM: nested checks — card valid, then PIN correct, then balance enough, then dispense.
- E-commerce coupon: else-if ladder on cart total for discount slabs.
- Elevator panel / keypad: switch on button number.
- Weather app: if raining and temperature < 10, print Carry umbrella and jacket.
- Day type: switch expression on a
Stringday code to weekend / weekday.
Tricky Interview Points
Q1) What is a conditional statement in Java?
Answer A statement that chooses which code to run based on a boolean condition: if, if-else, else-if, nested if, switch, switch expressions, and ternary.
Q2) Can you write if (1) in Java?
Answer No. The condition must be boolean. if (1) is a C/C++ habit and does not compile. Write if (x != 0) when you mean a non-zero int.
Q3) Difference between if and if-else?
Answer if runs a block only when true and otherwise skips it. if-else always chooses one of two blocks: true or false.
Q4) What is an else-if ladder?
Answer A chain of if / else if / else checks evaluated in order. The first true condition’s block runs, then the chain stops.
Q5) What is a nested if?
Answer An if statement placed inside another if/else block. Used when a second decision depends on the first (for example login then checkout).
Q6) When should you use switch instead of if-else?
Answer When branching on one discrete value with many exact matches (menu choice, day number, enum, String code). For ranges, else-if is usually clearer.
Q7) Which types work in a switch?
Answer byte, short, char, int (and wrappers), String, and enum. Not long, float, double, or boolean.
Q8) What is fall-through?
Answer In a classic switch, after a matching case, execution continues into later cases until break, return, or the end.
Q9) What did Java 14 add for switch?
Answer Switch expressions: arrow cases without fall-through, comma-separated labels, and the ability to return a value (yield in block cases).
Q10) Is default mandatory?
Answer For a switch statement, no. For a switch expression, yes — unless the compiler can prove every enum constant is covered.
Q11) Can two cases share a body?
Answer Yes. Classic: stacked case labels. Arrow switch: case 1, 2, 3 -> ...
Q12) What is a dangling else?
Answer Ambiguity about which if an else belongs to when braces are missing. Always use { } to make pairing clear.
Q13) What is the ternary operator?
Answer condition ? exprTrue : exprFalse — a compact expression form of if-else that yields a value.
Q14) What does if (obj instanceof String s) do?
Answer Pattern matching for instanceof (Java 16+): if obj is a String, s is bound to that String in the true block. null instanceof String is false.
Simple Programs
if — low balance warning
public class LowBalance {
public static void main(String[] args) {
int balance = 300;
if (balance < 500) {
System.out.println("Low balance warning");
}
}
} if-else — even or odd
public class EvenOdd {
public static void main(String[] args) {
int n = 17;
if (n % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
} else-if — ticket fare by age
public class TicketFare {
public static void main(String[] args) {
int age = 14;
if (age < 5) {
System.out.println("Free");
} else if (age < 18) {
System.out.println("Child fare");
} else if (age < 60) {
System.out.println("Adult fare");
} else {
System.out.println("Senior fare");
}
}
} Nested if — login then order
public class Checkout {
public static void main(String[] args) {
boolean loggedIn = true;
int cart = 2;
if (loggedIn) {
if (cart > 0) {
System.out.println("Checkout OK");
} else {
System.out.println("Add items first");
}
} else {
System.out.println("Login required");
}
}
} Classic switch with break
public class ClassicSwitch {
public static void main(String[] args) {
int n = 2;
switch (n) {
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("other");
}
}
} Switch expression (Java 14+)
public class DayTypeExpr {
public static void main(String[] args) {
String day = "SAT";
String kind = switch (day) {
case "SAT", "SUN" -> "weekend";
case "MON", "TUE", "WED", "THU", "FRI" -> "weekday";
default -> "unknown";
};
System.out.println(kind);
}
} Ternary — shop open or closed
public class ShopOpen {
public static void main(String[] args) {
int hour = 20;
String s = (hour >= 9 && hour < 21) ? "Open" : "Closed";
System.out.println(s);
}
} Problem Solving Tricks
- Always use braces
{ }withif/else— prevents dangling-else mistakes. - Java conditions are boolean-only; never write
if (n)for an int. - In else-if ladders, order ranges from high to low (or most specific first).
- Prefer
else iffor ranges; preferswitchfor exact menu-like choices. - Put
breakafter every classic switch case unless fall-through is intentional and commented. - Prefer arrow
switchwhen you only need a value — no forgottenbreak. - Switch on enums instead of magic strings when the set is closed.
- Keep nested if depth small; extract helper methods when nesting gets hard to read.
- Use ternary only for short value choices — not for multi-statement logic.
- Test boundary values in grades/fares (exactly 40, 75, 90) — off-by-one bugs hide there.
- Put the boolean test first in
x != null && x.method()so the method never runs on null.
Practice Programs List
- Write an if program that prints Eligible to vote only when age >= 18.
- Write if-else to check whether a year is a leap year (4 / 100 / 400 rule).
- Build an else-if grade calculator that also prints Pass/Fail.
- Write nested if for ATM: valid PIN, then sufficient balance, then success message.
- Create a switch calculator menu: 1 add, 2 sub, 3 mul, 4 div of two integers.
- Use switch on a char traffic light: R stop, Y wait, G go.
- Rewrite a Pass/Fail if-else using the ternary operator.
- Write else-if for electricity bill slabs based on units consumed.
- Nested if: if temperature > 30 and humidity > 70 print Humid heat warning.
- Map marks 0–100 to letter grades with else if, then rewrite as a switch expression over
marks / 10. - Write a classic switch that intentionally falls through (days in a month) and comment why.
- Use instanceof pattern matching to print the length if an Object is a String.