INSTACK 360

Java Loops: For, While, Do-While

Iterate effectively in Java. Learn the differences between for, while, and do-while loops.

Beginner 5 min read

Looping in Java

There may be a situation when you need to execute a block of code several times. Loop statements allow us to execute a statement or group of statements multiple times.

The While Loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

int x = 10;
while( x < 20 ) {
    System.out.print("value of x : " + x );
    x++;
}

The For Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

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

The Enhanced For Loop (For-Each)

Mainly used to traverse collections or arrays.

int[] numbers = {10, 20, 30, 40, 50};
for(int num : numbers) {
    System.out.println(num);
}

The Do-While Loop

Similar to a while loop, except that a do-while loop is guaranteed to execute at least one time.