Loops in Java: A Comprehensive Guide to Mastering Tasks

Introduction: Loops in Java

Loops in Java are essential for handling repetitive tasks in programming. One option is to write the same or similar code multiple times to execute a block of code repetitively. However, this approach is far from perfect, as it creates a lot of duplicate code that is hard to read. A better option is to use loops.

What are Loops?

Loops are structures for controlling repetitive program flow. A typical loop has two parts. One part is a Boolean control condition. The other part is a code block that will be executed while the condition is true or until the condition is false. The Boolean condition is reevaluated with each run of the code block. Each type of loop has different exit criteria, as you will learn in this tutorial.

Types of Loops in Java

There are two main types of loops: while and for loops. What type it is depends on the loop’s syntax and logic. The while loops depend on a Boolean condition. This condition could be general and while it is true, the code block is repeatedly executed. The for loops also repeatedly execute a code block, but the loop condition typically depends on the increment or decrement of an integer variable. When this variable reaches a certain target value, the loop will break.

Tutorial Overview: Loops in Java

In this tutorial, you will use while and for loops to create repetitive tasks and learn about the benefits and drawbacks of each one.

Prerequisites

To follow this tutorial, you will need:

  • An environment in which you can execute Java programs to follow along with the examples. To set this up on your local machine, you will need the following:
  • Java (version 11 or above) installed on your machine, with the compiler provided by the Java Development Kit (JDK). For Ubuntu and Debian, follow the steps for Option 1 in our tutorial How To Install Java with Apt on Ubuntu 22.04. For other operating systems, including Mac and Windows, follow the download options for Java installation.
  • To compile and run the code examples, this tutorial uses Java Shell, also known as JShell, which is a Read-Evaluate-Print Loop (REPL) run from the command line. To get started with JShell, check out the Introduction to JShell guide.
  • Familiarity with Java and object-oriented programming, which you can find in our tutorial How To Write Your First Program in Java.
  • An understanding of Java data types, which is discussed in our tutorial Understanding Data Types in Java.

while Loops

While loops check a Boolean condition, like whether two variables are equal or objects are related. Any Boolean statement works, making while loops powerful and widely used. In this section, you’ll create your first Java loop using the while keyword. A variable x will start at 3, and as long as x is greater than 0, the loop will print and decrement x, ensuring the loop ends after a few executions. Without the decrement, the loop would be infinite. To follow along, open JShell using the jshell command and exit with /exit.

To test out this code, paste the following lines into jshell:


int x = 3;
while (x > 0) {
    System.out.println("x is " + x--);
}

On the first line, you define the x variable.

The loop begins on line 2 with the while keyword. The conditional statement (x > 0) controls the loop. It compares whether x is bigger than 0. After that comes the opening bracket {, which denotes the start of the block of code. This code block will be executed repeatedly while the condition is true (x > 0).

Inside the code block, the System.out.println(“x is ” + x–); statement on line 3 prints the current value of x using the println() method. (For more on the System.out.println statement, check out our tutorial How To Write Your First Program in Java.) Inside the argument for println(), x is postdecremented by 1 with the code x–. With each execution, x decreases by 1.

The block of code ends on the last line with the closing bracket }. This is also the end of the loop.

When you run this code in jshell, the following output will print:

Output


x ==> 3
x is 3
x is 2
x is 1

The first line confirms that x has received the value of 3. On the following lines, the value of x is printed three times, decreasing by 1 each time. There are only three iterations where x equals 3, 2, and 1. The loop breaks when x reaches 0 because the conditional statement x > 0 is no longer satisfied. At this point, the loop exits and nothing else is printed.

The previous example is a common way to create a loop. The intention of the loop is clear, and the exit condition is straightforward: x > 0. In theory, you could make the condition more complex by adding additional variables and comparisons (such as x > 0 and y < 0), but this is not considered a best practice from a clean-code point of view. Complex conditions make the code hard to follow and understand while bringing little, if any, value.

do-while Loops

The do-while loop is less popular than while loops, but is still widely used. A do-while loop resembles a while loop, but they differ in one key aspect: the code block is executed first and then the loop condition is evaluated.

As a reminder, while loops first evaluate the condition and may never run the code block if the condition is not met. In do-while loops, however, there is always at least one execution of the code block before the loop control condition is evaluated. If the condition is true, the loop will continue additional iterations until it is no longer true. Do-while loops are useful for cases like asking a question and terminating only upon receiving the correct answer.

In this section, you will create a do-while loop similar to the while loop in the previous section. The int variable will be called x and will have an initial value of 3. This time, however, the condition is reversed (x < 0) and the code block will execute before the condition is assessed.

Open jshell and add the do-while loop:


int x = 3;
do {
    System.out.println("x is " + x--);
} while (x < 0);

The code has some similarities with the while loop from the previous section. First, there is the assignment of the variable x, which is again 3.

On line 2, the loop starts with the keyword do and the opening bracket { for the code block. On line 3, the value of x is printed using the println() method. With the println() method, you also decrement the value of x using the postdecrement operator –.

The closing bracket } for the code block is on the last line, followed by the while keyword and the conditional statement (x < 0). This is the part that differs from the previous while loop. Here, the condition is reversed: x should be smaller than 0. In the previous example, the condition required x to be bigger than 0. This change demonstrates that the code block will run once even though the condition is never satisfied.

When you run this code in jshell, the following output will print:

Output

The first line confirms that the value of x is 3. The second line prints x is 3. This is the peculiarity of the do-while loop: even though the condition (x < 0) is not met, the code block is still executed at least once. This unconditional execution might not always be desired, which is why you need to be careful when using do-while loops. Because of this caveat, do-while loops are not used as often.

for Loops

An alternative loop structure is the for loop. It is also used to run a block of code repeatedly under a condition, but it has more options than a while loop. In the loop control condition, you can add

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: