Control Flow in Java: Exploring Loops and Jump Statements

In Java programming, loops are fundamental constructs that allow developers to execute a block of code repeatedly based on a certain condition or for a specific number of iterations. Understanding the different types of loops and how to control their flow is crucial for efficient and robust program design. This article delves into the primary loop statements in Java: while, do-while, for, and the enhanced for loop, along with the break and continue jump statements.

The while Loop

The while loop is Java's most basic iteration construct, designed for scenarios where the number of repetitions is not known beforehand. It continues to execute a block of code as long as a specified boolean expression evaluates to true. The condition is checked before each iteration.


while (boolean_expression) {
   // Code to be executed repeatedly
}
   

Example: while Loop

This example demonstrates a while loop counting up to a specific value.


public class WhileLoopDemo {
   public static void main(String[] args) {
       int count = 0; // Initialize a counter
       System.out.println("Starting while loop:");
       while (count < 5) { // Loop as long as count is less than 5
           System.out.println("Current count: " + count);
           count++; // Increment the counter
       }
       System.out.println("While loop finished. Final count: " + count);
   }
}
   

The output of the above program:


Starting while loop:
Current count: 0
Current count: 1
Current count: 2
Current count: 3
Current count: 4
While loop finished. Final count: 5
   

The do-while Loop

Similar to the while loop, the do-while loop also executes a block of code repeatedly based on a boolean condition. However, its distinguishing feature is that the loop body is guaranteed to execute atleast once, because the condition is evaluated after the loop's statements have run for the first time.


do {
   // Code to be executed at least once
} while (boolean_expression);
   

It's important to remember the semicolon after the while condition in a do-while loop.

Example: do-while Loop

This example illustrates the do-while loop, showing its execution even when the condition might initially be false.


public class DoWhileLoopDemo {
   public static void main(String[] args) {
       int value = 3;
       System.out.println("Starting do-while loop demo.");
       do {
           System.out.println("Processing value: " + value);
           value--; // Decrement the value
       } while (value > 0); // Loop continues as long as value is greater than 0
       System.out.println("Do-while loop finished. Final value: " + value);
   }
}
   

The output of the above program:


Starting do-while loop demo.
Processing value: 3
Processing value: 2
Processing value: 1
Do-while loop finished. Final value: 0
   

The for Loop

The for loop is a concise iteration construct, typically used when the number of iterations is known or can be easily determined. It combines initialization, condition checking, and iteration updates into a single line.


for (initialization; condition; update) {
   // Code to be executed
}
   

Here's how the for loop operates:

  1. Initialization: Executed once at the beginning of the loop. This typically declares and initializes a loop control variable.
  2. Condition: Evaluated before each iteration. If true, the loop body executes; otherwise, the loop terminates.
  3. Update: Executed after each iteration. This typically modifies the loop control variable (e.g., increments or decrements it).

Example: for Loop

This example uses a for loop to calculate the sum of numbers within a range.


public class ForLoopDemo {
   public static void main(String[] args) {
       int totalSum = 0;
       System.out.println("Calculating sum of numbers from 1 to 5:");
       for (int i = 1; i <= 5; i++) { // i starts at 1, continues up to 5, increments by 1
           System.out.println("Adding " + i + " to sum.");
           totalSum += i;
       }
       System.out.println("Total sum: " + totalSum);
   }
}
   

The output of the above program:


Calculating sum of numbers from 1 to 5:
Adding 1 to sum.
Adding 2 to sum.
Adding 3 to sum.
Adding 4 to sum.
Adding 5 to sum.
Total sum: 15
   

The Enhanced for Loop (For-Each Loop)

Introduced in Java 5, the enhanced for loop (often called the "for-each" loop) simplifies iteration over arrays and collections. It eliminates the need for explicit index management, making code cleaner and less error-prone.


for (DataType item : collectionOrArray) {
   // Code to be executed for each item
}
   
  • DataType: The type of the elements in the array or collection.
  • item: A new local variable that holds the current element during each iteration.
  • collectionOrArray: The array or collection to iterate over.

Example: Enhanced for Loop

This example demonstrates iterating over an array of strings and a list of integers using the enhanced for loop.


import java.util.ArrayList;
import java.util.List;

public class ForEachLoopDemo {
   public static void main(String[] args) {
       String[] colors = {"Red", "Green", "Blue"};
       System.out.println("Available Colors:");
       for (String color : colors) {
           System.out.println("- " + color);
       }

       List<Integer> scores = new ArrayList<>();
       scores.add(90);
       scores.add(85);
       scores.add(92);
       System.out.println("\nRecorded Scores:");
       for (Integer score : scores) {
           System.out.println("  Score: " + score);
       }
   }
}
   

The output of the above program:


Available Colors:
- Red
- Green
- Blue

Recorded Scores:
 Score: 90
 Score: 85
 Score: 92
   

The break Statement

The break statement is a jump statement used to terminate a loop (for, while, do-while) or a switch statement immediately. When break is encountered, the control flow exits the innermost enclosing loop or switch, and execution continues with the statement immediately following the terminated construct.


break;
   

Example: break Statement

This example shows how break can be used to exit a loop early once a specific condition is met.


public class BreakStatementDemo {
   public static void main(String[] args) {
       System.out.println("Searching for the first even number between 1 and 10:");
       for (int num = 1; num <= 10; num++) {
           if (num % 2 == 0) { // Check if the number is even
               System.out.println("Found an even number: " + num + ". Exiting loop.");
               break; // Exit the loop immediately
           }
           System.out.println("Current number (odd): " + num);
       }
       System.out.println("Loop termination complete.");
   }
}
   

The output of the above program:


Searching for the first even number between 1 and 10:
Current number (odd): 1
Found an even number: 2. Exiting loop.
Loop termination complete.
   

The continue Statement

The continue statement is another jump statement that is used within loops (for, while, do-while) to skip the remainder of the current iteration and proceed directly to the next iteration. It does not terminate the loop entirely.


continue;
   

Its behavior varies slightly depending on the loop type:

  • In a for loop, continue causes the flow to jump to the update expression, and then the condition is re-evaluated.
  • In while and do-while loops, continue causes the flow to jump directly to the boolean expression for re-evaluation.

Example: continue Statement

This example demonstrates using continue to skip processing specific elements in a loop.


public class ContinueStatementDemo {
   public static void main(String[] args) {
       System.out.println("Displaying numbers except multiples of 3 (from 1 to 10):");
       for (int val = 1; val <= 10; val++) {
           if (val % 3 == 0) { // If val is a multiple of 3
               System.out.println("Skipping multiple of 3: " + val);
               continue; // Skip the rest of this iteration and move to the next 'val'
           }
           System.out.println("Processing number: " + val);
       }
       System.out.println("Iteration concluded.");
   }
}
   

The output of the above program:


Displaying numbers except multiples of 3 (from 1 to 10):
Processing number: 1
Processing number: 2
Skipping multiple of 3: 3
Processing number: 4
Processing number: 5
Skipping multiple of 3: 6
Processing number: 7
Processing number: 8
Skipping multiple of 3: 9
Processing number: 10
Iteration concluded.
   

Tags: java loops while-loop do-while-loop For-Loop

Posted on Sat, 19 Sep 2026 16:30:04 +0000 by mahlia