Home

 › 

Articles

 › 

Understanding Loops in Java, with Examples

Collection Framework in Java

Understanding Loops in Java, with Examples

Understanding loops in Java is a vital part of becoming a better programmer. Imagine you have some kind of repetitive task like writing the numbers 1 through 10. Instead of writing each number one by one, you can use a loop to make the process faster and more efficient.

At a basic level, a loop is just a set of instructions that tells your computer to repeat a specific block of code.

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. So, without wasting any more time, let’s dive in.

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 named i as 0. The variable name i is 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, i must be less than 5. By the time the inside code runs five times, i will be 5, so this will be false, and the loop will terminate.

Why will i be 5? Because of the iteration statement. This says to increment i by 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

Oftentimes, for loops are used to loop over arrays and other types of collections in Java. For example, if you had an array of integers named numbers, 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 a for-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 continues while that 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 the do keyword. 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, but two of them are vital in the context of loops.

Break

When put in the body of a loop, break works 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 to break, continue is 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.

Frequently Asked Questions

What is a loop in Java?

A loop in Java is something you would use if you wanted to repeat a set of instructions if a given value is true. It is basically just instructions telling your computer to repeat a certain block of code.

What are the 3 different types of for loops?

You’ll encounter three different types of for-loops in Java: the simple for loop, for-each, and labeled for loop.

What are the 3 parts of a for loop Java?

Initialization, usually in the form of a keyword, the condition, such as whether a given value is true, and iteration, determining when the loop ends.

How can I loop over an array or a collection in Java?

You can iterate over an array or collection in Java using a while loop, for loop, or for-each loop.

What is an infinite loop in Java?

An infinite loop is a loop where the condition never becomes false. In other words, a terminating condition is never reached, and the condition always evaluates to true.

What does I ++ mean in Java?

I ++ is used when you want to increment a number, typically when iterating through a loop.

What is the best loop to use in Java?

The for loop is typically the most commonly used type of loop in Java. It is the fastest loop in most scenarios, so most programmers will default to it. Using the enhanced for loop or for-each loop might not be as fast, but it will improve readability. Still, you shouldn’t worry much about the type of loop you use if performance is your concern, since most compilers will optimize the code to the point that the differences are barely noticeable.

To top