The switch Statement to Multi-Way Branching
A switch block evaluates an expression and transfers control to a matching case label. Once a match is found, all subsequent statements execute untill a break appears or the block ends.
switch (expression) {
case literal_1:
// code block A
break;
case literal_2:
// code block B
break;
default:
// fallback block
break;
}
Execution Steps
- Compute the value of
expression. - Compare it with each
caseliteral from top to bottom. As soon as equality holds, execute that case’s body. - If no match exists, run the
defaultblock (when present). - A
breakstatement terminates theswitch; without it, execution falls through into the next case.
Example: Weekly Workout Suggestions
A user enters a day number (1–7) and receives a workout plan. This is implemented with a switch reading from Scanner.
import java.util.Scanner;
public class WorkoutPlanner {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter day number (1-7): ");
int day = input.nextInt();
switch (day) {
case 1:
System.out.println("Jogging");
break;
case 2:
System.out.println("Swimming");
break;
case 3:
System.out.println("Brisk walking");
break;
case 4:
System.out.println("Spinning class");
break;
case 5:
System.out.println("Boxing");
break;
case 6:
System.out.println("Hiking");
break;
case 7:
System.out.println("Cheat meal day");
break;
default:
System.out.println("Invalid day number");
break;
}
input.close();
}
}
Leveraging Fall-Through Behavior
Omitting break causes case penetration, where execution continues into subsequent cases. This is useful for grouping related values.
import java.util.Scanner;
public class WeekClassifier {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter week day (1-7): ");
int day = input.nextInt();
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Workday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid input");
break;
}
input.close();
}
}
Constructs for Repetition
Repetition statements execute a loop body as long as a condition remains true. The loop must eventually alter the condition to prevent infinite execution.
The for Loop
A for loop packs initialization, condition check, and state update into a single header.
for (initialization; termination_check; step_expression) {
// body
}
Execution order:
- Execute the initializer once.
- Evaluate the condition. If
false, exit the loop. - Run the body.
- Execute the step expression, then return to step 2.
Printing sequences 1–5 and 5–1
public class SequencePrinter {
public static void main(String[] args) {
for (int val = 1; val <= 5; val++) {
System.out.println(val);
}
System.out.println("---");
for (int val = 5; val >= 1; val--) {
System.out.println(val);
}
}
}
Accumulating a sum: 1 through 5
public class SumAccumulator {
public static void main(String[] args) {
int accumulator = 0;
for (int count = 1; count <= 5; count++) {
accumulator += count;
}
System.out.println("Sum of 1..5 = " + accumulator);
}
}
Summing even numbers from 1 to 100
public class EvenSum {
public static void main(String[] args) {
int total = 0;
for (int n = 1; n <= 100; n++) {
if (n % 2 == 0) {
total += n;
}
}
System.out.println("Sum of evens 1-100: " + total);
}
}
Finding Armstrong numbers (three-digit narcissistic numbers)
An Armstrong number satisfies: sum of cubes of each digit equals the original number (e.g., 153 = 1³ + 5³ + 3³).
public class ArmstrongNumbers {
public static void main(String[] args) {
for (int candidate = 100; candidate < 1000; candidate++) {
int units = candidate % 10;
int tens = candidate / 10 % 10;
int hundreds = candidate / 100;
int sumCubes = units * units * units
+ tens * tens * tens
+ hundreds * hundreds * hundreds;
if (sumCubes == candidate) {
System.out.println(candidate);
}
}
}
}
Displaying Armstrong numbers with two per line
public class FormattedArmstrong {
public static void main(String[] args) {
int printedCount = 0;
for (int trial = 100; trial <= 999; trial++) {
int d1 = trial % 10;
int d2 = trial / 10 % 10;
int d3 = trial / 100;
if (d1*d1*d1 + d2*d2*d2 + d3*d3*d3 == trial) {
System.out.print(trial + " ");
printedCount++;
if (printedCount % 2 == 0) {
System.out.println();
}
}
}
}
}
The while Loop
A while loop evaluates the condition before each iteration, making it suitable when the number of repetitions is unknown.
initialization;
while (condition) {
// body
update;
}
Simulating folding a paper to reach Mount Everest’s height
public class EverestFold {
public static void main(String[] args) {
double sheetThickness = 0.1; // millimeters
final long EVEREST_HEIGHT = 8_844_430; // millimeters
int folds = 0;
while (sheetThickness <= EVEREST_HEIGHT) {
sheetThickness *= 2;
folds++;
}
System.out.println("Folds required: " + folds);
}
}
The do-while Loop
A do-while guarantees the body runs at least once because the condition is tested afterwards.
initialization;
do {
// body
update;
} while (condition);
public class DoWhileDemo {
public static void main(String[] args) {
int counter = 1;
do {
System.out.println("Iteration " + counter);
counter++;
} while (counter <= 5);
}
}
Comparing Loop Variants
forandwhileare pre-test loops; the body may never execute.do-whileis a post-test loop; the body always executes once.- Loop-control variables declared in a
forheader are scoped to the loop;whilevariables remain accessilbe afterward.
Endless Loops
All three forms can loop forever:
for (;;) { /* infinite */ }
while (true) { /* infinite */ }
do { /* infinite */ } while (true);
Altering Loop Flow
break – Immediate Exit
break terminates the innermost enclosing loop (or switch) and resumes execution at the next statement.
public class BreakDemo {
public static void main(String[] args) {
for (int age = 20; age <= 80; age++) {
if (age == 60) {
break;
}
System.out.println("Working at age " + age);
}
}
}
continue – Skip Remaining Body
continue halts the current iteration and proceeds to the next condition check.
public class ContinueDemo {
public static void main(String[] args) {
for (int floor = 1; floor <= 24; floor++) {
if (floor == 4) {
continue;
}
System.out.println("Floor " + floor + " reached");
}
}
}
Labeled break and continue
Labels allow jumping out of deeply nested loops.
public class LabeledLoopExample {
public static void main(String[] args) {
outerLoop:
while (true) {
System.out.println("Enter day (0 to exit): ");
java.util.Scanner sc = new java.util.Scanner(System.in);
int day = sc.nextInt();
switch (day) {
case 0:
System.out.println("Goodbye");
break outerLoop;
default:
System.out.println("Workout plan for day " + day);
break;
}
}
}
}
Generating Random Values
The java.util.Random class produces pseudo‑random numbers.
import java.util.Random;
public class RandomBasics {
public static void main(String[] args) {
Random generator = new Random();
// yields a value between 0 (inclusive) and bound (exclusive)
int dice = generator.nextInt(10) + 1; // 1–10
System.out.println("Random 1-10: " + dice);
}
}
Guessing Game
A random target between 1 and 100 is generated; the user attempts to guess it with hints.
import java.util.Random;
import java.util.Scanner;
public class NumberGuesser {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int secret = rand.nextInt(100) + 1;
int guess;
do {
System.out.print("Your guess: ");
guess = input.nextInt();
if (guess > secret) {
System.out.println("Too high");
} else if (guess < secret) {
System.out.println("Too low");
} else {
System.out.println("Correct!");
}
} while (guess != secret);
input.close();
}
}