DEV Community

Cover image for Java By Example: Loop(for and while)
Alan
Alan

Posted on

Java By Example: Loop(for and while)

for and while are the two Java looping construct. Here are some basic types of for and while loops.

class Loop {
  public static void main(String[] args) {

    // The most basic type, with a single condition.
    Integer i = 1;
    while(i <= 3){
        System.out.println(i);
    i = i + 1;
    }

    // A classic initial/condition/after `for` loop.
    for(Integer j = 7; j <= 9; j++){
         System.out.println(j);
    }

    // `while(true)` will loop repeatedly
    // until you `break` out of the loop
    // or `return` from the enclosing function.
    while(true){
        System.out.println("loop");
    break;
    }

    // You can also `continue` to the next iteration of the loop.
    for(Integer n = 0; n <= 5; n++) {
        if(n%2 == 0){
            continue;
        }
        System.out.println(n);
    }

  }

}
Enter fullscreen mode Exit fullscreen mode
javac Loop.java
java Loop
# 1
# 2
# 3
# 7
# 8
# 9
# loop
# 1
# 3
# 5
Enter fullscreen mode Exit fullscreen mode

We’ll see some other for forms later when we look at:
foreach statements (Foreach),
async channels (Async), and other data structures.

Top comments (0)