Inorthward this tutorial, we'll cover the four types of loops in Java: the for loop, enhanced for loop (for-each), while loop and do-while loop. We'll likewise cover loop control flow concepts with nested loops, labeled loops, intermission statement, continue statement, render argument and local variable scope. We're also going to comprehend common loop exceptions and errors like infinite loops, java.lang.ArrayIndexOutOfBoundsException and java.lang.OutOfMemoryError.

Each type of loop will be shown with multiple examples and then you can see how it's used in a wide diversity of circumstances. Nosotros'll cover how you loop over characters in a string, an array of strings, an array of integers, likewise as iterating over collections such every bit java.util.List, java.util.Set and java.util.Map.

Introduction

Loops are used in most programs for a variety of reasons. The basic reason for using loops is when a repetitive action needs to be taken over and over. Ordinarily, this will be for a set of data. It's better and more efficient to utilise loops than having to explicitly write the lawmaking to process each action. And sometimes the programmer won't know in advance how many pieces of data the program volition encounter so looping will be necessary.

For example, loops can be used to iterate over a list of returned database records, to sort a list of numbers, or to read a file line by line.

Loops Concepts

All loops in Java utilize the same edifice blocks that we're going to ascertain here.

  • loop initialization – setting the initial value of variable(s) to be used in the loop
  • boolean condition – this is a boolean expression that determines whether to continue looping for one more iteration
  • step value (update value) – an update to the loop variable(s)
  • loop torso – execute the main part of the loop that does the processing

Throughout this tutorial, we'll be referring to these concepts every bit we introduce each loop.

For Loop

For loops are all-time used when you know how many times you accept to loop over something. For example, when looping over an array of numbers y'all will demand to loop over as many times equally there are elements in the assortment.

For Loop Structure

Coffee for loops are structured to follow this order of execution:

1) loop initialization
2) boolean condition – if true, keep to next step; if false, exit loop
iii) loop torso
four) pace value
5) repeat from step ii (boolean status)

java-for-loop-diagram

Example – Incrementing Step Value

Here is a simple for loop incrementing values from 0 to 99.

Discover the settings for the loop:

  • loop index is initialized to 0
  • boolean condition tests that the loop alphabetize is less than 100
  • pace value increments the loop index by 1 after every loop
  • loop exits when i gets to 100 and the boolean condition evaluates to fake
          

1
ii
3

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

Output:

          

ane
two
3
4
5
6
vii
8
9
10

0
one
ii
three
4
...
96
97
98
99

Example – Decrementing Step Value

Here is a like for loop decrementing values from 100 to 1.

          

1
2
3

for ( int i= 100 ; i> 0 ; i-- ) {
System.out.println (i) ;
}

Notice that we changed the post-obit:

  • loop is initialized at 100
  • boolean condition tests that the loop alphabetize is greater than 0
  • the step value decrements the loop index by 1 after every loop
  • loop exits when i gets to 0 and the boolean condition evaluates to false

Output:

          

1
two
3
4
5
6
7
8
nine

100
99
98
97
...
four
3
two
1

Example – Multiple Loop Variables

You lot can also use more i variable in the loop initialization, test expression and for the footstep value. The only limitation is that the boolean examination expression has to evaluate to a unmarried value (true or false). Here is an example using 3 different variables for the loop initialization, test status and footstep value. Notice how the examination condition only has one value, even though we're using iii variables.

          

1
two
3

for ( int i= 0, j= five, m= 30 ; (i+j+grand) < 500 ; i+= 5, j*= 2, k-= 2 ) {
System.out.println (i+j+one thousand) ;
}

Output:

          

one
2
3
iv
5
6
7

35
43
56
79
122
205
368

Example – No Initialization

Every office of the loop is optional. And so you don't take to have a loop initialization and step value, or fifty-fifty a examination status.

In the adjacent example, nosotros're missing the loop initialization considering nosotros're using a local variable that nosotros initialized before the loop.

          

1
two
3
4

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

Output:

          

Example – No Step Value

You lot also don't need the step (update) value. In the post-obit instance, we removed it and we're incrementing the loop index within the loop torso.

          

ane
2
3
4

int i= 0 ;
for ( ; i< 5 ; ) {
Organization.out.println (i++ ) ;
}

Output:

          

Example – Infinite Loop

Finally, we can remove the boolean test condition only that will cause an infinite loop and the program will never cease on its own.

          

ane
ii
3
4

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

Output:

          

1
2
3
four
v
6
7
8
9
10

0
1
2
3
four
5
6
vii
8
... keeps growing without finish

Example – Integer Array

To loop over an integer array with a for loop, we initialize the loop variable to 0, which is the first assortment index. The boolean expression tests to make sure that i is less than the size of the array because the last array alphabetize will exist 1 less than the size of the assortment.

          

one
2
iii
iv

int [ ] intArray = { 1, 3, 5, 7, 9 } ;
for ( int i= 0 ; i<intArray.length ; i++ ) {
Organisation.out.println (intArray[i] ) ;
}

Output:

          

Example – Cord Characters

To loop over a cord of characters with a for loop, we initialize the loop variable to 0 and and so utilize the Cord.charAt() method to get the character at the specified index. Merely like in the integer array example, nosotros're starting the loop index at 0 and going up to 1 less the size of the cord. This is because cord indexes work in a similar fashion equally arrays in Java: first grapheme index is 0 and the concluding character index volition exist 1 less than the size of the string.

          

1
2
3
4
5

String myString = "hullo" ;

for ( int i= 0 ; i<myString.length ( ) ; i++ ) {
Arrangement.out.print (myString.charAt (i) ) ;
}

Output:

          

Example – String Array

To loop over an assortment of strings with a for loop, we'll utilize a like technique like we used to loop over an array of integers. The loop index is initialized to 0 and nosotros keep looping until ane less than the size of the string array.

          

one
2
three
4
five
vi
vii
8
ix
10

String [ ] myStrings= {
"alpha",
"beta",
"gamma",
"delta"
} ;

for ( int i= 0 ; i<myStrings.length ; i++ ) {
Organization.out.println (myStrings[i] ) ;
}

Output:

          

i
2
3
4

alpha
beta
gamma
delta

Example – Listing

To loop over a coffee.util.List with a for loop, we initialize the loop variable to 0 and keep looping until i less than the size of the list. We use the Listing.become() method to retrieve the specific listing chemical element with the current loop index. The example uses a list of strings but the structure would piece of work the aforementioned way for a listing of other elements.

          

1
2
3
4
five
half-dozen
seven
viii
9

    List<Cord> myList = new ArrayList<String> ( ) ;
myList.add together ( "alpha" ) ;
myList.add ( "beta" ) ;
myList.add ( "gamma" ) ;
myList.add ( "delta" ) ;

for ( int i= 0 ; i<myList.size ( ) ; i++ ) {
System.out.println (myList.get (i) ) ;
}

Output:

          

ane
2
three
4

blastoff
beta
gamma
delta

Example – Ready 1

We tin't iterate over a java.util.Fix directly with a for loop by accessing its elements with an index the style we did for a list. Instead, we need to convert the ready into an array get-go and then iterate over the array. This is one way of converting a java.util.Prepare to an assortment. Notice that the converted assortment is a generic array of Objects even though the original set consisted of strings. Later on the conversion to the assortment, nosotros iterate over it in a similar way as nosotros did for an array of integers. Also discover that the set stored just the unique strings that we added and not in the lodge that we added them.

          

1
ii
3
4
5
vi
7
8
9
10
eleven
12
13

      Set<String> mySet = new HashSet<String> ( ) ;
mySet.add ( "alpha" ) ;
mySet.add together ( "alpha" ) ;
mySet.add together ( "beta" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "delta" ) ;

Object [ ] mySetStrings = mySet.toArray ( ) ;

for ( int i= 0 ; i<mySetStrings.length ; i++ ) {
Arrangement.out.println (mySetStrings[i] ) ;
}

Note how the output is in a different order from the club we inserted elements into the gear up:

          

1
2
3
4

alpha
delta
beta
gamma

Example – Set 2

We tin also use a for loop to iterate over a java.util.Set by converting it first to an array of the specific type. In this example, nosotros're iterating over the ready's elements in a for loop afterwards they've been converted to an assortment of strings.

          

1
2
iii
4
5
6
7
8
9
10
11
12
13

      Set<Cord> mySet = new HashSet<String> ( ) ;
mySet.add ( "blastoff" ) ;
mySet.add together ( "alpha" ) ;
mySet.add together ( "beta" ) ;
mySet.add together ( "gamma" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "delta" ) ;

String [ ] mySetStrings = mySet.toArray ( new String [mySet.size ( ) ] ) ;

for ( int i= 0 ; i<mySetStrings.length ; i++ ) {
Organisation.out.println (mySetStrings[i] ) ;
}

Note how the output is in a different order from the order we inserted elements into the set:

          

1
2
3
4

blastoff
delta
beta
gamma

Example – Map

To iterate over a java.util.Map with a for loop, we first get the map'south set up of keys and then catechumen that java.util.Ready to a Cord array.

          

1
ii
three
4
5
six
7
8
9
10
11
12
thirteen

Map < String,String>myMap = new HashMap< Cord,String> ( ) ;
myMap.put ( "a", "alpha" ) ;
myMap.put ( "b", "beta" ) ;
myMap.put ( "c", "gamma" ) ;
myMap.put ( "d", "delta" ) ;

    Gear up<String> keySet = myMap.keySet ( ) ;

String [ ] keys = keySet.toArray ( new Cord [keySet.size ( ) ] ) ;

for ( int i= 0 ; i<keys.length ; i++ ) {
System.out.println ( "Key:" + keys[i] + " Value:" + myMap.get (keys[i] ) ) ;
}

Output:

          

1
ii
3
4

Cardinal:a Value:blastoff
Key:b Value:beta
Primal:c Value:gamma
Cardinal:d Value:delta

Further Reading

The for Statement (The Coffee™ Tutorials)
Java Programming Tutorial – 22 – for Loops (YouTube)
How to Iterate over a Fix/HashSet without an Iterator?

Enhanced For Loop

Enhanced for loops (aka for-each or foreach loops) are a simplified version of a for loop. The advantage is that there is less lawmaking to write and less variables to manage. The downside is that you have no control over the step value and no admission to the loop index inside the loop body.

They are best used when the footstep value is a uncomplicated increment of 1 and when you merely need access to the current loop element. For instance, if y'all need to loop over every chemical element in an assortment or Drove without peeking ahead or behind the current element.

Enhanced For Loop Structure

Enhanced for loops follow this order of execution:

1) loop body
ii) repeat from step i until entire array or collection has been traversed

At that place is no loop initialization, no boolean status and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops.

java-enhanced-for-loop-diagram

Instance – Integer Array

You can utilize an enhanced for loop to traverse the elements of an int assortment one past one:

          

1
2
three
four

int [ ] intArray = { 1, 3, 5, 7, 9 } ;
for ( int currentValue : intArray) {
System.out.println (currentValue) ;
}

The currentValue variable holds the current value being looped over in the intArray array. Observe in that location's no explicit step value – information technology's always an increment by ane.

The colon tin can be thought of to hateful "in". So the enhanced for loop declaration states: loop over intArray and store the current array int value in the currentValue variable.

The output is:

          

Example – String Characters

We can't use the enhanced for loop to iterate directly over a single String. If you endeavour to do that as in the following code, you will get a compile time error.

          

1
2
3
4
5
6

String myString = "hello" ;

//compile fourth dimension error: Can only iterate over an array or an instance of coffee.lang.Iterable
for ( char c : myString) {

}

Output:

          

i
2

Exception in thread "chief" java.lang.Error: Unresolved compilation problem:
Can only iterate over an array or an instance of java.lang.Iterable

To solve this problem, we can convert the string to an array of characters and and so iterate over the array:

          

1
2
3
4
5

Cord myString = "hi" ;

for ( char c : myString.toCharArray ( ) ) {
System.out.impress (c) ;
}

Output:

          

Case – Cord Array

We can utilise the for-each loop to iterate over an array of strings. The loop declaration states: loop over myStrings String array and store the electric current String value in the currentString variable.

          

1
2
three
4
v
6
7
8
9
10

Cord [ ] myStrings= {
"alpha",
"beta",
"gamma",
"delta"
} ;

for ( String currentString : myStrings) {
System.out.println (currentString) ;
}

Output:

          

i
2
iii
4

alpha
beta
gamma
delta

Example – Listing

The enhanced for loop can also be used to iterate over a java.util.List as follows:

          

1
two
3
four
5
6
7
eight
9

    List<String> myList = new ArrayList<String> ( ) ;
myList.add ( "alpha" ) ;
myList.add ( "beta" ) ;
myList.add together ( "gamma" ) ;
myList.add ( "delta" ) ;

for ( String currentItem : myList) {
Organisation.out.println (currentItem) ;
}

The loop declaration states: loop over myList List of Strings and store the current List value in the currentItem variable.

Output:

          

1
2
3
four

blastoff
beta
gamma
delta

Case – Set

The enhanced for loop can also be used to iterate over a coffee.util.Set equally follows:

          

1
2
3
4
v
six
7
viii
9
10
11

    Fix<String> mySet = new HashSet<String> ( ) ;
mySet.add ( "alpha" ) ;
mySet.add ( "blastoff" ) ;
mySet.add ( "beta" ) ;
mySet.add ( "gamma" ) ;
mySet.add together ( "gamma" ) ;
mySet.add ( "delta" ) ;

for ( String currentItem : mySet) {
Organization.out.println (currentItem) ;
}

The loop declaration states: loop over mySet Set of Strings and shop the current Set value in the currentItem variable. Notice that since this is a Set, duplicate Cord values are non stored. Also, there'southward no need to convert the Set elements into an array the way we had to do for a regular for loop.

Output:

          

1
two
3
4

blastoff
delta
beta
gamma

Example – Map

To iterate over a java.util.Map with a for-each loop, we tin iterate over the map's set of keys:

          

1
2
3
four
v
6
7
8
9
ten
11

Map < Cord,String>myMap = new HashMap< String,Cord> ( ) ;
myMap.put ( "a", "blastoff" ) ;
myMap.put ( "b", "beta" ) ;
myMap.put ( "c", "gamma" ) ;
myMap.put ( "d", "delta" ) ;

    Prepare<Cord> keySet = myMap.keySet ( ) ;

for ( String currentKey : keySet) {
System.out.println ( "Fundamental:" + currentKey + " Value:" + myMap.become (currentKey) ) ;
}

Output:

          

i
2
3
4

Cardinal:a Value:alpha
Key:b Value:beta
Key:c Value:gamma
Key:d Value:delta

Farther Reading

For-Each Loop – Java 5 Documentation
What is the syntax of enhanced for loop in Java?
Coffee Programming Tutorial – 31 – Enhanced for Loop (YouTube)
Java for loop syntax: "for (T obj : objects)"

While Loop

While loops are best used when you lot don't know how many times you have to loop over something. For example, when reading lines of text from a file, a program will continue reading until it gets to the cease of the file, without knowing beforehand how many lines it volition read.

While Loop Structure

While loops in Coffee have a simpler structure than for loops because they don't accept an initialization or a pace value. Their structure follows this society of execution:

i) boolean status – if true, proceed to side by side step; if fake, leave loop
2) loop body
3) repeat from stride 1 (boolean condition)

java-while-loop-diagram

Instance – Integer Array

To loop over an integer assortment with a while loop, nosotros initialize a local variable to 0, which is the first assortment alphabetize. The boolean expression tests to make sure that i is less than the size of the assortment because the last array index will be 1 less than the size of the array. Nosotros also increment the local variable inside the loop body.

          

1
2
three
4
5

int [ ] intArray = { 1, iii, 5, 7, nine } ;
int i= 0 ;
while (i<intArray.length ) {
System.out.println (intArray[i++ ] ) ;
}

Output:

          

Example – String Characters

To loop over a string of characters with a while loop, nosotros initialize a local variable to 0 and and so use the String.charAt() method to get the character at the specified index. Every bit in the previous example, we increment the local variable within the loop body.

          

1
2
3
four
5
half-dozen

String myString = "hi" ;

int i= 0 ;
while (i<myString.length ( ) ) {
Organization.out.impress (myString.charAt (i++ ) ) ;
}

Output:

          

Case – String Assortment

To loop over an array of strings with a while loop, we'll use a like technique like nosotros used to loop over an array of integers. A local variable is initialized to 0 and we go along looping until 1 less than the size of the string array, while incrementing the local variable within the loop body.

          

i
2
3
4
five
6
7
8
9
10
11

Cord [ ] myStrings= {
"alpha",
"beta",
"gamma",
"delta"
} ;

int i= 0 ;
while (i<myStrings.length ) {
System.out.println (myStrings[i++ ] ) ;
}

Output:

          

1
2
3
4

alpha
beta
gamma
delta

Example – List

To loop over a java.util.List with a while loop, we initialize a local variable to 0 to use it as the list index and keep looping until 1 less than the size of the listing. We utilize the List.become() method to retrieve the specific listing element with the local variable and increase information technology within the loop body.

          

one
2
3
4
5
6
seven
8
9
ten

    List<String> myList = new ArrayList<String> ( ) ;
myList.add ( "blastoff" ) ;
myList.add ( "beta" ) ;
myList.add ( "gamma" ) ;
myList.add ( "delta" ) ;

int i= 0 ;
while (i<myList.size ( ) ) {
System.out.println (myList.become (i++ ) ) ;
}

Output:

          

i
2
3
4

alpha
beta
gamma
delta

Example – Gear up one

We tin can't iterate over a java.util.Set directly with a while loop past accessing its elements with an index the style we did for a listing. Instead, nosotros need to convert the set into an array beginning and then iterate over the array. The converted array is a generic array of Objects even though the original set up consisted of strings. After the conversion to the assortment, we iterate over it in a like way every bit we did for an array of integers.

          

1
2
3
4
5
half dozen
7
8
9
10
11
12
thirteen
fourteen

    Set<String> mySet = new HashSet<String> ( ) ;
mySet.add together ( "blastoff" ) ;
mySet.add ( "alpha" ) ;
mySet.add ( "beta" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "gamma" ) ;
mySet.add together ( "delta" ) ;

Object [ ] mySetStrings = mySet.toArray ( ) ;

int i= 0 ;
while (i<mySetStrings.length ) {
System.out.println (mySetStrings[i++ ] ) ;
}

Output:

          

i
2
three
four

alpha
delta
beta
gamma

Example – Fix 2

Nosotros can also use a while loop to iterate over a coffee.util.Set by converting information technology showtime to an array of the specific type. In this example, we're iterating over the set's elements in a while loop afterwards they've been converted to an array of strings.

          

ane
2
3
four
5
half dozen
7
viii
9
10
eleven
12
13
14
xv

    Set<Cord> mySet = new HashSet<String> ( ) ;
mySet.add ( "alpha" ) ;
mySet.add ( "blastoff" ) ;
mySet.add together ( "beta" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "delta" ) ;

Cord [ ] mySetStrings = mySet.toArray ( new String [mySet.size ( ) ] ) ;

int i= 0 ;

while (i<mySetStrings.length ) {
Organisation.out.println (mySetStrings[i++ ] ) ;
}

Output:

          

1
2
3
four

alpha
delta
beta
gamma

Example – Map

To iterate over a java.util.Map with a while loop, we start get the map's set of keys and and then convert that java.util.Ready to a String assortment. Notation how nosotros have to manually increase i within the loop body because we're not using a for loop.

          

ane
ii
three
four
five
6
7
viii
ix
10
11
12
13
fourteen
15

Map < String,String>myMap = new HashMap< Cord,String> ( ) ;
myMap.put ( "a", "alpha" ) ;
myMap.put ( "b", "beta" ) ;
myMap.put ( "c", "gamma" ) ;
myMap.put ( "d", "delta" ) ;

    Set<String> keySet = myMap.keySet ( ) ;

String [ ] keys = keySet.toArray ( new String [keySet.size ( ) ] ) ;

int i= 0 ;
while (i<keys.length ) {
System.out.println ( "Key:" + keys[i] + " Value:" + myMap.get (keys[i] ) ) ;
i++;
}

Output:

          

1
ii
3
4

Cardinal:a Value:alpha
Central:b Value:beta
Key:c Value:gamma
Key:d Value:delta

Example – Infinite Loop

An space while loop will occur when the boolean condition is always truthful. This loop could all the same be cleaved out of if inside the loop trunk the suspension or return argument was used.

          

ane
2
3
4

int i= 0 ;
while ( truthful ) {
Arrangement.out.println (i++ ) ;
}

Output:

          

Another example of an infinite while loop tin happen when you accidentally place a semicolon after the while loop declaration. You might think the loop would execute normally and go out merely it will be in an infinite loop with nothing displayed to the output:

          

1
two
iii
four
five
six
7
eight
9
10
11

String [ ] myStrings= {
"alpha",
"beta",
"gamma",
"delta"
} ;

int i= 0 ;
while (i<myStrings.length ) ; {
System.out.println (myStrings[i++ ] ) ;
}

Further Reading

The while and do-while Statements – The Java™ Tutorials
while Loop in java (tutorials betoken)
Java Programming Tutorial – 13 – While Loop (YouTube)

Do-While Loop

Practise-while loops (aka do loops) are best used when you don't know how many times you have to loop over something AND yous desire to execute the loop at least once. For example, if a program continuously takes input from the user and outputs it, until the user enters the letter "q", and so you would use a do-while loop since you would need to take the user's input at least once.

Do-While Loop Structure

Merely like while loops, do-while loops in Java accept a simpler structure than for loops because they don't have an initialization or a step value. They are similar to while loops but the order of operations is unlike. Their construction follows this club of execution:

1) loop body
2) boolean condition – if true, continue to adjacent step; if false, leave loop
3) repeat from stride 1 (loop torso)

The difference between a do-while loop and a while loop is that the do-while loop executes the torso starting time before evaluating the boolean status, whereas the while loop first evaluates the boolean condition before executing the loop body.

java-do-while-loop-diagram

Example – Integer Array

To loop over an integer assortment with a do-while loop, we initialize a local variable to 0, which is the first array alphabetize. The boolean expression tests to make sure that i is less than the size of the assortment because the last assortment index will be 1 less than the size of the array. We also increment the local variable inside the loop body. Since the exercise loop executes the loop body first earlier checking the boolean expression, the code would throw a ArrayIndexOutOfBoundsException if the array was empty.

          

1
2
three
4
5

int [ ] intArray = { ane, 3, v, 7, 9 } ;
int i= 0 ;
practice {
Organization.out.println (intArray[i++ ] ) ;
} while (i<intArray.length ) ;

Output:

          

Instance – String Characters

To loop over a string of characters with a do-while loop, we initialize a local variable to 0 and and so use the String.charAt() method to get the grapheme at the specified index. As in the previous example, nosotros increment the local variable inside the loop body. If the string was empty, the lawmaking would cause a StringIndexOutOfBoundsException.

          

1
2
three
four
5
6

Cord myString = "hello" ;

int i= 0 ;
do {
Organisation.out.print (myString.charAt (i++ ) ) ;
} while (i<myString.length ( ) ) ;

Output:

          

Example – String Array

To loop over a string of characters with a do-while loop, we initialize a local variable to 0 and so utilize the Cord.charAt() method to get the graphic symbol at the specified alphabetize. Equally in the previous example, we increase the local variable inside the loop body. The code would throw a ArrayIndexOutOfBoundsException if the array was empty.

          

ane
2
iii
iv
five
vi
7
8
9
ten
11

String [ ] myStrings= {
"alpha",
"beta",
"gamma",
"delta"
} ;

int i= 0 ;
do {
Arrangement.out.println (myStrings[i++ ] ) ;
} while (i<myStrings.length ) ;

Output:

          

1
2
3
iv

alpha
beta
gamma
delta

Example – List

To loop over a java.util.List with a do-while loop, we initialize a local variable to 0 to use it as the list alphabetize and keep looping until 1 less than the size of the list. We utilize the Listing.get() method to call back the specific list element with the local variable and increase it within the loop trunk. The lawmaking would throw a ArrayIndexOutOfBoundsException if the list was empty.

          

1
two
3
iv
5
6
7
eight
9
10

    Listing<Cord> myList = new ArrayList<String> ( ) ;
myList.add ( "alpha" ) ;
myList.add ( "beta" ) ;
myList.add ( "gamma" ) ;
myList.add ( "delta" ) ;

int i= 0 ;
do {
Arrangement.out.println (myList.get (i++ ) ) ;
} while (i<myList.size ( ) ) ;

Output:

          

ane
two
3
four

blastoff
beta
gamma
delta

Example – Set 1

Nosotros can't iterate over a java.util.Set directly with a exercise-while loop by accessing its elements with an index the manner we did for a list. Instead, we need to convert the set into an array beginning and and then iterate over the array. The converted assortment is a generic array of Objects even though the original set consisted of strings. Afterwards the conversion to the array, we iterate over it in a similar way equally we did for an array of integers. The code would throw a ArrayIndexOutOfBoundsException if the set up was empty.

          

1
2
iii
4
v
6
7
8
9
x
11
12
13
14

    Set<String> mySet = new HashSet<String> ( ) ;
mySet.add ( "alpha" ) ;
mySet.add together ( "alpha" ) ;
mySet.add ( "beta" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "delta" ) ;

Object [ ] mySetStrings = mySet.toArray ( ) ;

int i= 0 ;
do {
System.out.println (mySetStrings[i++ ] ) ;
} while (i<mySetStrings.length ) ;

Output:

          

one
2
3
4

alpha
delta
beta
gamma

Example – Set 2

We can too use a practise-while loop to iterate over a java.util.Ready past converting it offset to an array of the specific type. In this example, we're iterating over the prepare's elements in a do-while loop afterward they've been converted to an array of strings. The code would throw a ArrayIndexOutOfBoundsException if the fix was empty.

          

i
2
iii
4
5
vi
vii
8
nine
x
11
12
13
14
15

    Set<String> mySet = new HashSet<String> ( ) ;
mySet.add ( "alpha" ) ;
mySet.add ( "alpha" ) ;
mySet.add together ( "beta" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "gamma" ) ;
mySet.add ( "delta" ) ;

String [ ] mySetStrings = mySet.toArray ( new String [mySet.size ( ) ] ) ;

int i= 0 ;

do {
System.out.println (mySetStrings[i++ ] ) ;
} while (i<mySetStrings.length ) ;

Output:

          

1
2
iii
4

alpha
delta
beta
gamma

Example – Map

To iterate over a java.util.Map with a practice-while loop, we first get the map's set of keys and then catechumen that java.util.Set up to a String array. The code would throw a ArrayIndexOutOfBoundsException if the map was empty.

          

1
two
iii
4
v
6
7
8
9
ten
11
12
13
14
15

Map < Cord,String>myMap = new HashMap< String,String> ( ) ;
myMap.put ( "a", "alpha" ) ;
myMap.put ( "b", "beta" ) ;
myMap.put ( "c", "gamma" ) ;
myMap.put ( "d", "delta" ) ;

    Set<Cord> keySet = myMap.keySet ( ) ;

String [ ] keys = keySet.toArray ( new String [keySet.size ( ) ] ) ;

int i= 0 ;
exercise {
Organisation.out.println ( "Central:" + keys[i] + " Value:" + myMap.get (keys[i] ) ) ;
i++;
} while (i<keys.length ) ;

Output:

          

1
2
iii
4

Central:a Value:alpha
Central:b Value:beta
Key:c Value:gamma
Central:d Value:delta

Instance – Infinite Loop

An infinite while loop will occur when the boolean condition is always truthful. This loop could still be broken out of if inside the loop torso the break or return statement was used.

          

ane
2
3
4

int i= 0 ;
do {
System.out.println (i++ ) ;
} while ( true ) ;

Output:

          

Further Reading

The while and practise-while Statements – The Coffee™ Tutorials
Java Programming Tutorial – 24 – do while Loops (YouTube)
Do while syntax for java – debugging exercise

Loop Command Flow

Break Statement

Sometimes it's necessary to exit a loop earlier the loop has finished fully iterating over all the step values. For example, looping over a list of numbers until you lot discover a number that satisfies a certain status. Or looping over a stream of characters from a file until a certain character is read.

In the following example, we're using a elementary for loop to print out values from 0 to 9:

          

1
2
three

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

Output:

          

one
two
3
4
5
6
7
eight
ix
10

0
one
ii
3
4
5
6
seven
8
ix

At present if we add together a suspension statement when i==4, our lawmaking volition break out of the loop once i equals iv. Yous tin utilise the pause statement to break out of for loops, while loops and do-while loops. The interruption statement volition only break out of the current loop. In order to intermission out of an outer loop from a nested inner loop, you would demand to apply labels with the interruption statement.

          

ane
2
3
4
5
six

for ( int i= 0 ; i< ten ; i++ ) {
System.out.println (i) ;
if (i== four ) {
suspension ;
}
}

Output:

          

Keep Statement

Java's go along statement skips over the current iteration of a loop and goes directly to the side by side iteration. Afterward calling the go on statement in a for loop, the loop execution will execute the step value and evaluate the boolean condition before proceeding with the next iteration. In the following example, we're printing out all values from 0 to 9 in a loop only nosotros skip over press out four.

          

one
ii
three
four
5
6

for ( int i= 0 ; i< x ; i++ ) {
if (i== iv ) {
continue ;
}
Organization.out.println (i) ;
}

Output:

          

1
two
3
iv
v
half-dozen
7
viii
nine

0
1
ii
iii
5 <---- SKIPPED OVER 4 and continued with next loop iteration
half-dozen
vii
eight
9

You can also use the proceed statement in a while loop but you would need to iterate the step value within the loop. Notation how the i++ iteration is done in two place: right earlier calling coninue and at the end of the loop trunk. If i wasn't incremented before continue, the loop would become stuck in in space loop considering i would be stuck at 4 and keep calling keep to go to the top of the loop.

          

1
two
3
4
5
six
7
8
ix

int i= 0 ;
while (i< 10 ) {
if (i== 4 ) {
i++;
continue ;
}
System.out.println (i) ;
i++;
}

Output:

          

1
2
three
4
5
6
7
8
ix

0
1
2
three
v <---- SKIPPED OVER 4 and continued with adjacent loop iteration
half dozen
vii
8
9

The keep statement in a practice-while loop is used in a similar way as for a while loop – the loop variable has to be incremented manually in 2 places in the loop body, to forestall an space loop condition, merely like for a while loop.

          

one
two
3
4
5
6
seven
8
9

int i= 0 ;
practice {
if (i== 4 ) {
i++;
continue ;
}
System.out.println (i) ;
i++;
} while (i< ten ) ;

Output:

          

1
2
3
four
5
vi
7
8
9

0
ane
2
3
5 <---- SKIPPED OVER iv and continued with next loop iteration
vi
vii
8
9

Nested Loops

Sometimes information technology's necessary to have loops within loops. For example, when reading from a table of data with rows and columns, the showtime (outer) loop can loop over all the rows and the 2nd (inner) loop can loop over all the columns inside each row.

When loops are inside other loops we refer to the inner loops as nested. There could fifty-fifty be multiple layers of nested loops. Here'due south an case of a 3 layer nested loop:

          

1
2
3
4
5
6
vii

for ( int i= 0 ; i< 5 ; i++ ) { //loop one
for ( int j= 0 ; j< 4 ; j++ ) {//loop 2
for ( int chiliad= 0 ; one thousand< 2 ; yard++ ) { //loop three
System.out.println ( "[" + i + "][" + j + "][" + k + "]" ) ;
}
}
}

Output:

          

1
two
three
four
five
half-dozen
seven
8
9
10
11
12
thirteen
14
15
sixteen
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

[0][0][0]
[0][0][i]
[0][1][0]
[0][ane][1]
[0][two][0]
[0][2][1]
[0][iii][0]
[0][3][1]
[one][0][0]
[1][0][one]
[i][1][0]
[ane][1][1]
[1][2][0]
[1][2][1]
[1][3][0]
[1][3][i]
[2][0][0]
[2][0][1]
[two][i][0]
[two][1][1]
[2][2][0]
[2][ii][one]
[2][three][0]
[2][3][ane]
[3][0][0]
[three][0][1]
[3][1][0]
[three][i][1]
[3][ii][0]
[three][2][one]
[3][3][0]
[3][3][one]
[4][0][0]
[iv][0][1]
[4][ane][0]
[4][1][ane]
[four][2][0]
[four][2][1]
[4][3][0]
[4][3][i]

Loop Characterization

Many earlier programming languages such as C/C++ used the goto keyword to make the program jump or "become to" another part of the plan from where it'due south currently executing. The goto statement definitely has a bad rap because of its likeliness to make the program harder to understand and to lead to "spaghetti code" where the catamenia of execution is very hard to follow.

Evils of Goto Statement

Java doesn't have use the goto keyword fifty-fifty though information technology is listed every bit an unused keyword of the language. Java does take labels, which is a express version of a goto statement within loops to make the program jump to some other function of the plan.

You can use labels inside nested loops by specifying where you desire execution to continue subsequently breaking out of an inner loop. Usually, the break statement volition only pause out of the innermost loop so when you want to break out of an outer loop, you can use labels to reach this, essentially doing something similar to a goto argument.

The post-obit instance uses iii loops, all nested within each other. Since there's no way to completely intermission out of the outer nigh loop from inside the inner almost loop, we can use the label "outer1" to accomplish this and specify the characterization next to the break statement.

          

1
2
iii
4
v
vi
7
viii
9
10
11

    outer1:
for ( int i= 0 ; i< 5 ; i++ ) {
for ( int j= 0 ; j< 4 ; j++ ) {
for ( int thou= 0 ; yard< 2 ; k++ ) {
Organisation.out.println ( "[" + i + "][" + j + "][" + k + "]" ) ;
if (j == three ) {
break outer1;
}
}
}
}

Output:

          

i
two
3
4
5
six
7

[0][0][0]
[0][0][1]
[0][ane][0]
[0][i][1]
[0][2][0]
[0][two][one]
[0][iii][0]

Find how the terminal line displayed is "[0][three][0]" which is where j == 3 and that's where nosotros chosen "interruption outer1;" to break out of the outer most loop. We can also place a characterization on the second loop to allow breaking out it without breaking out of the unabridged loop:

          

1
2
3
iv
five
6
7
eight
nine
10
11

for ( int i= 0 ; i< 5 ; i++ ) {
outer2:
for ( int j= 0 ; j< 4 ; j++ ) {
for ( int k= 0 ; chiliad< 2 ; 1000++ ) {
System.out.println ( "[" + i + "][" + j + "][" + k + "]" ) ;
if (j == 3 ) {
intermission outer2;
}
}
}
}

Output:

          

1
2
3
4
five
6
7
8
9
10
11
12
13
fourteen
15
16
17
xviii
xix
twenty
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

[0][0][0]
[0][0][1]
[0][i][0]
[0][i][ane]
[0][ii][0]
[0][two][one]
[0][3][0]  <---- BREAKS OUT OF 2ND LOOP
[1][0][0]
[1][0][1]
[1][1][0]
[ane][1][i]
[1][2][0]
[1][ii][1]
[1][iii][0]  <---- BREAKS OUT OF 2ND LOOP
[2][0][0]
[2][0][i]
[2][1][0]
[2][i][1]
[2][2][0]
[2][2][1]
[2][iii][0]  <---- BREAKS OUT OF 2ND LOOP
[3][0][0]
[3][0][1]
[3][i][0]
[3][1][1]
[3][two][0]
[three][ii][1]
[3][3][0]  <---- BREAKS OUT OF 2ND LOOP
[4][0][0]
[4][0][1]
[four][i][0]
[iv][1][1]
[4][2][0]
[4][2][i]
[four][three][0]  <---- BREAKS OUT OF 2d LOOP

Detect all the times the code breaks out of the 2d loop with the "outer2" characterization. Each time it breaks out, outer virtually loop gets incremented past i and the lawmaking keep executing.

You can also use labels with the continue keyword to continue looping from a specific betoken. Taking the first labelled loop example and just irresolute i line to specify "go along outer1;" instead of "break outer1;" will cause the loop to continue looping from the "outer1" label instead of breaking out of the loop. Note how each time "continue outer1" is called, the code continues from the outer loop later incrementing the loop alphabetize i past 1.

          

ane
2
iii
iv
five
6
seven
viii
ix
10

    outer1:
for ( int i= 0 ; i< 5 ; i++ ) {
for ( int j= 0 ; j< iv ; j++ ) {
for ( int m= 0 ; k< 2 ; k++ ) {
Organisation.out.println ( "[" + i + "][" + j + "][" + g + "]" ) ;
if (j == 3 ) {
continue outer1;
}
}
}

Output:

          

ane
two
three
iv
v
vi
7
8
9
x
11
12
thirteen
14
xv
16
17
xviii
xix
twenty
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

[0][0][0]
[0][0][1]
[0][i][0]
[0][one][1]
[0][2][0]
[0][2][1]
[0][3][0] <---- CONTINUE WITH Characterization CALLED Here
[ane][0][0] <---- CONTINUES FROM Next ITERATION OF OUTER LOOP
[i][0][1]
[1][1][0]
[1][1][i]
[i][2][0]
[i][2][1]
[one][3][0] <---- CONTINUE WITH LABEL CALLED Hither
[2][0][0] <---- CONTINUES FROM Adjacent ITERATION OF OUTER LOOP
[ii][0][1]
[2][1][0]
[2][1][i]
[ii][two][0]
[2][ii][1]
[2][3][0] <---- CONTINUE WITH Characterization CALLED Here
[iii][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[three][0][1]
[3][1][0]
[3][i][ane]
[iii][2][0]
[3][2][1]
[3][3][0] <---- Keep WITH LABEL Chosen Here
[iv][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[4][0][1]
[4][1][0]
[four][ane][1]
[4][2][0]
[iv][2][1]
[4][three][0]

Return Statement Inside Loops

Java's return statement is used to exit program execution from a method. Information technology tin likewise be employ to go out from a loop (or nested loop) within a method. Its behavior is similar to the pause argument but whereas the break statement exits the electric current loop, the render argument exits the unabridged method.

          

1
2
three
4
v
half-dozen

for ( int i= 0 ; i< 10 ; i++ ) {
if (i== 4 ) {
return ; //go out current method
}
Organization.out.println (i) ;
}

Output:

          

Local Variable Scope

Local variables defined within loops are visible only inside the loop. If y'all attempt to utilise one of these variables exterior the loop, you will get a compilation mistake. For example, for loops usually initialize loop variable and these are only accessible from within the for loop. The following example uses a do-while loop with ii local variables: i and j. i was defined before the loop then it's however accessible after the loop. But j is defined from within the loop then the compiler will throw an mistake when trying to access j exterior the loop.

          

i
2
three
4
5
half dozen
7
8

int i= 0 ;
do {
int j = 0 ; //defined in loop
System.out.println (i++ ) ;
} while (i < 5 ) ;

    i = 0 ; //no error - defined before loop
j = 1 ; //compile error - divers within loop

Output:

          

1
2

Exception in thread "primary" java.lang.Error: Unresolved compilation trouble:
j cannot be resolved to a variable

Further Reading

Breaking out of nested loops in Java
"loop:" in Java code. What is this, why does it compile?

Loop Errors and Exceptions

Loops take their own unique errors and exceptions that we will examine below.

Infinite Loops

We already covered space loops as they pertain to for loops, while loops and exercise-while loops. The main idea is that the loop never exits because the boolean status is always true.

Here's another example of an space for loop where a subtle error is introduced. The code uses 2 loop variables: i and j. Note how the boolean expression uses i but the pace value uses j. This will cause an infinite loop because i never gets incremented and the boolean expression will always evaluate to truthful.

          

ane
2
iii
four
5

int [ ] intArray = { 1, 3, five, 7, 9 } ;

for ( int i= 0, j= 0 ; i<intArray.length ; j++ ) {
Arrangement.out.println (intArray[i] ) ;
}

Output:

          

Assortment Index Out Of Premises Exception

This exception tin can occur when the loop tries to admission an assortment element beyond the size of the array. The errors tin be quite subtle equally shown in the following instance:

          

1
2
3
4
5

int [ ] intArray = { 1, iii, 5, 7, 9 } ;

for ( int i= 0 ; i<=intArray.length ; i++ ) {
Organisation.out.println (intArray[i] ) ;
}

Output:

          

one
ii
3
4
5
6

one
iii
5
7
ix
Exception in thread "master" java.lang.ArrayIndexOutOfBoundsException: v

The exception occurs because the loop'south boolean expression checks if i is less than or equal to the size of the array. But since the assortment has 5 elements, the final valid assortment index will be 4. Then when the loop tries to admission the assortment with alphabetize five, the JVM throws a ArrayIndexOutOfBoundsException. This is why the output shows a "five" where the exception is thrown.

The next example uses a exercise loop to brandish the elements in an assortment. Since the do loop executes the loop torso commencement before checking the boolean expression, this code throws an ArrayIndexOutOfBoundsException considering an empty array will not have a single element.

          

1
2
3
4
5

int [ ] intArray = { } ;
int i= 0 ;
do {
System.out.println (intArray[i++ ] ) ;
} while (i<intArray.length ) ;

Output:

          

1

Exception in thread "main" coffee.lang.ArrayIndexOutOfBoundsException: 0

String Index Out of Bounds Exception

This exception can occur when accessing an element within a string that doesn't exist. It's similar to ArrayIndexOutOfBoundsException just more specific to strings. In the following do-while loop, the code is trying to access the starting time character in an empty string.

          

1
2
three
4
5
6

String myString = "" ;

int i= 0 ;
do {
Organization.out.print (myString.charAt (i++ ) ) ;
} while (i<myString.length ( ) ) ;

Output:

          

1

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

Out of Retentivity Fault

Ofttimes loops encounter a coffee.lang.OutOfMemoryError when each loop iteration allocates more and more memory. Here is a elementary example showing how each loop iteration allocates retention for a progressively larger array of integers until the JVM throws an OutOfMemoryError. Each loop iteration multiples the size of the assortment by v.

          

1
2
3
4
v
vi

int arraySize = 100 ;
for ( int i= 0 ; i< 15 ; i++ ) {
int [ ] intArray = new int [arraySize] ;
System.out.println ( "Created integer array of size: " + arraySize) ;
arraySize *= 5 ;
}

Output:

          

i
ii
3
4
v
6
7
8
ix
10
xi

Created integer assortment of size: 100
Created integer array of size: 500
Created integer array of size: 2500
Created integer array of size: 12500
Created integer array of size: 62500
Created integer assortment of size: 312500
Created integer array of size: 1562500
Created integer array of size: 7812500
Created integer assortment of size: 39062500
Created integer array of size: 195312500
Exception in thread "master" java.lang.OutOfMemoryError: Java heap space

Farther Reading

Very elementary for loop error Coffee
For Loop in Coffee | Important points
java.lang.ArrayIndexOutOfBoundsException: iii in a while loop