Categories
News

How to Write a for Loop in Java | MakeUseOf

Learn how to use for loops, one of the most useful skills to master in beginner programming.

Loops are very powerful programming tools that will complete a set of instructions until a condition is met. They are very handy and should be one of the first programming concepts that you learn. There are many different types of loops, but for loops are arguably one of the most useful loops.

The For Loop in Java

For loops will continue to execute a block of code until a condition is met. It is important to note that a for loop will check the condition at the beginning of the loop, not the end. This means that if the condition is met, the loop will not start.

For loop syntax is similar across programming languages. So, if you have created a for loop in another programming language, a Java for loop will look familiar. However, if you are not familiar at all with Java, it is recommended that you read a beginner's tutorial before learning advanced topics like for loops.

for([statement1]; [condition]; [statement2]){
//code to execute each loop
}

The keyword for indicates a for loop. The condition that determines how long the loop will continue is located between the brackets. The first statement is run once when the for loop is initiated. The condition defines when the loop should stop. The second statement is executed at the end of every loop. Semicolons mark the end of statement1 and the condition. Typically, the statements are used to create a counter and the condition stops the loop once the counter reaches a specific number. Finally, the code that is executed in each loop is placed between the curly brackets.

public class Main{
public static void main(String[] args) {
for(int i = 1; i < 4; i++){
System.out.print(i);
}
}
}
//Output: 123

In the example above, the for loop prints out the value of i. The keyword for initializes the loop. The variable i is initially set to 1. The condition checks whether i is four or greater. This isn't the case, so our loop is executed. The loop code prints out the value of i, which is still 1 at this point. Once the loop code is completed, i is incremented by one and the loop begins again. At the end of the third loop, i is increased to four. When the next loop begins, our condition is met, so the loop stops.

Related: Core Java Concepts You Should Learn When Getting Started

Nested For Loop

Once you get the hang of a for loop, you should try to create a nested for loop. This is when you have a for loop inside of another for loop. This is an advanced technique because it can be difficult to understand how the two loops will interact. A good way to visualize how nested for loops work is to create the following pattern with a nested for loop.

*
**
***

To create this, we will need one loop to control how many stars are printed on each line, and another loop to control how many lines to create. When you are new to nested for loops it can be difficult to determine which loop is the inner loop. In this case, the loop that prints the stars is the inner loop. We need that loop to run each time a new line is created.

When creating a nested loop, be careful when you choose the name of your counter variables. Although often programmers use a generic i counter, using generic counters becomes confusing when multiple loops interact.

for(int lineCounter = 1; lineCounter < 4; lineCounter++){
for(int starCounter = 1; starCounter <= lineCounter; starCounter++){
System.out.print("*");
}
System.out.print("\n");
}

Let's run through this example to better understand how it works. Our first loop is counting how many lines we make. After the loop executes three times, it will stop. The next loop is a tad more complex. This loop controls how many stars are printed on each line. In our pattern, we want the same number of stars as the line number. The first line has one star, the second two, and the third three. So, we want that loop to print as many stars as our current line counter. After our star loop is completed, the line loop creates a new line by printing \n, which is the command for a new line.

Infinite Loops

One of the dangers of coding any type of loop is that you can accidentally create an infinite loop. These are loops that never stop. Although there are cases when an infinite loop is needed, generally, they are created by accident when the loop's condition is not carefully planned. In these cases, the program will continue to run until you force it to close.

To create an infinite loop, you can use the following syntax:

for(;;){
//code that never stops looping
}

Related: Websites & Apps That Can Help When Learning Java Programming

Using a For Loop with an Array

A common way to use a for loop is to iterate through an array. For example, if you want to print all of the strings in an array, you cannot simply say

System.out.print([array]);

This command would print information about the array, not the contents of the array. To print the contents of the array, you have to print each individual element in the array. This would be time-consuming to code, but you could create a for loop to go through each element.

String[] words = {"Hello", " ", "World", "!"};

for(int i = 0; i < words.length; i ++){
System.out.print(words[i]);
}

Remember, array positions start at zero, not one, so we want our loop to start at zero. Our first loop will print Hello, the second loop will print a space, and so on. After the fourth loop, our counter will be incremented to four, which is not less than the length of the array, which is also four. This will stop the loop.

Output:

Hello World!

For-Each Loop

Although you can use a for loop to iterate over an array, it is easier to use a for-each loop. These loops are designed specifically for arrays. A for each loop will go through each element in an array and execute code. For-each loops have a slightly different syntax. The keyword for is still used, but a condition is not specified.

for([dataType] [arrayElement] : [array]){
//code to be executed
}

Our previous example can be re-written as a for-each loop using this syntax:

String[] words = {"Hello", " ", "World", "!"};

for(String word : words){
System.out.print(word);
}

The loop is started with the keyword for. We then specify that the data in our array are strings. Next, we choose a variable name to refer to the elements in the array as we iterate through the loop. In this case, we used word. This is followed by a colon and the name of the array we want to iterate through. Now, inside our loop, we just have to use the variable word to refer to each element in the array.

When to Use a For Loop

For Loops are great tools that can save you a lot of coding. They are the best type of loop to use when you know exactly how many times you want your loop to run. You can even increase the complexity of for loops by nesting them. Nested for loops are particularly handy when working with multi-dimensional arrays. For loops are easy to learn and an important skill for beginners. This technique is sure to save you from coding unnecessary repetitive code.