Understanding Loops in Java, With Examples

Pira25 / Shutterstock.com

Loops are a useful, fundamental part of Java and programming in general. Without them, the code for many tasks would be much more difficult to write, and the methods for doing them would become increasingly complex.

Types of Loops

There are three different types of loops in Java:for, while, and do-while.You could say there are four types if you want to include the enhanced for loop, or for-each loop as a standalone. Depending on your needs, each one can be used in different situations to better accomplish different goals.

For Loops

In Java, for loops have three parts: the initialization, condition, and iteration statements. Here s the general format:

for (initialization; condition; iteration) {
    // code to be executed
}

Now, what do these statements mean? The initialization statement defines the code to execute before the loop starts, the condition expression defines what must be true for the loop to continue, and the iteration statement defines what occurs after each iteration (one run-through ) of the loop.

If you had code that you wanted to be executed five times, you could write:

for (int i = 0; i < 5; i++) {
    // code to be executed
}

The initialization statement defines a new integer variable namedias 0. The variable nameiis commonly used to define a variable that controls the execution of the loop.

In the middle, the conditional expression says what must be true for the loop to continue. Here,imust be less than 5. By the time the inside code runs five times,iwill be 5, so this will be false, and the loop will terminate. Why willibe 5? Because of the iteration statement. This says to incrementiby 1, each iteration. Therefore, the inside code will run five times.

These three statements can be anything you want, and you can even skip them if you wish (although you still must have semicolons to show which is which. For example, if you wanted to make an infinite loop that never stops, you could write:

for (;;) {
    // code to be executed
}

Since there s no conditional expression to determine when the loop stops, the loop will simply run forever. There are also no initialization or iteration statements, but these are irrelevant here.

For loops are useful when you want the code to run for a known number of times, whether that s a hardcoded number or a value stored in a variable.

loops in java
A for-loop in action. Here, the for-loop iterates over an array of integers and prints each element to the console.

History-Computer.com

Enhanced For Loops

Oftentime, for loops are used to loop over arrays and other types of collections in Java. For example, if you had an array of integers namednumbers, you could sum it up with the following loop:

int sum = 0;
for (int i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

Instead of referencing elements by index, an enhanced for loop, also known as afor-each loop, allows you to reference elements directly. The previous block of code could be rewritten as:

int sum = 0;
for (int num : numbers) {
    sum += num;
}

As can be seen, you must specify the type of each element, as well as the name you want to reference the elements as. Each iteration will give the next element in the array or collection.

While Loops

Although for loops have three parts, while loops have only one: a conditional expression. A while loop continueswhilethat expression is true. The general form is:

while (condition) {
    // code to be executed}

Similar to the for loop, this can be used to make code run a certain number of times, like so:

int i = 0;
while (i < 5) {
    // code to be executed
    i++;
}

While loops are useful when you don t know how many times a loop will run. Often, the conditional expression is simply a boolean variable that can change in the body of the loop.

Do-While Loops

Do-while loops are the same as while loops, with one key difference: they will run at least once. Sometimes, you want a block of code to run once, regardless of whether the condition is initially true. This can be done with while loops, but it becomes much more complicated. A do-while loop looks like this:

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

As can be seen, the loop body goes after thedokeyword. Aside from it running at least once, the do-while loop functions like a while loop.

Special Keywords

There are 67 special keywords in Java, buttwoof them are vital in the context of loops.

Break

When put in the body of a loop,breakworks as a standalone statement. When the loop body reaches it, the loop will end. For example, since the loop ends at the end of the first iteration, Hello World will only be printed once.

for (int i = 0; i < 5; i++) {
    System.out.println("Hello World");
    break;
}

Continue

Similar tobreak,continueis another standalone statement. When it is reached, that iteration of the loop will end, and the next iteration begins. In this block of code, Hello World will never be printed, because the loop will always move to the next iteration before the print statement is reached.

for (int i = 0; i < 5; i++) {
    continue;
    System.out.println("Hello World");
}

Wrapping Up

You won t get far in Java without learning how to use loops. They are one of the fundamental building blocks of the language, and many programs will make use of different loops in various ways. We ve only scratched the surface of all you can do with loops in Java, so keep studying and putting your newfound knowledge into practice.

Leave a Comment