For Each Loop In Java
for-each loop
It is a Java 5 feature. For each loop or enhanced for loop is used to traverse an array or collection in Java. It is simple to use than for loop because in it, we don’t need to increment the value and use subscript notation.
It works on the elements basis and not index basis. It returns an element one by one in the defined variable.
Syntax
for(Type var: array)
{
// statements or code.
}
Let’s see an example, given below.
Code
- public class ForEachExm {
- public static void main(String[] args) {
- int arr[] = {1, 2, 3, 4, 5};
- for (int s : arr) {
- System.out.println("Array:" + s);
- }
- }
- }
Output
The Nested loop
Java also allows to be nested i.e., one loop is declared inside another loop.
Let’s see an example, given below.
Code
- public class NestedLoopExm {
- public static void main(String args[]) {
- for (int i = 1; i < 11; i += 1) {
- for (int j = 0; j < 9 - i / 2; j++) {
- System.out.println("");
- }
- for (int j = 0; j < i; j++) {
- System.out.println("*");
- }
- System.out.println("\n");
- }
- System.out.println("");
- }
- }
Output
Summary
Thus, we learnt “For each loop” or enhanced for loop is used to traverse an array or collection in Java and also learnt how to use it.