JAVA foreach loop: introduction

java foreach loop for beginners

The JAVA foreach loop is known also as the enhanced for loop.

It is introduced by Java 2 Platform, Standard Edition (J2SE™) version 5.0 for iterating over arrays.

The JAVA foreach loop statement is used to repeat a set of instructions multiple times like the other java loops.

java foreach loop: syntax

for (typeElement elementVariableName : arrayName) {

<statement_or_block>

}

JAVA foreach loop repeats the set of instructions for each element in the array.

We may not know the exact number of elements in the array. But we are sure that our processing is done for each element in that array.

The JAVA foreach loop enhances the readability of the code.

JAVA foreach loop  Examples:

JAVA Foreach loop and array example

public class TestForEach {
public static void main(String[] args) {
int[] tab = { 1, 2, 3, 4, 5 };
for (int item : tab) {
System.out.println(item);
}
}
}

This code displays each integer in the tab array:

The result of the execution of this program is the following:

1

2

3

4

5

JAVA Foreach loop and arraylist example

The arrayList is a JAVA class which represents an array of objets.

To learn more about arrays, check the JAVA arrays tutorial.

To learn more about classes and objects, check the JAVA classes tutorial.

public class
TestForEach {
public static void main(String[] args) {
ArrayList<Integer> tab = new ArrayList<Integer>();
tab.add(1);
tab.add(2);
tab.add(3);
tab.add(4);
tab.add(5);
for (int item : tab) {
System.out.println(item);
}
}
}

The output of this program is the following:

1

2

3

4

5

Special Loop Flow Control

Java foreach loop and the break keyword

The break keyword finishes the loop statement.

It is generally used to stop the execution of the do foreach loop if some condition is true.

public class TestForeach {
public static void main(String[] args) {
int [] tab = {1,2,3,4,5};
for (int item : tab) {
if(item == 3){
break;
}
System.out.println(item);
}     
}
}

The output of this JAVA code is the following:

1

2

Java Foreach loop and the continue keyword

The JAVA continue keyword is used to skip one iteration.

public
class TestForEach {
public static void main(String[] args) {
int[] tab = { 1, 2, 3, 4, 5 };
for (int item : tab) {
if (item == 3) {
continue;
}
System.out.println(item);
}
}
}

The output of this code is the following:

1

2

4

5

We notice that we skipped the processing of the item number  3.

This core JAVA tutorial which deals with java foreach loop statement arrives at its end.

To check the other JAVA loop statements, please check the JAVA Loops tutorial.

Please, don’t forget to follow us on Facebook to get our next JAVA core tutorial.

Post a Comment

Previous Post Next Post