a peek into my MIND

February 8, 2010

Exiting nested loops in java using named statements

Filed under: Java — Bharat Kondeti @ 10:17 pm

There may be cases when one has to break the outer for loop when a condition get’s satisfied in the inner for loop.

In the following example code, I am finding the country where the state belongs to..

Country rc = null;
boolean stop = false;
for (Country country : countries) {
	if(stop) break;
	for (State state : country.getStates()) {
		if(state.getName().equalsIgnoreCase(stateName)) {
			rc = country; stop = true; break;
		}
	}
}

In the following example I am naming my external for loop and passing that name to the break statement.

Country rc = null;
COUNTRY:
for (Country country : countries) {
	for (State state : country.getStates()) {
		if(state.getName().equalsIgnoreCase(stateName)) {
			rc = country; break COUNTRY;
		}
	}
}
Advertisements

1 Comment »

  1. Great tutorial.. Thanks for the info..

    Comment by Khairul Ikhwan Kamarudin — February 9, 2010 @ 2:48 am


RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: