1. java
  2. /basics
  3. /loops

The Basics of Java Loops

Getting Started

Loops might seem daunting at first. The reason we get accustomed to this construct, is to introduce control flow to our programs, by defining and specifying the order of the execution. With that, we can produce codebases that focus on both efficiency and effectiveness.

To simplify matters more, a loop allows us to repeat a set of instructions a specified number of times or until a certain condition is met. Syntax-wise, there are four elements we should know before we dive in further.

Initialization Expressions

Before diving into the loop's body, we need to set the initialization expression, which assigns our loop variables their starting values. This crucial step occurs just once, right at the beginning of the loop.

for (int i = 0; ...; ...) { // Initialization: int i = 0
  ...
}

Test Expressions

As we proceed, the test expression comes into play, evaluating the loop's condition at each iteration. The loop will keep chugging along as long as the condition holds true, requiring a boolean value (true or false) for its evaluation. In certain scenarios, we might even choose to leave out the test expression and let the loop run without a specific condition.

while (condition) { // Test expression
  ...
}

Update Expressions

Update expressions allow us to tweak the loop variables after each pass through the loop. Executed at the end of an iteration, these expressions enable us to increment or decrement loop variable values or perform other modifications as needed.

for (...; ...; i++) { // Update expression: i++
  ...
}

The Loop Body

We can think of the loop body as an encapsulation of statements that are executed repeatedly as long as the test expression is true. The code inside it will be carried out, depending on the value of the test expression. So, when the test expression evaluates to false, the loop will be terminated.

for (int i = 0; i < 10; i++) {
  // Loop body: statements to be executed while i < 10
  System.out.println(i);
}

Now that we have a basic grasp of the usage and syntax, let's glance over the different types of loops and showcase their intricacies.

The For Loop

With this loop type, we have a convenient way to iterate through a code block a set number of times. Usually, this means that we have a clear enough idea of the volume we want to specify.

Although the syntax is quite easy to grasp, things can get a little more complex when we deal with nested structures. We'll cover that aspect in a separate section below.

for (initialization; condition; increment/decrement) {
  // statements in the body to be executed
}

Let's turn to a common basic example and print out the numbers from 1 to 10.

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

We'll get the following output.

1
2
3
4
5
6
7
8
9
10

One of the advantages of for loops is their compactness, as all the loop control statements are contained within the header. However, a common pitfall is creating an infinite loop by accidentally omitting the update expression or using an incorrect condition. To avoid this, we need to ensure that the loop condition eventually evaluates to false.

Additionally, Java has another option called the for-each loop, which you may find referred to as the "enhanced for loop". It's designed for iterating through collections or arrays without the need for an index variable. We can follow this up with a brief example.

class Main {
  public static void main(String[] args) {
    int[] numbers = { 1, 2, 3, 4, 5 };

    for (int number : numbers) {
      System.out.println(number);
    }

  }
}

We can notice the number variable that represents the current element in the numbers array. Consequently, the loop will iterate through each element, and print its value. As an alternative, this approach gives us a more concise and readable way to traverse collections and arrays.

The While Loop

Another option at our disposal is the while loop. With it, we can execute a code block as long as a specific condition remains true.

while (condition) {
  // statements in the body to be executed
}

Let's consider a similar example and print out a range of integers.

class Main {
  public static void main(String[] args) {
    int i = 1;
    while (i < 7) {
      System.out.println(i);
      i++;
    }
  }
}

Observe the output and notice that we get numbers up to 7 as a result.

1
2
3
4
5
6

In the first two lines of the body, we initialize the variable and define the loop condition. The loop will keep executing as long as the specific condition i < 7 is true. In each iteration, we print the current value of i and increment it by 1. Once it reaches 7, the loop condition becomes false, and the loop stops executing.

The Do-while Loop

We can categorize this type as a variant of while loops. As an alternative, it guarantees at least one execution of the code block, even if the condition evaluates to false from the outset.

do {
  // statement to be executed
} while (condition);

Let's modify the same example with the do-while syntax.

class Main {
  public static void main(String[] args) {
    int i = 1;
    do {
      System.out.println(i);
      i++;
    } while (i < 7);
  }
}

We get the same output in both approaches. However, the main difference between them is that the first checks the condition up front, and the latter ensures at least one iteration before evaluating the condition.

The Break and Continue Statements

Java doesn't limit us to just the basic control statements. We can expand our loop toolkit with break and continue. Simply put, with break, we can exit a loop before it's done, while continue lets us skip over an iteration and move right along to the next one.

class Main {
  public static void main(String[] args) {
    for (int i = 1; i < 10; i++) {
      if (i == 5) {
        break;
      }
      System.out.println(i);
    }
  }
}

Output:

1
2
3
4

With the above example, we demonstrate the break statement in action. When the loop variable i equals 5, the loop is interrupted, and the remaining iterations are skipped.

Next, let's see how continue can help us filter out odd numbers.

class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 10; i++) {
      if (i % 2 != 0) {
        continue;
      }
      System.out.println(i);
    }
  }
}

Output:

2
4
6
8
10

We can notice that the continue statement skips over odd numbers by jumping to the next iteration when the condition i % 2 != 0 is true.

Nested Loop Structures

Sometimes we'll need to nest one loop within another to process multi-dimensional data sets or perform complex operations. These are known as nested loops. Let's illustrate this with an example and construct a multiplication table.

class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 10; i++) {
      for (int j = 1; j <= 10; j++) {
        System.out.print(i * j + "\t");
      }
      System.out.println();
    }
  }
}

Output:

1   2   3   4   5   6   7   8   9   10  
2   4   6   8   10  12  14  16  18  20  
3   6   9   12  15  18  21  24  27  30  
4   8   12  16  20  24  28  32  36  40  
5   10  15  20  25  30  35  40  45  50  
6   12  18  24  30  36  42  48  54  60  
7   14  21  28  35  42  49  56  63  70  
8   16  24  32  40  48  56  64  72  80  
9   18  27  36  45  54  63  72  81  90  
10  20  30  40  50  60  70  80  90  100

In our nested structure, the outer loop iterates through the numbers 1 to 10, while the inner one calculates the products of the current outer loop value and numbers 1 to 10. As a result, we get a neatly formatted multiplication table.

Final Thoughts

So far, we've explored various types of loops in Java, including the for loop, while loop, and do-while loop. We've learned how to harness loop control statements as well as nested loop structures that introduce the potential for more robust code. With this knowledge, you'll have the prerequisites to start tackling more intricate and practical programs.

Lastly, we recommend trying and modifying the examples in the Replit Java Compiler and Interpreter, and checking out some of our additional resources below.

Useful Resources

Overview of Operators in Java

Conditional Statements in Java

Java Data Types - A Beginner's Guide

The Basics of Java Syntax

An Introduction to Java Output