Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

In Java, loops are used to execute a block of code repeatedly based on a condition. Java provides several types of loop constructs to handle various looping requirements. In programming, loops are control flow structures used to execute a block of code multiple times. Loops are essential for performing repetitive tasks automatically, which saves time and simplifies code.

for Loop

The for loop is commonly used when the number of iterations is known beforehand. It has the following syntax:

for (initialization; condition; increment/decrement) {
    // code to be executed
}

Example:

for (int i = 0; i < 5; i++) {
    System.out.println("This is iteration " + i);
}

while Loop

The while loop is used when the number of iterations is not known, and the loop should continue as long as a certain condition is true.

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

Example:

int i = 0;
while (i < 5) {
    System.out.println("This is iteration " + i);
    i++;
}

do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body is executed at least once, since it checks the condition after executing the loop body.

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

Example:

int i = 0;
do {
    System.out.println("This is iteration " + i);
    i++;
} while (i < 5);

Enhanced for Loop (For-each Loop)

Java provides an enhanced for loop, also known as a "for-each" loop, which makes it easier to iterate over arrays or collections.

for (type element : array/collection) {
    // code to be executed
}

Example:

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println("Number: " + num);
}

Nested Loops

Java allows loops to be nested within other loops, although it's essential to manage these carefully to avoid confusion and errors.

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.println("i: " + i + ", j: " + j);
    }
}

Controlling Loop Execution

  • break: The break statement is used to exit the loop prematurely when a certain condition is met.

  • continue: The continue statement skips the rest of the loop's body and continues with the next iteration.

Example with break and continue:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // will exit the loop
    }
    if (i % 2 == 0) {
        continue; // will skip the even numbers
    }
    System.out.println(i);
}

These are the basic types of loops available in Java, each with its own specific use case and advantages.

  • No labels