The Artima Developer Community
Sponsored Link

Java Buzz Forum
How to break from nested loop in Java

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Javin Paul

Posts: 1090
Nickname: javinpaul
Registered: Jan, 2012

Javin Paul is Java Programmer working on Finance domain.
How to break from nested loop in Java Posted: Dec 17, 2014 7:11 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Javin Paul.
Original Post: How to break from nested loop in Java
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
Latest Java Buzz Posts
Latest Java Buzz Posts by Javin Paul
Latest Posts From Java67

Advertisement
There are situations we need nested loops in Java, one loop containing another loop e.g. to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in two dimensional array. There are couple of more situations where you need nested looping e.g.  printing pascal triangle and printing those star structures exercises from school days. Sometime depending upon some condition we also like to came out of both inner and outer loop. For example while searching a number in a two dimensional array, once you find the number, you want to come out of both loop. Question is how can you break from nested loop in Java. You all know about break right? you have seen break in switch statements, or terminating for, while and do while loop, but not many Java developer know but there is a feature called labeled break, which you can used to break from nested loop. All the places, where you have used break before is example of unlabeled break, but once you use label with break you can terminate a particular loop in nested loop structure. In order to use labeled for loop, you first need to label each loop as OUTER or INNER, or whatever you want to call them. Then depending upon from which loop you want to exit, you can call break statement as shown in our example. By the way, there is a better way to do the same thing, by externalizing the code of nested loop into a method and using return statement for coming out of the loop. This improves readability of your algorithm by giving appropriate name to your logic.
Read more »

Read: How to break from nested loop in Java

Topic: Creating a REST API with Spring Boot and MongoDB Previous Topic   Next Topic Topic: The Inconvenient Truth About Dynamic vs. Static Typing

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use