Loops syntax

In Java, loops are used to execute a block of code repeatedly as long as a specified condition is met. There are several types of loops in Java, each suited to different types of tasks: for, while, do-while, and enhanced for loops.

for Loop

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

for (initialization; condition; update) {
    // code to be executed
}
  • initialization: This step is executed first, and it’s used to declare and initialize loop control variables.
  • condition: Before each iteration, the condition is evaluated. If it’s true, the loop body is executed; if it’s false, the loop terminates.
  • update: This step is executed after each iteration and is generally used to update the loop control variable.

For example:

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

while Loop

The while loop is used when the number of iterations is not known and depends on a condition. The syntax is:

while (condition) {
    // code to be executed
}
  • condition: The loop continues to execute as long as this condition is true.

For example:

int i = 0;
while (i < 10) {
    System.out.println("i: " + 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. The syntax is:

do {
    // code to be executed
} while (condition);
  • condition: The loop continues to execute as long as this condition is true. The condition is evaluated after each iteration.

For example:

int i = 0;
do {
    System.out.println("i: " + i);
    i++;
} while (i < 10);

Enhanced for Loop (for-each Loop)

The enhanced for loop is used to iterate over arrays or collections. It’s simpler and more readable than a standard for loop when dealing with collections. The syntax is:

for (type variableName : arrayOrCollection) {
    // code to be executed
}

For example:

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

Nested Loops

Loops can be nested inside other loops. Each loop will run its full course for every iteration of the outer loop.

For example:

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

Loop Control Statements

break: Terminates the loop and transfers control to the statement immediately following the loop.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println("i: " + i);
}

continue: Skips the current iteration of the loop and proceeds with the next iteration.

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    System.out.println("i: " + i);
}