Conditional and Loop Control Structures in Java

Control structures dictate the sequence of statement execution within a program, enabling the construction of small logical units that perform specific functions.

  • Sequential Structure: Statements execute line by line from top to bottom, without any conditional checks or jumps.
  • Selection Structure: Executes a specific code block based on a given condition.
    • Includes if…else and switch statements.
  • Iteration Structure: Repeats a code block as long as a loop condition holds true.
    • Includes for, while, and do-while loops.
    • Note: JDK 5.0 introduced the foreach loop, which simplifies iterating over collections and arrays (covered in the Collections topic).

Selection Structure

The switch statement evaluates an expression against multiple constant cases.

switch(expression) {
    case constant1:
        codeBlock1;
        // break;
    case constant2:
        codeBlock2;
        // break;
    // ...
    [default:
        defaultBlock;
        break;
   ]
}

Key Points for switch:

  • The switch expression's value must be one of: byte, short, char, int, enum (JDK 5.0), or String (JDK 7.0).
  • case labels must be constants, not variables, expressions with uncertain results, or ranges.
  • All case constant values within a single switch statement must be unique.
  • Fall-through Behavior: If a case block lacks a break statement, execution will "fall through" to the next case block(s) without re-evaluating the condition, until a break is encountreed or the switch block ends.
  • The break statement exits the switch block. Without it, execution proceeds sequentially to the end.
  • The default block is optional and can be placed anywhere within the switch statement. It executes when no case matches.

Comparing if-else and switch:

  • Any logic implemented with switch can be rewritten using if-else. The reverse is not always true.
  • Guideline: When both switch and if-else are applicable, prefer switch for slightly better performance.
  • Detailed Comparison:
    • if-else Advantages:
      • The if condition is a boolean expression, allowing checks for both equality and ranges, making it more versatile.
      • switch only tests for equality against constant values, making its use cases narrower.
    • switch Advantages:
      • When checking equality against fixed constants, switch is often preferred due to slightly higher efficiency and cleaner syntax. Range checks are only possible with if.
      • Fall-through can be used to execute multiple blocks for a single match, a feature not present in if-else.

Iteration Structure

Comparison of for, while, and do-while:

  • do-while executes its loop body at least once. for and while evaluate the loop condition first before deciding to execute the body.
  • Fundamentally, all three loop types are interchangeable for implementing iteration logic.
    • Use for when the number of iterations (or a clear range) is known beforehand.
    • Use while when the iteration count is not predetermined.
    • Consider do-while when the loop body must execute at least once.
  • Common infinite loop constructs: while(true) and for(;;).
    • These are useful when the termination condition is determined inside the loop body, using a break statement.

break vs. continue:

  • break: Terminates the innermost enclosing loop or switch statement.
  • continue: Skips the remaining code in the current iteration of the innermost loop and proceeds to the next iteration.
  • Both can be used with labels to specify which outer loop to break out of or continue. The label must be placed immediately before the loop statement.
// break ends the current statement block
{
    ...
    break;
    ... // This code is unreachable
}

// Using a labeled break to exit an outer block
outerBlock: {
    ...
    innerBlock: {
        ...
        if (condition) {
            break innerBlock; // Exits innerBlock
        }
        ...
    }
    // Execution continues here after breaking innerBlock
}

Example using a labeled continue to optimize prime number checking:

class PrimeNumberFinder {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        int primeCount = 0;

        candidateLoop: for (int candidate = 2; candidate <= 100000; candidate++) {
            for (int divisor = 2; divisor <= Math.sqrt(candidate); divisor++) {
                if (candidate % divisor == 0) {
                    continue candidateLoop; // Not a prime, skip to next candidate
                }
            }
            System.out.println(candidate); // It's a prime number
            primeCount++;
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Total prime numbers: " + primeCount);
        System.out.println("Execution time (ms): " + (endTime - startTime));
    }
}

Unlike the unstructured goto found in some languages, Java's break and continue provide controlled flow changes within loops and switches.

Reading Input with Scanner

The java.util.Scanner class is used to read different types of data (int, double, String, etc.) from the standard input (keyboard).

  1. Import the class: import java.util.Scanner;
  2. Create a Scanner object: Scanner inputReader = new Scanner(System.in);
  3. Call the appropriate nextXxx() method to read data of the expected type.
  4. Close the resource: inputReader.close();

Ensure the input value matches the expected type; otherwise, an InputMismatchException will occur.

import java.util.Scanner;

public class UserInputDemo {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.println("Welcome to the Social Network!");
        System.out.print("Enter your username: ");
        String username = reader.next();

        System.out.print("Enter your age: ");
        int userAge = reader.nextInt();

        System.out.print("Enter your weight (kg): ");
        double userWeight = reader.nextDouble();

        System.out.print("Are you single (true/false)? ");
        boolean isSingle = reader.nextBoolean();

        System.out.print("Enter your gender (M/F): ");
        char userGender = reader.next().charAt(0); // Get first character

        System.out.println("\nProfile Summary:");
        System.out.println("Username: " + username);
        System.out.println("Age: " + userAge);
        System.out.println("Weight: " + userWeight);
        System.out.println("Single: " + isSingle);
        System.out.println("Gender: " + userGender);

        reader.close();
    }
}

Generating Random Integers in a Range:

  • Math.random() returns a double value in the range [0.0, 1.0).
  • To obtain a random integer in the inclusive range [a, b], use: (int)(Math.random() * (b - a + 1)) + a.

Tags: java Control Flow Conditional Statements loops Switch Statement

Posted on Sat, 23 May 2026 21:00:07 +0000 by darklight