☕ Java

Control Statements

Control statements determine the flow of execution in a Java program. Without them, code executes line by line from top to bottom. Control statements allow the program to make decisions, repeat actions, and jump to different parts of the code based on conditions. Java provides three categories: selection statements (if, if-else, switch), iteration statements (for, while, do-while), and jump statements (break, continue, return).

Categories of Control Statements

Java control statements fall into three categories. Selection statements choose which block of code to execute based on a condition. Iteration statements repeat a block of code multiple times. Jump statements transfer control to a different part of the program unconditionally.
Java
// ── 1. SELECTION STATEMENTS — choose a path: ────────────────────────
//
//  if            → execute a block if condition is true
//  if-else       → choose between two blocks
//  if-else if    → choose among multiple conditions
//  switch        → choose among multiple constant values

// ── 2. ITERATION STATEMENTS — repeat a block: ────────────────────────
//
//  for           → repeat a known number of times
//  while         → repeat while condition is true (check first)
//  do-while      → repeat while condition is true (execute first)
//  for-each      → iterate over arrays and collections

// ── 3. JUMP STATEMENTS — transfer control: ───────────────────────────
//
//  break         → exit a loop or switch immediately
//  continue      → skip current iteration, jump to next
//  return        → exit the current method, optionally return a value

// ── Without control statements — always the same path: ───────────────
int score = 85;
System.out.println("Calculating grade...");
System.out.println("Grade: A");          // always prints A regardless
System.out.println("Done.");

// ── With control statements — path depends on data: ──────────────────
int score2 = 85;
System.out.println("Calculating grade...");
if (score2 >= 90) {
    System.out.println("Grade: A");
} else if (score2 >= 80) {
    System.out.println("Grade: B");      // this executes for score=85
} else {
    System.out.println("Grade: C or below");
}
System.out.println("Done.");

Selection Statements Overview

Selection statements evaluate a boolean expression and execute different code blocks based on the result. Java provides if, if-else, if-else-if chains, and switch statements. Every selection statement evaluates to true or false — Java does not allow non-boolean types (such as integers) as conditions, unlike C or JavaScript.
Java
// ── Boolean expressions in conditions: ───────────────────────────────

// Comparison operators:
int age = 20;
boolean isAdult   = age >= 18;     // true
boolean isMinor   = age < 18;      // false
boolean isExact   = age == 20;     // true
boolean isNot20   = age != 20;     // false

// Logical operators — combine conditions:
boolean a = true, b = false;
boolean andResult = a && b;        // false — both must be true
boolean orResult  = a || b;        // true  — at least one must be true
boolean notResult = !a;            // false — negation

// ── Java requires a boolean — NOT an integer: ─────────────────────────
int x = 1;
// if (x) { }          // COMPILE ERROR — not a boolean
if (x == 1) { }        // CORRECT — explicit comparison

// ── Common boolean expressions used in conditions: ────────────────────
String name = "Alice";
int    score = 75;
Object obj   = null;

// Null check:
if (name != null) { }

// String comparison — use .equals(), never ==:
if (name.equals("Alice")) { }
if ("Alice".equals(name)) { }      // null-safe — preferred

// Range check:
if (score >= 60 && score <= 100) { }

// Null-safe check before method call:
if (obj != null && obj.toString().isEmpty()) { }

// instanceof check:
Object value = "Hello";
if (value instanceof String s) {   // Java 16+ pattern matching
    System.out.println(s.toUpperCase());
}

Iteration Statements Overview

Iteration statements (loops) repeat a block of code. Java provides four loop constructs. The for loop is used when the number of iterations is known in advance. The while loop is used when the condition is evaluated before each iteration. The do-while loop guarantees at least one execution. The enhanced for-each loop iterates over arrays and Iterable collections.
Java
// ── for loop — known iteration count: ────────────────────────────────
for (int i = 0; i < 5; i++) {
    System.out.print(i + " ");      // 0 1 2 3 4
}

// ── while loop — condition checked before each iteration: ─────────────
int count = 0;
while (count < 5) {
    System.out.print(count + " ");  // 0 1 2 3 4
    count++;
}

// ── do-while loop — executes at least once: ───────────────────────────
int n = 10;
do {
    System.out.println("Executed once even though n >= 5");
    n++;
} while (n < 5);                    // condition false — but ran once

// ── for-each loop — iterate over array or collection: ─────────────────
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
    System.out.print(num + " ");    // 10 20 30 40 50
}

List<String> names = List.of("Alice", "Bob", "Charlie");
for (String name : names) {
    System.out.println("Hello, " + name);
}

// ── Jump statements inside loops: ────────────────────────────────────
// break — exit loop immediately:
for (int i = 0; i < 10; i++) {
    if (i == 5) break;
    System.out.print(i + " ");      // 0 1 2 3 4

}

// continue — skip current iteration, continue to next:
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue;       // skip even numbers
    System.out.print(i + " ");      // 1 3 5 7 9
}