Java Loop Control
Java - Loop Control
Section titled “Java - Loop Control”Loops are fundamental control structures in programming that allow you to execute a block of code repeatedly as long as a certain condition remains true, or for a specific number of iterations.
Java provides several looping mechanisms:
whileLoop: Executes a block of code as long as a condition is true (checked before each iteration).do...whileLoop: Similar towhile, but the condition is checked after the block executes, guaranteeing at least one execution.forLoop: Typically used when the number of iterations is known beforehand. Initializes a counter, checks a condition, and updates the counter in each iteration.- Enhanced
forLoop (or for-each loop): Provides a concise way to iterate over elements in an array or collection.
The while Loop
Section titled “The while Loop”The while loop repeatedly executes a target statement as long as a given boolean condition is true. The condition is checked before the loop body executes.
Syntax:
Section titled “Syntax:”while (boolean_expression) { // Statements to execute repeatedly // Usually includes logic to eventually make the expression false}Flow: The boolean_expression is evaluated. If true, the statements inside the loop body are executed. Then, the expression is evaluated again. This repeats until the expression becomes false. If the expression is initially false, the loop body never executes.
Example:
Section titled “Example:”public class WhileLoopExample { public static void main(String[] args) { int count = 0; // Initialization
while (count < 5) { // Condition check System.out.println("Current count: " + count); count++; // Update (crucial to avoid infinite loop!) } System.out.println("Loop finished."); }}Output:
Current count: 0Current count: 1Current count: 2Current count: 3Current count: 4Loop finished.The do...while Loop
Section titled “The do...while Loop”The do...while loop is similar to the while loop, but the condition is tested after the loop body executes. This guarantees that the loop body runs at least once, even if the condition is initially false.
Syntax:
Section titled “Syntax:”do { // Statements to execute // Update logic often goes here} while (boolean_expression);Flow: The statements inside the loop body are executed first. Then, the boolean_expression is evaluated. If true, the loop repeats. If false, the loop terminates.
Example:
Section titled “Example:”import java.util.Scanner;
public class DoWhileExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number;
do { System.out.print("Enter a positive number (or 0 to exit): "); number = scanner.nextInt(); if (number > 0) { System.out.println("You entered: " + number); } } while (number > 0); // Condition checked after execution
System.out.println("Exiting program."); scanner.close(); }}Sample Interaction:
Enter a positive number (or 0 to exit): 10You entered: 10Enter a positive number (or 0 to exit): 5You entered: 5Enter a positive number (or 0 to exit): 0Exiting program.The for Loop
Section titled “The for Loop”The for loop provides a concise way to iterate a specific number of times. It combines initialization, condition checking, and updating of a loop control variable into one line.
Syntax:
Section titled “Syntax:”for (initialization; boolean_expression; update) { // Statements to execute}Flow of Control:
- Initialization: Executed once at the very beginning. Usually declares and initializes a loop counter variable (e.g.,
int i = 0). - Condition Check: The
boolean_expressionis evaluated before each iteration (including the first). Iftrue, the loop body executes. Iffalse, the loop terminates. - Loop Body Execution: If the condition is
true, the statements inside the loop execute. - Update: Executed after the loop body finishes each iteration. Typically increments or decrements the loop counter (e.g.,
i++,i--). - The flow then returns to step 2 (Condition Check).
Example:
Section titled “Example:”public class ForLoopExample { public static void main(String[] args) { // Loop from 0 up to (but not including) 5 for (int i = 0; i < 5; i++) { System.out.println("Iteration number: " + i); } System.out.println("For loop finished."); }}Output:
Iteration number: 0Iteration number: 1Iteration number: 2Iteration number: 3Iteration number: 4For loop finished.Enhanced for Loop (for-each)
Section titled “Enhanced for Loop (for-each)”Introduced in Java 5, the enhanced for loop simplifies iteration over arrays and collections. It eliminates the need for index management.
Syntax:
Section titled “Syntax:”for (ElementType element : collectionOrArray) { // Statements using 'element'}ElementType: The data type of the elements in the collection or array.element: A variable name declared within the loop. In each iteration, it holds the current element from the sequence.collectionOrArray: The array or collection object (e.g.,ArrayList,HashSet) you want to iterate over.
Example:
Section titled “Example:”import java.util.ArrayList;import java.util.List;
public class EnhancedForExample { public static void main(String[] args) { // Example with an array int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Iterating over array:"); for (int number : numbers) { System.out.print(number + " "); } System.out.println("\n");
// Example with a List (Collection) List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); System.out.println("Iterating over List:"); for (String name : names) { System.out.print(name + " "); } System.out.println(); }}Output:
Iterating over array:10 20 30 40 50
Iterating over List:Alice Bob CharlieLoop Control Statements: break and continue
Section titled “Loop Control Statements: break and continue”Java provides statements to alter the normal flow of loop execution.
The break Keyword
Section titled “The break Keyword”The break keyword is used to terminate the innermost loop ( while, do-while, for) or switch statement immediately. Execution jumps to the statement following the terminated loop or switch.
Syntax:
Section titled “Syntax:”`break;`Example:
Section titled “Example:”public class BreakExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) { if (number == 30) { System.out.println("Found 30, breaking loop."); break; // Exit the loop immediately } System.out.println("Processing: " + number); } System.out.println("After the loop."); }}Output:
Processing: 10Processing: 20Found 30, breaking loop.After the loop.The continue Keyword
Section titled “The continue Keyword”The continue keyword skips the rest of the current iteration of the innermost loop (while, do-while, for) and proceeds directly to the next iteration.
- In a
forloop,continuejumps to the update statement. - In a
whileordo-whileloop,continuejumps to the condition check.
Syntax:
Section titled “Syntax:”`continue;`Example:
Section titled “Example:”public class ContinueExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { if (i == 3) { System.out.println("Skipping iteration 3."); continue; // Skip the rest of this iteration } System.out.println("Processing iteration: " + i); } System.out.println("Loop finished."); }}Output:
Processing iteration: 1Processing iteration: 2Skipping iteration 3.Processing iteration: 4Processing iteration: 5Loop finished.Choosing the Right Loop
Section titled “Choosing the Right Loop”- Use
forwhen you know (or can calculate) the number of iterations in advance. - Use enhanced
for(for-each) for simple iteration over all elements of an array or collection when you don’t need the index. - Use
whilewhen you need to loop based on a condition, and the number of iterations isn’t known beforehand. Also suitable when the loop might not need to execute at all. - Use
do-whilewhen you need the loop body to execute at least once before the condition is checked.
What is Next?
Section titled “What is Next?”Having covered decision making and looping, the next chapters will explore specific data types like Numbers, Characters, and Strings in more detail, along with associated operations and methods.