Chapter 3.1: Control Structures
Introduction
Learning Outcomes
Explain how sequence, selection and loops direct the flow of a program.
Write conditional code with if, if-else, else if chains, nested decisions and &&/|| conditions.
Compare a value against constants; explain what break does and how “fall-through” works.
Use for, while and do-while where each fits; avoid infinite loops and off-by-one errors.
Count how many times nested loops run in patterns, tables and digit examples.
Predict variable values and output by tracing a program step by step; show the effect of break and continue.
Introduction
Control Structures
- Control structures direct a program's flow: which statements run, in what order, how often.
- Java has three basic control structures; any program can be built from them:
Statements run top to bottom, once each.
A condition picks one of two (or more) paths: if-else, switch.
Work repeats while a condition holds: for, while, do-while.
Why it matters: decisions let a program react to different situations and user input; loops automate repetitive work.
Introduction · Step-by-step code trace
Sequential Execution
Code runs top to bottom, line by line; one operation finishes before the next starts. A program with no control structures is sequential.
The first line runs: x gets 5. The next line does not start until this one finishes.
Second line: y gets 10.
The third line uses the results of the first two: 5 + 10 = 15.
The last line prints the result. If the lines were reordered (e.g. line 3 first), the program would not compile.
int x = 5; int y = 10; int result = x + y; System.out.println(result);
Decisions: if
Making Decisions
- Decision making means the program chooses which path to follow at run time.
- It lets the program carry out different actions depending on conditions.
- In Java this is done with
if-elseandswitch-case. - A condition is a
true- orfalse-valued boolean expression. - Analogy: a sign at a fork in the road. “If it's raining, take an umbrella; otherwise don't.”
- Why it matters: the program responds to different situations and user input, the flow is steered, and flexibility increases.
| Operator | Meaning | Example (x = 7) |
|---|---|---|
== | equal | x == 7 → true |
!= | not equal | x != 7 → false |
< > | less / greater | x < 10 → true |
<= >= | less-or-equal / greater-or-equal | x >= 8 → false |
= is assignment, == is comparison. if (x = 7) does not compile: the condition must be a boolean.Decisions: if
The if-else Statement
if (condition) { // runs if the condition is true } else { // runs if the condition is false }
- First the condition is evaluated.
- If the condition is true (
true), theifblock runs and theelseblock is skipped. - If the condition is false (
false), theifblock is skipped and theelseblock runs. - The
elseis optional. Of the two blocks, at most one runs. - The condition always goes in parentheses:
if (condition).
Decisions: if
if Alone, and Braces
else-less if
int temp = 35; if (temp > 30) { System.out.println("It's hot!"); } System.out.println("The program continues.");
It's hot! The program continues.
If the condition were false (e.g. temp = 20), only “The program continues.” would print. After if, the next line always runs.
Pitfall: no braces
int temp = 35; if (temp > 40) System.out.println("Very hot!"); System.out.println("Drink water.");
Drink water.
Without braces, if owns only the first statement. Indentation means nothing to Java: “Drink water.” runs regardless of the condition. That's why braces { } are used even for one-line blocks.
Decisions: if · Step-by-step code trace
Example: Age Check
age is assigned 18.
The condition is evaluated: 18 >= 18 → true. Flow takes the “Y” (yes) branch.
The if block runs and prints the message.
The else block (line 5) is skipped. age = 16 would make it false, and only “You cannot get a license.” would be printed.
int age = 18; if (age >= 18) { System.out.println("You can get a license."); } else { System.out.println("You cannot get a license."); }
Decisions: if · Step-by-step code trace
Example: Absolute Value
To read from the keyboard, create a Scanner object (this needs import java.util.Scanner; at the top of the file).
The user is told what to enter. print does not move to a new line; the cursor waits on the same line.
The user types -7,5. On a computer with a Turkish locale the decimal separator is a comma, so -7.5 throws InputMismatchException.
absValue is declared but has no value yet.
Condition: -7.5 < 0 → true.
-num = −(−7.5) = 7.5 is assigned. The else block is skipped.
The result is printed. println, however, always prints a double value with a dot: 7.5.
Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); double num = scanner.nextDouble(); double absValue; if (num < 0) { absValue = -num; } else { absValue = num; } System.out.println("Absolute value: " + absValue);
Decisions: if
else-if Chains
import java.util.Scanner; public class PositiveNegative { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); double num = scanner.nextDouble(); if (num > 0) { System.out.println("Positive."); } else if (num < 0) { System.out.println("Negative."); } else { System.out.println("Zero."); } } }
- With more than two options,
else iftests the conditions one after another. - Conditions are tried top to bottom; the block of the first true condition runs, and the rest are skipped.
- If none is true, the final
elseruns (if present).
Three separate runs
Enter a number: 4 Positive.
Enter a number: -2 Negative.
Enter a number: 0 Zero.
Decisions: if · Step-by-step code trace
else-if Chain: Letter Grade
grade = 75.
75 >= 90 → false. On to the next else if.
75 >= 80 → false. On to the next condition.
75 >= 70 → true: the first true condition is found.
“C” is printed.
The remaining conditions (including grade >= 60) are never tested. Order matters: if >= 60 were at the top, 75 would get a “D”.
int grade = 75; if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else if (grade >= 70) { System.out.println("C"); } else if (grade >= 60) { System.out.println("D"); } else { System.out.println("F"); }
Decisions: if
Nested Decisions
- Inside the block of one decision you can place another decision.
- Useful for more complex conditions: once the outer condition holds, a second question is asked.
- The inner
ifis tested only if the outer condition is true. - Deep nesting hurts readability; indent properly and, where possible, flatten with
&&orelse if:if (age >= 18) { if (hasLicense) … }andif (age >= 18 && hasLicense) …do the same thing. - Range checks are also written with
&&:grade >= 60 && grade < 90;60 <= grade < 90does not compile.
if (cond1) { if (cond2) { // cond1 AND cond2 true } } else { // cond1 false }
Decisions: if · Step-by-step code trace
Nested Decision: Letter Grade
grade = 85.
Outer condition: 85 >= 60 → true. Enter the outer if block.
Inner condition: 85 >= 90 → false. Go to the inner else.
“Letter grade: B” is printed.
The outer else (line 9) is skipped. grade = 45 would skip the inner if entirely and print F directly.
int grade = 85; if (grade >= 60) { if (grade >= 90) { System.out.println("Letter grade: A"); } else { System.out.println("Letter grade: B"); } } else { System.out.println("Letter grade: F"); }
Decisions: if · Step-by-step code trace
Short-Circuit: Tracing the Code
b = 0: a / b would cause a division-by-zero error (ArithmeticException) if evaluated. count will count whether the right-hand sides run.
&& first evaluates the left side: b != 0 → false.
If the left is false, &&'s result is already false: a / b > 2 is never evaluated, so no error occurs. s1 = false.
||: left side b == 0 → true.
If the left is true, ||'s result is already true: ++count does not run, count stays 0. s2 = true.
Again &&; the left side b == 0 → true. The result is not yet known.
The right side must be evaluated: ++count → 1, 1 > 0 → true. s3 = true.
The three results are printed: false true true.
count = 1: only one of the three right-hand sides ran. Side effects (++) on the right of &&/|| are therefore misleading.
int a = 10, b = 0, count = 0; boolean s1 = b != 0 && a / b > 2; boolean s2 = b == 0 || ++count > 0; boolean s3 = b == 0 && ++count > 0; System.out.println(s1 + " " + s2 + " " + s3); System.out.println("count = " + count);
Decisions: switch
The switch-case Statement
- switch-case compares the value of a variable against a set of constant values and acts according to the match.
- It is used to choose one path among several options.
- When the same variable gets many
==comparisons, it is tidier than anelse ifchain. - Analogy: elevator buttons. The floor number you press picks where you go.
switch (variable) { // value being checked case value1: // one value per case // statements 1 break; case value2: // statements 2 break; // ... default: // if nothing matches // default statements (optional) }
Decisions: switch
How switch-case Works
- The variable is compared with the
casevalues top to bottom. - If a matching
caseis found, thatcase's statements run, and thenbreakexits theswitch. - If no
casematches, thedefaultsection (if any) runs. defaultabsent as well? Then theswitchexits without doing anything.breakmissing? Execution falls into the next case (fall-through).
Decisions: switch · Step-by-step code trace
Example: Finding the Season
month = 4.
season is declared, with no value yet.
switch (month): the value 4 is computed once, then the case labels are searched.
case 4 matches. The three case labels on that line lead to the same code.
season = "Spring".
break: switch ends; execution jumps past its closing brace (line 18).
default guarantees that season gets a value on every path; without it: variable season might not have been initialized.
int month = 4; String season; switch (month) { case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; case 12: case 1: case 2: season = "Winter"; break; default: season = "Unknown"; } System.out.println(month + ": " + season);
Decisions: switch · Step-by-step code trace
Forgetting break: Fall-Through
day = 2.
The case matching 2 is searched for.
case 1 is skipped, case 2 matches.
“Tuesday” is printed. There is no break here!
The case 3: label is not a test; execution falls through to the code below.
“Wednesday” is printed too, even though the day is not 3.
break exits the switch; default does not run.
Execution continues after the switch. To avoid fall-through, end every case with break.
int day = 2; switch (day) { case 1: System.out.println("Monday"); case 2: System.out.println("Tuesday"); case 3: System.out.println("Wednesday"); break; default: System.out.println("Other day"); } System.out.println("switch done");
Decisions: switch
switch: char and String
char-based simple calculator
int a = 12, b = 4; char op = '*'; int result; switch (op) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': result = a / b; break; default: System.out.println("Bad operator"); result = 0; } System.out.println(a + " " + op + " " + b + " = " + result);
12 * 4 = 48
String-based command selection (Java 7+)
String command = "stop"; switch (command) { case "start": System.out.println("Engine started"); break; case "stop": System.out.println("Engine stopped"); break; default: System.out.println("Unknown command"); }
Engine stopped
Short cases can go on a single line: case '+': result = a + b; break;. String comparison is case-sensitive: "Stop" ≠ "stop".
Decisions: switch
switch Rules
- The selector (the expression in parentheses) can be:
byte,short,char,int(and their wrappers),String,enum. long,float,double,booleancannot be used with a classicswitch.casevalues must be compile-time constants (5,'a',"stop",finalconstants).- The same value cannot appear in two
cases. - Ranges (
month >= 3 && month <= 5) or complex conditions needif-else.
double d = 2.5; switch (d) { ... }
error: selector type double is not allowedint b = 2; switch (a) { case b: break; }
error: constant expression requiredswitch (a) { case 1: break; case 1: break; }
error: duplicate case labelDecisions: switch
switch-case vs. if-else
if-else / else if | switch-case | |
|---|---|---|
| What is tested? | Any boolean condition: ranges, compound conditions, different variables | Equality of a single expression with constant values |
| Flexibility | More flexible | Only certain types and constant case values |
| With many options | Long chains can look messy | A neat, readable list |
| Pitfall | Conditions in the wrong order pick the wrong branch | break missing → falls into the cases below |
| Example | if (grade >= 90) … else if (grade >= 80) … | switch (month) { case 3: … } |
Every switch can be written as an else if chain; the reverse is not always possible (e.g. ranges like grade >= 90).
Decisions: switch
The New switch (Java 14+)
int month = 11; String season = switch (month) { case 3, 4, 5 -> "Spring"; case 6, 7, 8 -> "Summer"; case 9, 10, 11 -> "Autumn"; case 12, 1, 2 -> "Winter"; default -> "Unknown"; }; System.out.println(season);
Autumn
- Java 14 introduced the arrow form:
case 3, 4, 5 -> … - A
casecan take several values separated by commas. - The arrow form has no fall-through; no
breakis needed. - A switch expression produces a value that can be assigned directly; it ends with
;. - The expression form must cover every possibility: for
int,defaultis required. - This course uses the classic form; the arrow form is available from Java 14 on.
Application: Temperature
Temperature Conversion: Table and Formulas
| Celsius (°C) | Fahrenheit (°F) | Kelvin (K) |
|---|---|---|
| −40 | −40 | 233.15 |
| 0 | 32 | 273.15 |
| 25 | 77 | 298.15 |
| 100 | 212 | 373.15 |
°F = (°C × 1.8) + 32
°C = (°F − 32) / 1.8
K = °C + 273.15
Goal: translate the formulas into Java and compute them for one value.
Application: Temperature
Temperature Conversion: One Value
public class Program { public static void main(String[] args) { double celsius = 25.0; double fahrenheit = (celsius * 1.8) + 32; double kelvin = celsius + 273.15; System.out.println(celsius + " °C = " + fahrenheit + " °F = " + kelvin + " K"); } }
25.0 °C = 77.0 °F = 298.15 K
- A sequential program: three lines of computation, one line of output; no decisions or loops.
- Use
doublefor decimal values. Parentheses make the order explicit: firstcelsius * 1.8, then+ 32. +used with a string performs concatenation;doublevalues print as25.0.- Every computed value should be used: had
kelvinnot been printed, computing it would have been wasted.
Loops
Loops and Their Kinds
A loop repeats the same operation several times. Analogy: running 10 laps on a track; every lap has the same moves, and the lap counter goes up by one.
When the number of repetitions is known; works over a range of values.
for (int i = 0; i < 5; i++) { … }
Runs while a condition holds; the number of repetitions may not be known in advance.
while (condition) { … }
The condition comes last; the body runs at least once.
do { … } while (condition);
- Loops are handy for processing a data set in order and for repeating work; they matter especially with arrays and lists.
- One loop instead of writing the same line 100 times: the code becomes shorter, tidier and more readable.
Loops
The for Loop
- The header sets the loop's init, condition and update (increment) steps on one line, separated by
;. - The condition is checked before every pass (iteration); the update step changes the loop variable.
- Order of execution: 1 → 2 → 4 → 3 → 2 → 4 → 3 → … → 2 false → exit the loop.
i= 0, 1, 2, 3, 4: the body runs 5 times;ireaching 5 makes the condition false.iexists only inside the loop.
Loops
How Loops Work
- The loop starts with the init step.
- The condition is checked.
- If it holds, the statements in the loop body run.
- The update (increment) step is applied (
forloops). - If the condition still holds, the body runs again.
- When the condition fails, the loop exits and execution continues with the next statement.
- If the condition is false on the first check, the body never runs.
1. Init: the loop variable gets its first value (once).
2. The condition is checked.
3. If the condition is true, the body runs.
4. Update: the loop variable changes.
5. Back to the condition; steps 3–4–5 repeat while it is true.
6. When the condition is false, the loop exits.
Loops · Step-by-step code trace
Summing Numbers (for)
sum starts at 0 (the identity element of addition).
Init: count = 1 (once).
Condition: 1 <= 10 → true.
Pass 1: sum = 0 + 1 = 1.
count++ → 2, condition: 2 <= 10 → true.
Pass 2: sum = 1 + 2 = 3.
count++ → 3, condition: 3 <= 10 → true.
Pass 3: sum = 3 + 3 = 6. The update and condition repeat the same way on every pass.
Pass 4: sum = 6 + 4 = 10.
Pass 5: sum = 10 + 5 = 15.
Pass 6: sum = 15 + 6 = 21.
Pass 7: sum = 21 + 7 = 28.
Pass 8: sum = 28 + 8 = 36.
Pass 9: sum = 36 + 9 = 45.
Pass 10: sum = 45 + 10 = 55.
count++ → 11, condition: 11 <= 10 → false. The loop ends; the body ran exactly 10 times.
After the loop, sum is printed. count no longer exists: it lives only inside the loop.
int sum = 0; for (int count = 1; count <= 10; count++) { sum += count; } System.out.println("Sum: " + sum);
Loops
Summing a Range
import java.util.Scanner; public class RangeSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Start value (a): "); int a = input.nextInt(); System.out.print("End value (b): "); int b = input.nextInt(); int sum = 0; for (int i = a; i <= b; i++) { sum += i; } System.out.println("Sum of the numbers: " + sum); } }
Inputs: 3 and 7
Start value (a): 3 End value (b): 7 Sum of the numbers: 25
The loop variable i starts not at a fixed number but at the user's input a: 3 + 4 + 5 + 6 + 7 = 25.
Inputs: 7 and 3
Start value (a): 7 End value (b): 3 Sum of the numbers: 0
On the first check 7 <= 3 is false: the body never runs, and the sum stays 0. Fix: if a > b, swap the two first (with an if).
Loops
The while Loop
int i = 0; while (i < 5) { // statements in the loop i++; }
- Only a condition is checked; init and update are written separately, outside and inside the loop.
- Runs as long as the condition holds; the condition is tested before the body.
- The natural choice when the number of repetitions isn't known in advance (e.g. “until the user enters 0”).
- Beware of infinite loops!
i++missing →istays 0, the condition stays true and the program never ends.
Loops
for vs. while
for
int sum = 0; for (int count = 1; count <= 10; count++) { sum += count; } System.out.println("Sum: " + sum);
while
int sum = 0; int count = 1; while (count <= 10) { sum += count; count++; } System.out.println("Sum: " + sum);
Sum: 55
Both loops have the same three parts: init count = 1, condition count <= 10, update count++. for puts them on one line; while scatters them, and the update is easy to forget. Both print 55.
Loops · Step-by-step code trace
Computing a Factorial (while)
Goal: 5! = 1 × 2 × 3 × 4 × 5. The product starts at 1 (if it were 0, the result would always be 0).
1 <= 5 → true. factorial *= count: 1 × 1 = 1.
count++ → 2. Back to the condition.
2 <= 5 → true. factorial *= count: 1 × 2 = 2.
3 <= 5 → true. factorial *= count: 2 × 3 = 6.
4 <= 5 → true. factorial *= count: 6 × 4 = 24.
5 <= 5 → true. factorial *= count: 24 × 5 = 120.
count++ → 6. Back to the condition.
The condition is false: the loop exits.
The result is printed. int is enough up to 12!; 13! overflows, so long is needed.
int n = 5; int factorial = 1; int count = 1; while (count <= n) { factorial *= count; count++; } System.out.println(n + " factorial: " + factorial);
Loops
Computing Powers (for)
import java.util.Scanner; public class Power { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter base and exponent: "); int base = sc.nextInt(); int exp = sc.nextInt(); long result = 1; for (int i = 1; i <= exp; i++) { result = result * base; } System.out.println("Result: " + result); System.out.println("Math.pow: " + Math.pow(base, exp)); sc.close(); } }
Enter base and exponent: 3 4 Result: 81 Math.pow: 81.0
Java's built-in Math.pow(base, exp) method does the same job but returns a double (81.0). Our own loop shows how the algorithm works; real programs prefer the library methods.
Loops
The do-while Loop
int i = 0; do { // statements in the loop i++; } while (i < 5);
- Does the work first, then checks the condition.
- Repeats while the condition holds.
- The body runs at least once.
while (condition)must be followed by a semicolon.- Typical uses: asking again until the user gives a valid value; menus.
Loops
do-while: Input Validation
import java.util.Scanner; public class DoWhileInput { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num; do { System.out.print("Enter a number (1-10): "); num = input.nextInt(); } while (num < 1 || num > 10); System.out.println("Accepted number: " + num); } }
Inputs: 15, 0, 7
Enter a number (1-10): 15 Enter a number (1-10): 0 Enter a number (1-10): 7 Accepted number: 7
- The question must be asked at least once:
do-whileis made exactly for this. - 15 and 0 are out of range: the condition
num < 1 || num > 10is true → ask again. - 7 is valid: the condition is false → exit the loop.
numis declared before the loop because it is used in the condition and after the loop.
Loops · Step-by-step code trace
Input Validation: Tracing the Code
The user will type 12, −3, 4 in turn. num is declared before the loop; it is used in the condition and after the loop.
The question is asked without checking the condition. nextInt() reads the first input: num = 12.
12 < 1 || 12 > 10: the right side is true → the condition is true, so the question is asked again.
The second input is read: num = -3.
-3 < 1 is true; || skips the right side → the condition is true, again.
Third input: num = 4.
4 < 1 false, 4 > 10 false → the condition is false: the loop exits.
The valid number is accepted. The question was asked 3 times; the loop runs until a valid number arrives.
Scanner input = new Scanner(System.in); int num; do { System.out.print("Enter a number (1-10): "); num = input.nextInt(); } while (num < 1 || num > 10); System.out.println("Accepted number: " + num);
Loops · Step-by-step code trace
while vs. do-while
i = 10.
while tests its condition first: false. The body (lines 3–4) never runs.
j = 10.
The do block is entered with no check.
The body runs once.
j++ → 11.
The condition is then tested: false → exit.
Same condition, different result: while ran 0 times, do-while ran once.
int i = 10; while (i < 5) { System.out.println("while: " + i); i++; } int j = 10; do { System.out.println("do-while: " + j); j++; } while (j < 5); System.out.println("i = " + i + ", j = " + j);
Loops
Comparing the Loop Types
for | while | do-while | |
|---|---|---|---|
| Where is the condition tested? | Before every pass | Before every pass | After every pass |
| Minimum passes? | 0 | 0 | 1 |
| Init / update | In the header, on one line | Outside the loop / in the body | Outside the loop / in the body |
| When? | Known count: “from 1 to n”, “every element of an array” | Until a condition changes: “until the number is 0” | The work must happen at least once: input validation, menus |
| Syntax | for (init; cond; upd) { } | while (cond) { } | do { } while (cond); |
The three loops can be converted into one another; choose for readability.
Loops
The for Loop: Playground
The boxes show the value of i on each pass the body ran. Try: init 10, condition <=, end 1 (never runs); update i-- with <= (infinite loop); init 1, != and i += 2 with end 9 (stops) and 10 (never equal: infinite). The simulation stops after 200 passes.
Nested Loops
Nested Loops
- A nested loop is a loop inside the body of another loop.
- Used for more complex work: matrices and multidimensional arrays, tables, patterns.
- Analogy: a clock. Each time the hour hand (outer loop) moves one step, the minute hand (inner loop) goes all the way round.
- The total number of passes is a product: 3 outer × 2 inner = 6 runs of the body.
- The number of nested loops and their conditions affect complexity. Too much nesting leads to complex, slow code: three loops × 1000 passes = 1 billion operations!
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { // nested loop body } }
Nested Loops · Step-by-step code trace
How Nested Loops Work
Outer loop starts: i = 1, 1 <= 3 → true.
Inner loop starts: j = 1. Body: i = 1, j = 1 is printed.
Body: i = 1, j = 2 is printed.
j = 3 → 3 <= 2 false: the inner loop is done. Back to the outer loop: i++ → 2, 2 <= 3 → true; the inner loop starts over.
Inner loop starts: j = 1. Body: i = 2, j = 1 is printed.
Body: i = 2, j = 2 is printed.
j = 3 → 3 <= 2 false: the inner loop is done. Back to the outer loop: i++ → 3, 3 <= 3 → true; the inner loop starts over.
Inner loop starts: j = 1. Body: i = 3, j = 1 is printed.
Body: i = 3, j = 2 is printed.
j = 3 → 3 <= 2 false: the inner loop is done. i++ → 4, 4 <= 3 false: the outer loop ends too. The body ran 3 × 2 = 6 times.
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { System.out.println("i = " + i + ", j = " + j); } }
Nested Loops · Step-by-step code trace
Example: Star Pattern
The inner loop's bound depends on the outer loop's variable (j <= i): each row prints one more star.
Row 1: the inner loop runs j from 1 to i = 1. print("* "): stays on the same line.
Inner loop done (j = 2 > 1). println() moves to the next line.
Row 2: the inner loop runs j from 1 to i = 2. print("* "): stays on the same line.
print("* "): stays on the same line.
Inner loop done (j = 3 > 2). println() moves to the next line.
Row 3: the inner loop runs j from 1 to i = 3. print("* "): stays on the same line.
print("* "): stays on the same line.
print("* "): stays on the same line.
Inner loop done (j = 4 > 3). println() moves to the next line.
Row 4: the inner loop runs j from 1 to i = 4. print("* "): stays on the same line.
print("* "): stays on the same line.
print("* "): stays on the same line.
print("* "): stays on the same line.
Inner loop done (j = 5 > 4). println() moves to the next line. 1 + 2 + 3 + 4 = 10 stars in total.
for (int i = 1; i <= 4; i++) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); }
Nested Loops
Place Value: What Is Printed?
for (int tens = 0; tens <= 4; tens++) { for (int ones = 1; ones <= 9; ones++) { int num = tens * 10 + ones; System.out.println("Tens digit: " + tens + ", ones digit: " + ones + " --> " + num); } }
Question: how many lines does the program print? What are the first and last lines? Which numbers are never printed?
Answer
Tens digit: 0, ones digit: 1 --> 1 Tens digit: 0, ones digit: 2 --> 2 Tens digit: 0, ones digit: 3 --> 3 … Tens digit: 4, ones digit: 8 --> 48 Tens digit: 4, ones digit: 9 --> 49
The outer loop runs 5 times (tens = 0…4), the inner loop 9 times (ones = 1…9): 5 × 9 = 45 lines. num = 1…49; ones doesn't start at 0, so 10, 20, 30, 40 are never printed. A long string is split across two lines with +; a line break inside the quotes gives an unclosed string literal error.
Nested Loops
Multiplication Table
for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { int product = i * j; System.out.print(i + "x" + j + "=" + product + "\t"); } System.out.println(); // new line }
- The outer loop walks the rows (
i), the inner one the columns (j): 10 × 10 = 100 products. printstays on the line;"\t"(tab) aligns columns.println()then starts a new row: outside the inner loop, inside the outer one.
Excerpt of the output (tabs shown as spaces)
1x1=1 1x2=2 1x3=3 1x4=4 1x5=5 1x6=6 … 2x1=2 2x2=4 2x3=6 2x4=8 2x5=10 2x6=12 … 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15 3x6=18 … … 10x1=10 10x2=20 10x3=30 10x4=40 10x5=50 …
break and continue · Step-by-step code trace
break in Loops
break is used to end a loop: once its condition holds, execution leaves the loop.
i = 1: 1 == 5 false, break is skipped; the step is printed.
i = 2: 2 == 5 false → printed.
i = 3: 3 == 5 false → printed.
i = 4: 4 == 5 false → printed.
i = 5: condition true → break. The loop ends immediately; 5 is not printed and 6–10 are never tried.
Statements after the loop continue. i no longer exists.
for (int i = 1; i <= 10; i++) { if (i == 5) { break; } System.out.println("Loop step: " + i); } System.out.println("Left the loop.");
break and continue
Prime Check: A Flag and break
import java.util.Scanner; public class PrimeCheck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); boolean isPrime = true; // flag if (num < 2) isPrime = false; // 0 and 1 are not prime for (int divisor = 2; divisor <= num / 2; divisor++) { if (num % divisor == 0) { // divides evenly isPrime = false; break; // break out of the loop } } if (isPrime) { System.out.println(num + " is prime."); } else { System.out.println(num + " is not prime."); } sc.close(); } }
Enter a number: 21 21 is not prime. Enter a number: 97 97 is prime.
Faster: if a number has a divisor, one of them is at most √num. With the condition divisor * divisor <= num, only 8 divisors are tried for 97 instead of 47.
break and continue · Step-by-step code trace
continue in Loops
continue skips the rest of the current pass and moves on to the next pass.
i = 1 is odd → condition false, the number is printed.
i = 2 is even → continue: line 5 is skipped; control goes straight to i++.
i = 3 is odd → condition false, the number is printed.
i = 4 is even → continue: line 5 is skipped; control goes straight to i++.
i = 5 is odd → condition false, the number is printed.
i = 6 is even → continue: line 5 is skipped; control goes straight to i++.
i = 7 is odd → condition false, the number is printed.
i = 8 is even → continue: line 5 is skipped; control goes straight to i++.
i = 9 is odd → condition false, the number is printed.
i = 10 is even → continue: line 5 is skipped; control goes straight to i++.
11 <= 10 false: the loop ends normally. continue does not end the loop; it only skips that pass.
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } System.out.println("Odd number: " + i); }
break and continue
break vs. continue
The loop ends completely; execution moves to the statement after the loop.
The rest of the pass is skipped; the loop goes on with the update and the condition.
Both are usually used inside an if; they also work in while and do-while; in while, a continue that skips the update can cause an infinite loop.
break and continue
break in Nested Loops
break ends only the inner loop
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) { break; } System.out.println(i + " " + j); } }
1 1 2 1 3 1
Labeled break: leaving the outer loop
outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i * j == 4) { break outer; } System.out.println(i + " x " + j); } }
1 x 1 1 x 2 1 x 3 2 x 1
In the left example, for each i only j = 1 is printed and the outer loop goes on. On the right, the outer: label names the outer loop; when i * j == 4 (i = 2, j = 2) break outer; exits both loops at once. Use labels sparingly.
break and continue · Step-by-step code trace
Labeled break: Tracing the Code
The outer: label names the outer loop. i = 1, j = 1: 1 × 1 = 1 ≠ 4, printed.
j = 2: 1 × 2 = 2, printed.
j = 3: 1 × 3 = 3, printed. The inner loop ends; the outer loop moves to i = 2.
i = 2, j = 1: 2 × 1 = 2, printed.
i = 2, j = 2: 2 × 2 = 4 → the condition is true.
break outer; exits not just the inner loop but the labeled outer loop too. The remaining cells are never visited.
Flow jumps past both loops: done is printed. With an unlabeled break, the i = 3 pass would run too.
outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i * j == 4) { break outer; } System.out.println(i + " x " + j); } } System.out.println("done");
Summary
Summary
| Structure | What it does | Syntax |
|---|---|---|
| Sequential | Statements run top to bottom, once each | — |
| if / else | If the condition is true one block, otherwise the other | if (c) { } else { } |
| else if | The block of the first true condition runs | if (c1) { } else if (c2) { } else { } |
| switch | Compares a value with constant cases; exits with break | switch (x) { case 1: … break; default: … } |
| for | Init, condition and update on one line; counted repetition | for (int i = 0; i < n; i++) { } |
| while | While the condition is true; 0 or more passes | while (c) { } |
| do-while | Body first, then the condition; at least 1 pass | do { } while (c); |
| break / continue | Ends the loop / skips the pass | break; · continue; |
Summary
Common Mistakes: Decisions
if (x = 5) → error: incompatible types: int cannot be converted to boolean. Correct: x == 5.if (x > 5); { … } compiles, but the ; is an empty statement: the block always runs.if (c) a(); b(); else c(); → error: 'else' without 'if'. Braces { } are required for more than one statement.switch: with no break, the cases below run too (fall-through). The compiler doesn't warn you.cases: error: variable season might not have been initialized. Fix: add a default.nextDouble() given -7.5 → InputMismatchException. -7,5 is what you must type.Summary
Common Mistakes: Loops
while: forgetting the update (i++) or updating in the wrong direction (i-- with i <= 10). The compiler won't catch it; the program never stops.for (int i = 0; i < 3; i++); or while (i < 5); is a loop with an empty body; the block below doesn't belong to it.i < 10 skips 10; i = 0 with i <= 10 runs 11 times. Check the first and last pass separately.for (int i …) { } followed by println(i) → error: cannot find symbol. If needed, declare i before the loop.break; System.out.println(i); → error: unreachable statement. break: the line after it can never be reached.factorial = 0 makes the result always 0. Resetting the variable inside the loop is wrong too.Summary
Practice Problems (1): What Is Printed?
Problem 1
int x = 7; if (x > 5) if (x > 10) System.out.println("A"); else System.out.println("B");
Problem 2
int s = 0; for (int i = 1; i <= 10; i += 3) { s += i; } System.out.println(s);
Problem 3
int k = 2; int points = 0; switch (k) { case 1: points += 10; case 2: points += 20; case 3: points += 30; break; case 4: points += 40; } System.out.println(points);
Answers
- B.
elsegoes with the nearestif(the inner one): 7 > 5 is true, 7 > 10 is false → B. - 22.
i= 1, 4, 7, 10; sum 22. - 50.
case 2is entered (+20),breakis missing:case 3is reached by fall-through (+30). Total 50.
Summary
Practice Problems (2)
Write code that sums the numbers from 1 to 100 that are divisible by 3 or 5.
Find how many digits an integer (e.g. 2024) has, using a while loop (num /= 10 drops the last digit).
Answers
int sum = 0; for (int i = 1; i <= 100; i++) { if (i % 3 == 0 || i % 5 == 0) { sum += i; } } System.out.println(sum);
Output: 2418. Each number is tested once; || ensures common multiples such as 15 are not added twice.
int num = 2024, digits = 0; while (num > 0) { digits++; num /= 10; } System.out.println(digits);
Output: 4. Each pass drops the last digit: 2024 → 202 → 20 → 2 → 0.
Summary
Exercises (1)
int n = 1; while (n < 100) { n *= 3; } System.out.println(n);
int k = 5; do { k -= 2; } while (k > 0); System.out.println(k);
int count = 0; for (int i = 1; i <= 4; i++) { for (int j = i; j <= 4; j++) { count++; } } System.out.println(count);
Answers (solve on paper first, then run the code to check)
- 243.
n: 1 → 3 → 9 → 27 → 81 → 243; it stops when 243 < 100 is false. - -1.
k: 5 → 3 → 1 → −1. The condition is checked at the end, so it goes down to −1. - 10. The inner loop runs
i= 1, 2, 3, 4: 4 + 3 + 2 + 1 = 10.
Summary
Exercises (2)
int t = 0; for (int i = 1; i <= 10; i++) { if (i % 3 == 0) { continue; } t += i; } System.out.println(t);
int i = 10; while (i >= 1) { System.out.print(i + " "); i -= 2; } System.out.println();
int a = 17, b = 42; int max = (a > b) ? a : b; System.out.println(max);
Answers
- 37. The sum of 1–10 is 55; the skipped 3 + 6 + 9 = 18; 55 − 18 = 37.
- 10 8 6 4 2.
igoes down from 10 by 2; at 0, 0 >= 1 is false.forversion:for (int i = 10; i >= 1; i -= 2). - 42. 17 > 42 is false, so the second value is chosen. Also write the equivalent
if-else.
Summary
References
- Oracle, The Java Tutorials: “Control Flow Statements” (if-then-else, switch, while, do-while, for, branching statements).
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition (Chapter 14: Blocks, Statements, and Patterns).
- P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapters 4–5: Control Statements).
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly (Chapter 5: Conditionals and Logic, Chapter 6: Loops).
- K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly.
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed. (3.8: Control Flow).