You might have heard of loops in Java, but what are they exactly? And how do they work?

Java loops help us perform tasks repeatedly.

The tasks in this case are statements of code.

The statements are executed sequentially.

The first statement is executed first, followed by the second statement etc.
However, for the statements to be executed, a certain specified condition MUST be true.

Immediately after the condition becomes false, execution of the statements will halt.

There are two types of loops in Java:

  • for loop
  • while loop

Let us discuss them one-by-one.

The for loop in Java

The Java for loop helps us iterate a set of statements for a specified number of times.

Use this loop when you need to execute a section of code for a fixed number of times. It takes the following syntax:

for(initialization; condition ; Increment/decrement)
{
    statement(s);
}

The initialization defines the initial value of loop condition.

The loop_condition specifies the condition that must always be true for loop to run.

The loop_increment/decrement defines the amount by which the initialization value will be incremented or decremented after each iteration.

For example:

public class ForExample {
  public static void main(String[] args) {
    for(int x=1; x<=5; x++){
      System.out.println(x);
    }
  }
}

The code will return the following:

Java for loop

Inside the for statement, we created the variable x and initialized its value to 1.

The loop condition is x<=5, that is, the value of x must be less than or equal to 5.

The x++ is the increment.
It states that the value of variable x should be incremented by 1 after every iteration.

The loop iterated for values of x between 1 and 5, with 5 included.

When the loop found itself violating the loop condition, that is, x<5, it had to halt execution immediately.

Java allows us to create a for loop inside another for loop. This results into a nested for loop.
The inner loop will be executed completely for a single execution of the outer loop. For example:

public class ForExample {
  public static void main(String[] args) {
    for(int x=1; x<=4; x++){
      for(int y=1; y<=4; y++){
        System.out.println(x+" "+y);
      }//end of x
    }//end of y
  }
}

The code returns the following:

Java for loop result

The while loop in Java

The Java while loop iterates over a section of code provided the specified condition is true.

Use this type of loop when the code is not to be executed for a fixed number of times, but rather until a certain condition is met.

The condition is evaluated first and if true, the loop statement(s) are executed.

If the condition becomes false, execution jumps to the statements that come after the loop.

The loop will halt execution when the condition becomes false.
The java while loop takes the following syntax:

while(boolean_expression) {
  // Statement(s)
}

An example of the Java while loop would be:

public class WhileLoopExample {

  public static void main(String args[]) {
    int age = 15;

    while( age < 18 ) {
      System.out.print("Your age is: " + age );
      age++;
      System.out.print("\n");
    }
  }
}

This code will return the following:

Java while loop iteration

We created the variable age and assigned it a value of 15.

The test condition checks whether this value is less than 18, which is true.

This means the loop will run.
When it reached 17, it checked and found the next value of age is 18.

The execution of the loop had to halt immediately since continuing to execute it will violate the loop condition.

Suppose the code was as follows:

public class WhileLoopExample {

  public static void main(String args[]) {
    int age = 20;

    while( age < 18 ) {
      System.out.print("Your age is: " + age );
      age++;
      System.out.print("\n");
    }
  }
}

The above code will return nothing when executed.

The value of variable age was initialized to 20.

In the test condition, we are checking whether this value is less than 18, which is false.

The loop body cannot be executed, but it halts at that point.

This means that there are conditions under which the while may never run.

However, Java allows us to combine the while loop with the do keyword to ensure that the loop runs for at least once.

This results into the do…while loop.

In the do…while loop, the test condition comes at the end of the loop body rather than at the beginning.

This is demonstrated in the following syntax:

do {
  statements;
} while(condition);

The above syntax shows that the loop body is executed once before the loop condition is evaluated.

The following example best demonstrates this:

public class DoWhileExample {

  public static void main(String args[]) {
    int age = 20;

    do {
      System.out.print("Your age is: " + age );
      age++;
      System.out.print("\n");
    } while( age < 18 );
  }
}

The code returns the following when executed:

Java do while loop

The value of variable age is 20.

In the test condition, we are checking whether this value is less than 18, which is false.

Despite this, the loop body was executed once.

This is because the Java compiler executed the loop body first before the test condition.

Since the test condition evaluated to a false, execution of the loop halted immediately.

Good luck!