Control Flow Statements
If-else, switch cases, for loops, while loops, and jumping statements
- Master decision making with if-else and switch
- Understand loop structures: for, while, do-while
- Use break and continue effectively
Series:
Java Core Concepts | Chapter: Control Flow Statements Audience: Beginner to Intermediate Java Developers Coverage: Decision Making (if, if-else, if-else-if, nested if, switch), Iterative (for, while, do-while, for-each), Branching (break, continue)
Table of Contents
Mind Map Control Flow Overview
1. Overview Three Types of Control Flow
| Category | What it Does | Keywords / Constructs |
|---|---|---|
| Decision Making | Executes code conditionally based on true/false expressions | if, if-else, if-else-if, switch |
| Iterative | Repeats a block of code multiple times | for, while, do-while, for-each |
| Branching | Alters the flow inside loops or switch blocks | break, continue |
2. Decision Making Statements
Simple `if`
Definition
Executes a block of code only if the given condition evaluates to true. If the condition is false, the block is skipped entirely and execution continues after it.
Syntax
1if (condition) {2 // executed only if condition is true3}4// always executed after the if block (whether condition was true or false)Flowchart
Code Example
1public class Main {2 public static void main(String[] args) {3 int value = 10;4
5 if (value > 8) {6 System.out.println("Only executed when value is greater than 8");7 }8
9 System.out.println("This always executes");10 }11}Only executed when value is greater than 8 This always executes
Step-by-Step
value = 1010 > 8→true- Print inside the if block
- Continue to the statement after the block
`if-else`
Definition
Provides two paths: if the condition is true, the if block runs; if false, the else block runs. Exactly one of the two blocks always executes.
Syntax
1if (condition) {2 // runs when condition is true3} else {4 // runs when condition is false5}Flowchart
Code Example
1int value = 7;2
3if (value > 8) {4 System.out.println("Value is greater than 8");5} else {6 System.out.println("Value is less than or equal to 8");7}8
9System.out.println("Rest of the code");Value is less than or equal to 8 Rest of the code
Step-by-Step
value = 77 > 8→falseifblock skipped →elseblock executes- "Rest of the code" executes
`if-else-if` Ladder
Definition
A chain of if followed by one or more else if blocks (and optionally a final else). Conditions are evaluated top to bottom — the first true condition's block executes; all others are skipped.
Syntax
1if (condition1) {2 // runs if condition1 is true3} else if (condition2) {4 // runs if condition1 is false AND condition2 is true5} else if (condition3) {6 // runs if condition1 and condition2 are false AND condition3 is true7} else {8 // runs if NONE of the above conditions are true (optional)9}Flowchart
Code Example
1int value = 13;2
3if (value == 1) {4 System.out.println("Value is 1");5} else if (value == 2) {6 System.out.println("Value is 2");7} else if (value == 3) {8 System.out.println("Value is 3");9} else {10 System.out.println("Value is " + value); // none matched11}Value is 13
Key Points
- Evaluation is always top to bottom
- As soon as one condition is
true, its block executes and the rest are skipped - The
elseblock is optional — use it when you need a fallback for "none matched" - You can have as many
else ifblocks as needed
Nested `if`
Definition
An if-else statement placed inside another if block or else block. There is no limit on nesting depth.
Syntax
1if (outerCondition) {2 // outer if block3 if (innerCondition) {4 // inner if block5 } else {6 // inner else block7 }8} else {9 // outer else block10 if (anotherCondition) {11 // ...12 }13}Code Example
1int value = 13;2
3if (value > 8) {4 System.out.println("Value is greater than 8");5
6 // Nested if inside the outer if7 if (value < 15) {8 System.out.println("Value is greater than 8 but less than 15");9 } else {10 System.out.println("Value is 15 or more");11 }12
13} else {14 System.out.println("Value is 8 or less");15}Value is greater than 8 Value is greater than 8 but less than 15
Step-by-Step
13 > 8→true→ enter outer if block- Print "Value is greater than 8"
13 < 15→true→ enter inner if block- Print "Value is greater than 8 but less than 15"
- Outer else is skipped
if blocks (more than 2-3 levels) hurt readability. Consider refactoring with early returns or extracting logic into methods.3. Switch Statement
Overview
The switch statement is functionally similar to the if-else-if ladder — it evaluates an expression and matches it against several case values, executing the matching block. It is often more readable than a long chain of else-if when comparing one variable against many fixed values.
Syntax
1switch (expression) {2 case value1:3 // code4 break;5 case value2:6 // code7 break;8 // ... more cases9 default:10 // runs if no case matched11 break; // optional if default is last12}How It Works Flowchart
Basic Example
1int a = 1, b = 2;2
3switch (a + b) { // expression evaluates to 34 case 1:5 System.out.println("a + b is 1");6 break;7 case 2:8 System.out.println("a + b is 2");9 break;10 case 3:11 System.out.println("a + b is 3"); // ✅ matches12 break;13 default:14 System.out.println("a + b is something else");15}a + b is 3
The `break` Statement Why It Matters
If break is omitted from a matched case, execution falls through to the next case, running its code regardless of whether the case value matches.
Without `break` Fall-Through Example
1int a = 1, b = 2; // a + b = 32
3switch (a + b) {4 case 1:5 System.out.println("a + b is 1");6 // no break!7 case 2:8 System.out.println("a + b is 2");9 // no break!10 case 3:11 System.out.println("a + b is 3"); // matches here12 // no break!13 case 4:14 System.out.println("a + b is 4"); // fall-through!15 // no break!16 default:17 System.out.println("default"); // fall-through!18}a + b is 3 a + b is 4 default
break is one of the most common bugs in switch statements. Always add break unless you intentionally want fall-through behavior.`default` Can Be Anywhere
The default block does not have to be at the bottom. However, if it is not at the end, it must have a break to prevent fall-through.
1int a = 9, b = 1; // a + b = 102
3switch (a + b) {4 case 1:5 System.out.println("one");6 break;7 default:8 System.out.println("default: " + (a + b)); // matches here9 // no break — falls through to case 210 case 2:11 System.out.println("a + b is 2");12 break; // stops here13 case 3:14 System.out.println("three");15 break;16}default: 10 a + b is 2
default is used before the last case and has no break, it falls through to the next case below it. Best practice: keep default at the end, or always use break after it.Combining Cases (Clubbing)
When multiple case values should run the same code, you can club them:
1String month = "March";2
3// Method 1 — stacked cases (separate lines)4switch (month) {5 case "January":6 case "February":7 case "March":8 System.out.println("Month is in Quarter 1");9 break;10 case "April":11 case "May":12 case "June":13 System.out.println("Month is in Quarter 2");14 break;15 default:16 System.out.println("Other quarter");17}Month is in Quarter 1
You can also write multiple values on one line (Java 14+):
1switch (month) {2 case "January", "February", "March":3 System.out.println("Quarter 1");4 break;5}Switch Statement Rules
| Rule | Detail |
|---|---|
| No duplicate case values | Two cases with the same value = compile error |
| Expression and case types must match | switch(intVal) → cases must be int; switch(stringVal) → cases must be String |
| Case values must be literals or constants | Variables are allowed only if declared final |
| Not all cases need to be handled | Default is optional in switch statement; missing cases just don't execute |
| Nested switch | A switch inside another switch is fully supported |
Case Value Must Be Literal or Constant
1int caseValue = 1; // not final — NOT allowed as case value2final int CONST_VALUE = 1; // final — allowed as case value3
4switch (someExpression) {5 case 1: // ✅ literal6 case CONST_VALUE: // ✅ final constant7 // case caseValue: // ❌ compile error — non-final variable8}Supported Data Types in Switch
Switch expressions/statements support 10 types:
| Category | Types |
|---|---|
| Primitive | byte, short, int, char |
| Wrapper | Byte, Short, Integer, Character |
| Other | String, enum |
float, double, long, and boolean are NOT supported in switch. Switch works by equality comparison (==), and floating-point equality is unreliable.Nested Switch
1Day day = Day.MONDAY;2
3switch (day) {4 case MONDAY:5 int outputValue = 1;6
7 switch (outputValue) { // nested switch inside case MONDAY8 case 1:9 System.out.println("Output value is one");10 break;11 }12 break;13 default:14 System.out.println("Other day");15}Output value is one
4. Switch Expression (Java 12+)
What's Different?
The switch expression allows the switch to return a value that can be assigned to a variable. It also introduces the arrow -> syntax that eliminates the need for break and prevents accidental fall-through.
The Problem Switch Expression Solves
In a switch statement, you cannot directly return a value:
1// ❌ This does NOT work — return is not allowed inside switch case2String result = switch (value) {3 case 1: return "one"; // ❌ Compile error4};The traditional workaround:
1String result = "";2switch (value) {3 case 1:4 result = "one";5 break;6 case 2:7 result = "two";8 break;9}10// result is now setThis is verbose and error-prone. Switch expression fixes this.
Arrow Label Syntax (`->`)
1int value = 1;2
3String outputVal = switch (value) {4 case 1 -> "one"; // returns "one" when value == 15 case 2 -> "two";6 case 3 -> "three";7 default -> "other";8};9
10System.out.println(outputVal); // oneone
Key Properties of Arrow Syntax
| Property | Detail |
|---|---|
No break needed | The arrow automatically exits after the expression |
| No fall-through | Each case is isolated — arrow prevents fall-through |
| Returns a value | The right side of -> is the value returned for that case |
| Must cover all cases | Switch expression must handle every possible input (or have a default) |
All Cases Must Be Covered
Switch expression assigns a value to a variable, so every possible input must produce a result:
1int value = 1;2
3// ❌ Compile error — switch expression does not cover all possible inputs4String outputVal = switch (value) {5 case 1 -> "one";6 case 2 -> "two";7 // Missing default — compiler complains even if value is always 18};Fix — add default:
1String outputVal = switch (value) {2 case 1 -> "one";3 case 2 -> "two";4 default -> "other"; // ✅ covers all remaining cases5};enum types, if you handle every enum constant explicitly, you don't need a default. For other types like int, you always need default since the range of possible values is too large to enumerate.Using Blocks with `yield`
The arrow -> returns a single expression — you cannot write multiple lines. If you need a code block (multiple statements before returning), use yield:
1int value = 2;2
3String outputVal = switch (value) {4 case 1 -> "one"; // single expression — no yield needed5
6 case 2 -> { // block — yield required to return7 String temp = "tw";8 temp = temp + "o"; // some logic9 yield temp; // return value using yield10 }11
12 case 3 -> {13 System.out.println("Preparing three...");14 yield "three";15 }16
17 default -> "other"; // single expression18};19
20System.out.println(outputVal); // twoPreparing three... (only if value = 3) two
Arrow vs Block in Switch Expression
| Form | When to Use | break needed? | yield needed? |
|---|---|---|---|
case X -> expression | Single return value, no extra logic | ❌ No | ❌ No |
case X -> { ... yield val; } | Multiple statements before returning | ❌ No | ✅ Yes |
Switch Statement vs Switch Expression Full Comparison
| Feature | Switch Statement | Switch Expression (Java 12+) |
|---|---|---|
| Returns a value | ❌ No | ✅ Yes |
break required | ✅ Yes (to prevent fall-through) | ❌ No (arrow syntax handles it) |
| Fall-through possible | ✅ Yes (if break omitted) | ❌ No (with arrow syntax) |
| All cases must be handled | ❌ No | ✅ Yes (compile error otherwise) |
yield keyword | ❌ N/A | ✅ Used to return from a block |
Arrow -> syntax | ❌ Not available | ✅ Available |
| Java version | All versions | Java 12+ |
5. Iterative Statements
`for` Loop
Definition
Repeats a block of code a known number of times. Contains three parts: initialization, condition check, and increment/decrement — all in one line.
Syntax
1for (initialization; condition; increment/decrement) {2 // executed while condition is true3}Three Parts Explained
| Part | Purpose | Example |
|---|---|---|
| Initialization | Declare and set the loop variable (runs once at start) | int val = 1 |
| Condition | Checked before each iteration; loop runs while true | val <= 10 |
| Increment/Decrement | Updates the loop variable after each iteration | val++ |
Execution Flow
Code Example
1for (int val = 1; val <= 10; val++) {2 System.out.println(val);3}1 2 3 4 5 6 7 8 9 10
Step-by-Step
| Iteration | val | val <= 10 | Action |
|---|---|---|---|
| 1 | 1 | ✅ true | Print 1, val → 2 |
| 2 | 2 | ✅ true | Print 2, val → 3 |
| ... | ... | ... | ... |
| 10 | 10 | ✅ true | Print 10, val → 11 |
| 11 | 11 | ❌ false | Exit loop |
Nested `for` Loop
Two (or more) for loops where the inner loop runs completely for each iteration of the outer loop. Most commonly used for 2D matrix traversal.
Code Example
1for (int x = 1; x <= 3; x++) {2 for (int y = 1; y <= 3; y++) {3 System.out.print("(" + x + "," + y + ") ");4 }5 System.out.println(); // new line after each row6}(1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3)
Execution Pattern
1x=1: y runs 1, 2, 32x=2: y runs 1, 2, 33x=3: y runs 1, 2, 34Total iterations = 3 × 3 = 9`while` Loop
Definition
Repeats a block while the condition is true. The condition is checked before each iteration — if it's false from the start, the loop body never executes.
Syntax
1initialization;2while (condition) {3 // loop body4 increment/decrement;5}Code Example
1int value = 1;2
3while (value <= 5) {4 System.out.println(value);5 value++;6}1 2 3 4 5
`do-while` Loop
Definition
Similar to while, but the condition is checked after the loop body executes. This guarantees the loop body runs at least once, even if the condition is initially false.
Syntax
1initialization;2do {3 // loop body — runs at least once4 increment/decrement;5} while (condition); // semicolon required herewhile. This is unique to do-while and is a common syntax mistake.Code Example
1int val = 1;2
3do {4 System.out.println(val);5 val++;6} while (val <= 5);1 2 3 4 5
The "At Least Once" Guarantee
1int val = 100; // condition is false from start2
3while (val <= 5) {4 System.out.println("while: " + val); // NEVER executes5}6
7do {8 System.out.println("do-while: " + val); // executes ONCE9 val++;10} while (val <= 5);do-while: 100
`while` vs `do-while` Comparison
| Feature | while | do-while |
|---|---|---|
| Condition checked | Before each iteration | After each iteration |
| Minimum executions | 0 (condition false initially → never runs) | 1 (always runs at least once) |
| Use when | May need to run 0 times | Must run at least once |
Semicolon after while | ❌ No | ✅ Yes — } while (cond); |
`for-each` Loop
Definition
Designed specifically to iterate over arrays or collections. Simpler and less error-prone than a regular for loop when you don't need the index.
Syntax
1for (DataType variable : arrayOrCollection) {2 // use variable — it holds the current element3}Code Example Iterating an Array
1int[] numbers = {1, 2, 3, 4, 5};2
3for (int val : numbers) {4 System.out.println(val);5}1 2 3 4 5
How It Works
`for-each` vs `for` Loop
| Feature | for Loop | for-each Loop |
|---|---|---|
| Index access | ✅ Yes | ❌ No |
| Modify array elements | ✅ Yes (via index) | ❌ No (variable is a copy) |
| Readability | ❌ More verbose | ✅ Cleaner |
| Works with collections | ✅ With iterator | ✅ Directly |
| Use when | Need index or modifying elements | Just reading/processing elements |
Loop Comparison All Four
| Loop | Condition Check | Min Runs | Best For |
|---|---|---|---|
for | Before each iteration | 0 | Known iteration count |
while | Before each iteration | 0 | Unknown count, check first |
do-while | After each iteration | 1 (always) | Must run at least once |
for-each | After each element | 0 (empty collection) | Iterating arrays/collections |
6. Branching Statements
Branching statements alter the normal flow of execution inside loops (and switch statements).
`break`
Definition
Immediately exits the nearest enclosing loop or switch block. Execution continues with the first statement after that loop/switch.
Syntax
1break; // exits the immediately enclosing loop or switchCode Example
1for (int val = 1; val <= 10; val++) {2 if (val == 3) {3 break; // exit the loop when val is 34 }5 System.out.println(val);6}7System.out.println("After loop");1 2 After loop
`break` in Nested Loops Important!
break only exits the immediately enclosing loop. The outer loop continues:
1for (int x = 1; x <= 3; x++) {2 for (int y = 1; y <= 3; y++) {3 if (y == 2) {4 break; // exits INNER loop only5 }6 System.out.println("x=" + x + ", y=" + y);7 }8}x=1, y=1 x=2, y=1 x=3, y=1
The inner loop breaks at y=2 every time, but the outer loop (x) continues normally.
`continue`
Definition
Skips the remaining statements in the current iteration and moves to the next iteration of the loop. Does NOT exit the loop — it just skips the current cycle.
Syntax
1continue; // skip rest of current iteration, go to nextCode Example
1for (int value = 1; value <= 10; value++) {2 if (value == 3) {3 continue; // skip printing 3, go to val=44 }5 System.out.println(value);6}1 2 4 5 6 7 8 9 10
(3 is skipped — the continue jumped straight to value++ when value == 3)
`break` vs `continue` Step-by-Step Comparison
For a loop printing 1 to 5, stopping/skipping at 3:
| Value | With break | With continue |
|---|---|---|
| 1 | Print 1 | Print 1 |
| 2 | Print 2 | Print 2 |
| 3 | Exit loop | Skip — go to next iteration |
| 4 | (loop ended) | Print 4 |
| 5 | (loop ended) | Print 5 |
| Output | 1 2 | 1 2 4 5 |
Flowchart `break` vs `continue`
`break` vs `continue` Summary
| Feature | break | continue |
|---|---|---|
| Effect | Exits the loop entirely | Skips current iteration only |
| Loop continues? | ❌ No — loop ends | ✅ Yes — next iteration runs |
| Works with | for, while, do-while, switch | for, while, do-while |
| Targets | Immediately enclosing loop/switch | Immediately enclosing loop |
7. Interview Question Bank
Decision Making
| Question | Key Answer |
|---|---|
| What are the types of control flow statements in Java? | Decision making, iterative, branching |
What is the difference between if-else and switch? | switch compares one expression against fixed constants; if-else can evaluate any boolean expression |
Can you use a return inside a switch statement? | Not to return from the switch itself; return exits the enclosing method |
| What data types can be used in a switch expression? | byte, short, int, char, their wrappers, String, enum — 10 total; no float, double, long, boolean |
| Can two switch cases have the same value? | No — compile error |
| Must case values be constants? | Yes — literals or final variables only |
Is default mandatory in switch? | In switch statement — no; in switch expression — yes (or all cases must be covered) |
Can default be placed anywhere in switch? | Yes — but needs break if not at the end to prevent fall-through |
Switch Expression
| Question | Key Answer |
|---|---|
| When was switch expression introduced? | Java 12 |
What is the -> arrow in switch expression? | Returns value from that case; eliminates need for break; prevents fall-through |
What is yield? | Keyword to return a value from a code block ({ }) inside a switch expression case |
| Must switch expressions handle all cases? | Yes — compile error otherwise; add default to cover remaining cases |
| Difference between switch statement and switch expression? | Expression returns a value, uses ->, no break needed, all cases must be covered |
Loops
| Question | Key Answer |
|---|---|
What is the difference between while and do-while? | while checks condition first (0+ runs); do-while checks after (1+ runs — always runs at least once) |
When would you use do-while over while? | When the loop body must execute at least once regardless of the condition |
What is for-each and when is it used? | Enhanced for loop to iterate over arrays/collections; cleaner but no index access |
Can you modify array elements inside a for-each? | No — the loop variable is a copy of the element, not the element itself |
What are the three parts of a for loop? | Initialization, condition check, increment/decrement |
Branching
| Question | Key Answer |
|---|---|
What does break do inside a loop? | Immediately exits the nearest enclosing loop or switch |
What does continue do? | Skips the rest of the current iteration and moves to the next one |
Does break in an inner loop affect the outer loop? | No — only exits the immediately enclosing loop |
What is the difference between break and continue? | break exits the loop; continue skips current iteration but continues the loop |
8. Master Summary
Quick Revision Bullets
Decision Making:
- ✅ Simple
if— runs block if conditiontrue; skips otherwise - ✅
if-else— exactly one of two blocks always executes - ✅
if-else-ifladder — top-to-bottom evaluation; first match wins;elseis optional fallback - ✅ Nested
if—if-elseinside anotherif-else; no depth limit - ✅ Switch statement — compares expression against constant case values; similar to
if-else-ifladder - ✅
breakin switch — exits the switch block; without it, execution falls through to next case - ✅
defaultin switch — runs if no case matches; optional in switch statement; can be anywhere (usebreakif not last) - ✅ Switch data types —
byte,short,int,char, wrappers,String,enum— 10 types; NOTfloat,double,long - ✅ Case values — must be literals or
finalconstants; no non-final variables - ✅ Two cases cannot have same value — compile error
Switch Expression (Java 12+):
- ✅ Returns a value; assignable to a variable
- ✅ Arrow
->syntax: nobreakneeded, no fall-through - ✅ All cases must be handled — compiler error otherwise; always add
default - ✅ For multi-line blocks: use
{ }and return value withyield
Iterative:
- ✅
for—init; condition; increment— use when iteration count is known - ✅ Nested
for— inner loop runs completely for each outer iteration; used in 2D matrix traversal - ✅
while— condition checked first; may run 0 times - ✅
do-while— condition checked after; always runs at least once;;afterwhile(...) - ✅
for-each— iterates arrays/collections; cleaner but no index access, can't modify elements
Branching:
- ✅
break— exits the immediately enclosing loop or switch; outer loops unaffected - ✅
continue— skips rest of current iteration; loop continues with next iteration - ✅
breakoutput (skipping 3 in 1-5):1 2 - ✅
continueoutput (skipping 3 in 1-5):1 2 4 5
End of Chapter — Java Control Flow Statements
Mastery check
How well can you recall this?
Finished this lesson?