FOR LOOP IN Java

problem

You wish to use a repetition mechanism in your Java program and execute an action or set of actions more than once. One of the options is the vastly used for-loop. It helps us to use this mechanism when the number of iterations is known before hand. For example, we want to repeat an action 10 times or 100 times, etc. In this post we will see how to utilize it with examples.

SOLUTION

Let’s start by creating a simple for loop that iterates 10 times and prints the message stored in a String variable.

				
					package com.programmerabroad;

public class ForLoop {

    public static void main(String[] args) {

        String message = "Testing for loop";

        for(int i=0; i<10; i++) {
            System.out.println(message);
        }
    }
}

				
			
The code above will be executed 10 times and will print on the console the contents of the message variable followed by a new line each time. The for loop ends when the condition, in this case i < 10 becomes False. More specific, when i = 10 it will stop executing.
 
The output will look as follows:
 

OUTPUT

for-loop-output

NESTING loops

The for loops can also be nested, meaning that a for loop can appear inside a for loop resulting in more iterations. If for example insert the for loop above inside itself then it will be executed 100 times. That is because the inner one will be executed 10 times and the outer one 10 times each resulting in a multiplication of 10 x 10 = 100.

More depth about this analysis can be found in the asymptotic analysis of algorithms.

Nesting example of the two:

				
					package com.programmerabroad;

public class NestedForLoops {
    
    public static void main(String[] args) {

        for(int i=0; i<10; i++) {
            for (int k=0; k<10; k++) {
                System.out.print(k + "\t");
            }
            System.out.println();
        }
    }
}

				
			

OUTPUT

nested-for-loops

breaking loops

Let’s suppose a case that you wish to stop the loop sooner than it’s destined execution times. In the following example we will check when the counter reaches the value 5 and we will use the break keyword to “break” it. When the break is reached, the execution will jump right after the body of the for loop, in this case line 12.

				
					package com.programmerabroad;

public class BreakLoop {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
            if (i == 5) {
                break;
            }
        }
        System.out.println("For loop break");
    }
}

				
			

OUTPUT

break-for-loop

Using labels

On the for loops we can additionally add a label. A label can be used if for example we have a nested for loop and we wish to break the outer for loop. It can also be applied on the continue statement that appears below.

For example, below 2 labels are applied on the loops. The outer_loop on the outer for loop and the label inner_loop in the inner for loop. The if condition breaks the outer loop when the total iterations reaches 21.

				
					package com.programmerabroad;

public class LabelForLoop {

    public static void main(String[] args) {
        
        int iterations = 0;

        outer_loop:
        for (int i = 0; i < 10; i++) {
            inner_loop:
            for (int k = 0; k < 10; k++) {
                iterations = iterations + 1;
                if (iterations >= 21) {
                    break inner_loop;
                }
                System.out.print(iterations + "\t");
            }
            System.out.println();
        }
    }
}

				
			

OUTPUT

label-for-loop

continue in for loop

Another one keyword that can be used inside for loop (and other loops) is the continue statement. In the example below when the i is even number the continue is executed. This means that the program execution from line 11 it will jump at line 14 where the end of the for-loop body is and it will go up at line 9. If the condition i < 10 is True it will re-enter the for-loop body at line 10 and carry on line by line and so on.

				
					package com.programmerabroad;

public class ContinueForLoop {

    public static void main(String[] args) {

        int total = 0;

        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                continue;
            }
            total = total + 1;
        }
        System.out.println(total);
    }
}

				
			

Another one way of looking at the continue statement is that it will skip whatever follows it till the end of the for-loop body. In the case above it will skip the line 13 whenever the i is even. Since it’s iterating from 0 to 9 inclusive, the total will be added 5 times so the result will be simply 5. Without the continue statement it would have been 10.

OUTPUT

continue-for-loop

CONCLUSION

In this post we saw few examples of using the for-loop in Java. One of the most used repetition mechanisms in the language and in others. We also saw how for loops can be nested and additionally how the break and continue statements can be applied on the loop. If we’re done sooner with the action we can stop the for loop with the break keyword. If we wish to “skip” an iteration we can use the continue keyword.

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.