Java by Example: For and While Loops

In Java, for and while are the primary looping constructs. Here are some basic types of for and while loops.

public class Main {

public static void main(String[] args) {

The most basic type of for loop, with a single condition.

for (int i = 1; i <= 3; i++) {

System.out.println(i);

}

A classic initial/condition/increment for loop.

for (int j = 7; j <= 9; j++) {

System.out.println(j);

}

A while loop without a condition will loop repeatedly until you break out of the loop.

while (true) {

System.out.println("loop");

break;

}

You can also continue to the next iteration of the loop.

for (int n = 0; n <= 5; n++) {

if (n % 2 == 0) {

continue;

}

System.out.println(n);

}

}

}

Next example: If/Else.