How to break out of nested loops in Java

Break out of nested loop in java

In this post, we will see how to break out of nested loops in Java.

Using break (will break inner loop)

It is very important to understand how nested loops work to ensure that applying break will output the desired result.

If you are a novice with nested loops, I am going to make the concept as easy as possible for you to understand.

When you apply break in the inner loop, it results in breaking the loop when a specific condition is met, but the outer loop continues to execute.

The following nested loop outputs the result of multiplying the two loops until the outer loop reaches position 3.

The loop will skip position 3 and continue executing for the remaining positions.

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16

Using named loop

In the first example we discussed, the nested loop continued to execute the outer loop after breaking position 3.

To prevent the outer loop from continuing to execute, we can use a named loop which is simply a loop with a label.

When the condition is met, instead of just breaking the nested loop, we want to add the named loop to the break statement to ensure that it breaks the outer loop.

For this approach, the nested loop will print out the product of the two loops until the outer loop reaches position 3.

The break statement will break the outer loop preventing it from iterating further.

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8

Using named block

Block is a sequence of statements containing local classes and variables within braces and can be used to break out of nested loops.

The block executes the statements one by one until the last line of code. If the code executes successfully, the block terminates successfully, and the same case applies if the code terminates abnormally.

To break out of a nested loop using this approach, we will print out the product of the nested loop until a condition is fulfilled.

Once the condition is fulfilled, we will break the execution of the block, which will, in effect, break the execution of the nested loop.

The block will break the nested loop when the product is equal to 4, and you can also add some statements to be executed if the condition was not valid before the closing braces of the block.

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

Using return

The return keyword works the same way as the break keyword by terminating the nested loop after a condition is met but returns a value for the loop to break.

To break from nested loops using the return approach, create a method and initialize a value that will be returned by the method once a condition is met.

The following example initializes the variable named multiply with 1 and tracks the multiplication of the nested loops until the result of the multiplication is 8.

When the product is 8, the method will return the value, and the nested loop will break immediately.

The for loop will also be printing out the product of the nested loops until the condition is met.

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
8

Conclusion

In this tutorial, you have learned four ways that you can use to break out of nested loops in java. The methods you covered include using break, return, named loop, and named block.


import_contacts

You may also like:

Related Posts

  • Multiple classes in one file in Java
    18 October

    Multiple classes in one file in Java

    Table of ContentsIntroductionMethods to Implement Multiple Classes In One Java Program1) Nested classes2) Multiple non-static nested classes In this post, we will see how to have multiple classes in one file in java. Introduction You need to have any number of classes in a single Java file, but there is a restriction that you can […]

  • public static void main(String args[]) - Java main method
    11 June

    public static void main(String[] args) – Java main method

    Table of ContentsWhy is the main method so important?SyntaxExplanation of the KeywordsExamples of Java main method ProgramsSimple Java ProgramPassing arguments in the main methodNon-Public main method.Defining a return value for the main methodOverloading the main methodQuestionsCan we run java without main method?Can we have more than one main method in classConclusion If you have worked […]

  • Java projects for beginners
    30 April

    Top 20 Java Projects for Beginners

    This tutorial provides the top 20 java projects for beginners for practice. These projects will help you to learn java quickly and efficiently.

  • How to end program in java
    08 March

    How to end program in java

    Table of ContentsUsing System.exit() to end java programExample to demonstrate System.exit() methodHow to end java program in an if statement in javaUsing return to end current method Ho In this post, we will see how to end program in java. You can use System.exit(0) to end program in java. Using System.exit() to end java program […]

  • 25 September

    Reference Variable in Java

    Table of ContentsReference variableStatic Reference VariableInstance Reference VariableLocal Reference Variable In this post, we will see about Reference variable in java. Reference variable A variable that holds reference of an object is called a reference variable. Variable is a name that is used to hold a value of any type during program execution. If the […]

  • 26 March

    Global variables in java

    In this post, we will see how to define global variables in java. Unlike C/C++, there are no standard global variables in java but you can still define global variables that can be used across all classes. Global variables are those variables that can be accessed across all the classes. Java does not support global […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.