Java Loops

Introduction to Java Loops

Loops in Java are used to execute a block of code repeatedly as long as a specified condition is true. They provide a convenient way to iterate over collections, process arrays, and perform repetitive tasks in programs.

Types of Loops in Java

Java supports three types of loops:

  1. for Loop
  2. while Loop
  3. do-while Loop

1. for Loop

The for loop is used when the number of iterations is known beforehand.

Syntax:

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

Example:

public class ForLoopExample { 
public static void main(String[] args) {
 for (int i = 0; i < 5; i++) {
 System.out.println("Iteration: " + i); 
} 
} 
}

2. while Loop

The while loop is used when the number of iterations is not known beforehand and the loop iterates based on a condition.

Syntax:

while (condition) { // Code to be executed }

Example:

public class WhileLoopExample {
 public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("Iteration: " + i); i++; } } }

3. do-while Loop

The do-while loop is similar to the while loop, except that it always executes the code block at least once, even if the condition is false.

Syntax:

do { // Code to be executed } while (condition);

Example:

public class DoWhileLoopExample { 
public static void main(String[] args) { int i = 0; do {    System.out.println("Iteration: " + i); i++; } while (i < 5); } }

Loop Control Statements

Java provides loop control statements to modify the execution of loops.

  1. break Statement:
    • Terminates the loop and transfers control to the statement immediately following the loop.
    • Useful for exiting a loop prematurely based on certain conditions.
  2. continue Statement:
    • Skips the current iteration of the loop and proceeds to the next iteration.
    • Useful for skipping specific iterations based on certain conditions.

Nested Loops

Java allows you to nest loops within one another to create complex iterations.

Example:

public class NestedLoopExample {
 public static void main(String[] args) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.println("i: " + i + ", j: " + j); } } } }

Infinite Loops

An infinite loop is a loop that never terminates unless the program is forcefully terminated.

Example:

public class InfiniteLoopExample {
 public static void main(String[] args) {
 while (true) { 
System.out.println("This is an infinite loop!"); 
} } }

Java loops provide a powerful mechanism for repeating tasks and iterating over collections of data. Understanding the different types of loops, loop control statements, nested loops, and infinite loops is essential for writing efficient and effective Java programs.