Chapter 03
Java Control Statements
5 topics · 1 sections · beginner-friendly study notes · Updated
Control statements decide which code runs and how many times.
Java provides decision statements (if-else, switch), loops (for, while, do-while) and jump statements (break, continue).
This chapter explains each with complete programs.
Every algorithm uses decisions and repetition.
Loops and conditions are the heart of coding tests and interviews.
Input validation, menus, grading, searching arrays, printing patterns, retry logic and processing files line by line.
if-else in Java
The if statement executes a block of code only when its boolean condition is true. The if-else statement adds an else block that runs when the condition is false. An else-if ladder tests several conditions in order.
In short: If something is true do this, otherwise do that.
Think about it
Programs must react to different inputs. Decisions are the first step from straight-line code to real logic. Grade calculation, login checks, age validation and discount rules.
Forms: simple if, if-else, if-else-if ladder and nested if.
The condition must be a boolean expression; unlike C, if (x = 5) with an int is a compile error.
Braces are optional for a single statement but strongly recommended, because a missing brace is a common bug.
In an else-if ladder only the first true branch runs and the rest are skipped.
The dangling else always belongs to the nearest if.
The ternary operator is a short form of if-else that returns a value.
Compare strings with equals(), never with ==, and put the literal first ("yes".
equals(s)) to avoid NullPointerException.
Key points
- Condition: Boolean expression that decides the branch.
- Branch: One path of code chosen by a decision.
- Ladder: Chain of else-if tests.
- Nested if: An if placed inside another if.
- The condition of if must be boolean in Java; 1 or 0 are not allowed.
- Always use braces { } even for one statement.
- In an else-if ladder, order the conditions from most specific to most general.
- Use equals() to compare string content.
Example
Codegrade ladder and leap year:
import java.util.Scanner;
public class IfElseDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter marks (0-100): ");
int marks = sc.nextInt();
if (marks < 0 || marks > 100) {
System.out.println("Invalid marks");
} else if (marks >= 90) {
System.out.println("Grade A+");
} else if (marks >= 75) {
System.out.println("Grade A");
} else if (marks >= 60) {
System.out.println("Grade B");
} else if (marks >= 40) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
// nested if: leap year
System.out.print("Enter a year: ");
int year = sc.nextInt();
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) System.out.println(year + " is a leap year");
else System.out.println(year + " is not a leap year");
} else {
System.out.println(year + " is a leap year");
}
} else {
System.out.println(year + " is not a leap year");
}
// ternary shortcut
String parity = (marks % 2 == 0) ? "even" : "odd";
System.out.println("Marks are " + parity);
sc.close();
}
}switch Statement in Java
The switch statement selects one block of code from many alternatives by comparing a value with case labels. It works with byte, short, char, int, their wrappers, String and enum. Java 14+ adds switch expressions with arrow syntax that return a value.
In short: Switch is a clean way to pick one action out of many choices.
Think about it
Switch is clearer than a long else-if ladder when you compare one variable with many constants. Menu choices, day-of-week names, command parsers and state machines.
Classic syntax: switch (value) { case 1: ...
; break; default: ...
}.
Without break the execution falls through into the next case, which is a feature but also a common bug.
The default case runs when nothing matches and can appear anywhere.
Case labels must be compile-time constants and unique.
The long, float, double and boolean types are not allowed in classic switch.
Strings are compared with equals(); a null selector throws NullPointerException.
Java 14 introduced arrow cases that never fall through: case 1, 7 -> "Weekend";.
A switch expression can yield a value: String r = switch (day) { case 1 -> "Mon"; default -> "Other"; };.
For multi-line blocks inside an expression use yield.
Java 21 adds pattern matching for switch.
Key points
- case: A label compared against the switch value.
- default: Block that runs when no case matches.
- Fall-through: Continuing into the next case when break is missing.
- yield: Returns a value from a block inside a switch expression.
- Forgetting break causes fall-through.
- switch does not support long, float, double or boolean.
- Arrow-style cases do not need break.
- Duplicate case labels are a compile-time error.
Read more
Example
Codeclassic and modern switch:
public class SwitchDemo {
enum Color { RED, GREEN, BLUE }
public static void main(String[] args) {
// classic switch with break
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("Other day");
}
// fall-through (no break)
int n = 2;
switch (n) {
case 1: System.out.println("one");
case 2: System.out.println("two"); // starts here
case 3: System.out.println("three"); // falls through
break;
default: System.out.println("default");
}
// String switch
String cmd = "stop";
switch (cmd) {
case "start" -> System.out.println("Starting");
case "stop" -> System.out.println("Stopping");
default -> System.out.println("Unknown");
}
// switch expression with yield (Java 14+)
int month = 2;
int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> {
boolean leap = false;
yield leap ? 29 : 28;
}
default -> -1;
};
System.out.println("Days: " + days);
// enum switch
Color c = Color.GREEN;
String hex = switch (c) {
case RED -> "#FF0000";
case GREEN -> "#00FF00";
case BLUE -> "#0000FF";
};
System.out.println(hex);
}
}for Loop in Java
The for loop repeats a block of code a known number of times. Its header has three parts: initialisation, condition and update: for (init; condition; update) { body }. The enhanced for loop (for-each) visits every element of an array or Iterable.
In short: Use for when you know how many times to repeat, like counting from 1 to 10.
Think about it
Repetition is how programs process lists, tables and ranges without repeating code. Printing a multiplication table, summing an array, drawing star patterns and iterating records.
Execution order: init runs once; the condition is checked before each iteration; the body runs; the update runs; then the condition is checked again.
Any part of the header may be left empty: for (;;) is an infinite loop.
You can declare several variables: for (int i = 0, j = 10; i < j; i++, j--).
A variable declared in the header is scoped to the loop.
Nested for loops are used for tables and patterns: the inner loop completes fully for each step of the outer loop.
The enhanced for loop, for (int x : arr), is shorter and safe from index errors, but you cannot change the array element through the loop variable and you do not know the index.
Do not modify a collection while iterating it with for-each; this throws ConcurrentModificationException.
Key points
- Iteration: One execution of the loop body.
- Loop variable: Variable that controls the loop, e.g. i.
- Nested loop: A loop inside another loop.
- For-each: Enhanced for loop over arrays and collections.
- Infinite loop: Loop whose condition never becomes false.
- for (;;) is a valid infinite loop.
- Off-by-one errors come from using
<=instead of < with array length. - The scope of i declared in the header ends with the loop.
- For-each cannot go backwards and cannot modify the array reference.
Example
Codecounting, tables and patterns:
public class ForLoopDemo {
public static void main(String[] args) {
// 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();
// table of 7
for (int i = 1; i <= 10; i++) {
System.out.println("7 x " + i + " = " + (7 * i));
}
// sum of an array with for-each
int[] marks = {70, 85, 90, 65};
int sum = 0;
for (int m : marks) {
sum += m;
}
System.out.println("Sum = " + sum + ", Average = " + (double) sum / marks.length);
// two variables in the header
for (int i = 0, j = 5; i < j; i++, j--) {
System.out.println("i=" + i + " j=" + j);
}
// nested loop: right triangle of stars
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("* ");
}
System.out.println();
}
// reverse loop
for (int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
}
}while and do-while Loop
The while loop checks its condition first and repeats the body while the condition is true (entry-controlled). The do-while loop runs the body once and then checks the condition (exit-controlled), so the body always executes at least once.
In short: Use while when you do not know in advance how many times to repeat. Use do-while when the code must run at least once.
Think about it
Many real tasks repeat until something happens rather than for a fixed count. Menu-driven programs, password retry, reading lines until the end of a file and the Euclid algorithm for GCD.
Syntax
while (condition) { body } and do { body } while (condition)
— note the semicolon after the do-while condition.In a while loop the body may run zero times.
Always change something inside the loop that moves the condition toward false, otherwise it runs forever.
Common use: reading input until the user types a stop value, digit processing (while (n > 0) { n /= 10; }), menus that repeat until the user chooses exit, and retry logic.
Choose for when the count is known, while when it depends on a condition, and do-while for menus and validation prompts.
Key points
- Entry-controlled: Condition checked before the body (for, while).
- Exit-controlled: Condition checked after the body (do-while).
- Sentinel: Special value that ends the loop, e.g. -1.
- Infinite loop: Loop that never ends because the condition never turns false.
- do-while ends with a semicolon.
- do-while executes at least once.
- while (true) with a break inside is a common pattern.
- Forgetting to update the loop variable creates an infinite loop.
Read more
Example
Codedigits, GCD and menu:
import java.util.Scanner;
public class WhileDemo {
public static void main(String[] args) {
// digits of a number
int n = 4721, sum = 0, original = n;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Digit sum of " + original + " = " + sum); // 14
// GCD with Euclid
int a = 48, b = 18;
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
System.out.println("GCD = " + a); // 6
// do-while: menu that runs at least once
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("1. Add 2. Subtract 0. Exit");
System.out.print("Choice: ");
choice = sc.nextInt();
switch (choice) {
case 1 -> System.out.println("Add selected");
case 2 -> System.out.println("Subtract selected");
case 0 -> System.out.println("Bye");
default -> System.out.println("Invalid choice");
}
} while (choice != 0);
sc.close();
// while(true) with break
int count = 0;
while (true) {
count++;
if (count == 3) break;
}
System.out.println("count = " + count);
}
}break and continue in Java
break exits the nearest enclosing loop or switch immediately. continue skips the rest of the current iteration and moves to the next iteration. A label lets break or continue target an outer loop.
In short: break means stop the loop. continue means skip this round and go to the next one.
Think about it
These statements make searching and filtering loops short and efficient. Stop searching when an element is found; skip invalid records; leave a nested search of a matrix.
In a for loop, continue jumps to the update part and then to the condition check.
In a while or do-while loop, continue jumps directly to the condition check, so you must update the variable before continue or the loop may never end.
A labelled break exits the labelled outer loop: outer: for (...
) { for (...
) { if (...
) break outer; } }.
A labelled continue skips to the next iteration of the labelled loop.
Java has no goto, so labels are the controlled way to leave nested loops.
The return statement also leaves a loop by leaving the whole method.
System.
exit(0) stops the entire program.
break inside a switch inside a loop exits only the switch, not the loop.
Key points
- break: Terminates the nearest loop or switch.
- continue: Skips to the next iteration.
- Label: Name placed before a loop for targeted jumps.
return: Leaves the current method.- break inside switch inside a loop only ends the switch.
- In while loops update the counter before continue.
- Java has no goto statement; use labels carefully.
- Labelled break works only inside the labelled statement.
Example
Codebreak, continue and labels:
public class BreakContinueDemo {
public static void main(String[] args) {
// break: stop at first multiple of 7
for (int i = 1; i <= 50; i++) {
if (i % 7 == 0) {
System.out.println("First multiple of 7: " + i);
break;
}
}
// continue: print only odd numbers
for (int i = 1; i <= 9; i++) {
if (i % 2 == 0) continue;
System.out.print(i + " ");
}
System.out.println();
// labelled break: find a value in a matrix
int[][] grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int target = 5;
boolean found = false;
search:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == target) {
System.out.println("Found at row " + r + ", col " + c);
found = true;
break search;
}
}
}
System.out.println("found = " + found);
// labelled continue: skip rows that contain 0
int[][] data = {{1, 2}, {0, 5}, {3, 4}};
outer:
for (int[] row : data) {
for (int v : row) {
if (v == 0) continue outer;
}
System.out.println("Clean row: " + row[0] + "," + row[1]);
}
// continue in while: update BEFORE continue
int i = 0;
while (i < 6) {
i++;
if (i == 3) continue;
System.out.print(i + " "); // 1 2 4 5 6
}
System.out.println();
}
}Solved examples
Print all even numbers from 1 to 20 using a for loop.
2 4 6 ... 20
Formula Applied:—Approach note: Changing the update part is faster than testing i % 2 inside the loop.
Find the output: int x = 1; do { System.out.print(x + " "); x++; } while (x < 1);
Printed values
Formula Applied:—Approach note: A while loop with the same condition would print nothing.
Find the output: for (int i = 1; i <= 5; i++) { if (i == 3) continue; if (i == 5) break; System.out.print(i + " "); }
Printed values
Formula Applied:—Approach note: Trace each value of i in a small table.
Using a for-loop, compute the sum of integers from 1 to 10 inclusive.
Sum value
Formula Applied:—Approach note: Off-by-one: use i <= n for inclusive ranges.
Real-world applications
Using Java Control Statements in real projects
Input validation, menus, grading, searching arrays, printing patterns, retry logic and processing files line by line.
Common mistakes
❌ Myth: if (x = 5) is allowed in Java like in C.
Why this is wrong: The condition must be boolean; assignment gives an int.
✅ Verified Truth: It is a compile-time error unless x is boolean.
⚠️ Exam Tip: Use == for comparison.
❌ Myth: switch can use long and double.
Why this is wrong: Classic switch supports only byte, short, char, int, wrappers, String and enum.
✅ Verified Truth: long, float, double and boolean are not allowed.
⚠️ Exam Tip: Mention Java 21 pattern switch only if asked.
❌ Myth: break inside a switch in a loop stops the loop.
Why this is wrong: break stops only the nearest switch or loop.
✅ Verified Truth: Use a labelled break or a flag to leave the outer loop.
⚠️ Exam Tip: Check which structure is closest to the break.
❌ Myth: do-while may run zero times.
Why this is wrong: The condition is checked after the body.
✅ Verified Truth: do-while always runs at least once.
⚠️ Exam Tip: Contrast it with while in every answer.
Revision notes
Control statements decide which code runs and how many times. Java provides decision statements (if-else, switch), loops (for, while, do-while) and jump statements (break, continue). This chapter explains each with complete programs.
High-Yield Quick Revision Points
- if needs a boolean condition; else-if ladder runs only the first true branch.
- Compare strings with equals(), not ==.
- switch works with byte, short, char, int, wrappers, String and enum; missing break causes fall-through.
- Arrow switch (Java 14+) has no fall-through and can return a value; use yield in blocks.
- for = counted loop; while = condition first; do-while = body first, ends with semicolon.
- For-each loops over arrays and Iterables but cannot give the index.
- break leaves the nearest loop or switch; continue skips to the next iteration.
- Labels with break or continue control nested loops; Java has no goto.
Practice questions
Which loop always executes at least once?
What happens when break is missing in a switch case?
Which type is NOT allowed in a classic switch?
What does for (;;) do?
What is the output of: for (int i = 0; i < 3; i++) System.out.print(i);
What does continue do?