Looping Statements in Java - For, While, Do-While Loop in Java

Looping statements in Java allow a block of code to be executed repeatedly, saving you from writing the same code over and over. Java provides three main types of loops: for, while, and do...while.

for Loop

Best used when the number of iterations is known in advance, since initialization, condition, and update are all defined in a single line.

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

while Loop

An entry-controlled loop that checks its condition before each iteration, ideal when the number of repetitions depends on a changing condition rather than a fixed count.

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

do...while Loop

An exit-controlled loop that checks its condition after running the loop body, which guarantees the code executes at least once.

int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);

Comparing the Three Loops

  • for — best when the iteration count is known ahead of time
  • while — best when the number of iterations depends on a condition, checked before running
  • do...while — best when the loop body must run at least once, condition checked after running

The Enhanced for-each Loop

In addition to these three, Java offers an enhanced for loop specifically for iterating over arrays and collections without needing an index variable.

int[] nums = {1, 2, 3};
for (int n : nums) {
    System.out.println(n);
}

Controlling Loops

All loop types can be controlled using break (to exit early) and continue (to skip to the next iteration), giving fine-grained control over how the loop behaves.

Choosing the right loop type comes down to one question: do you know the exact iteration count, does it depend on a condition, or must the body run at least once?

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course