Site icon TestingDocs.com

Enhanced For Loop in Java

Enhanced For Loop

The Enhanced For Loop in Java provides an alternative approach to traverse the array or collection in java and it eliminates the possibility of errors and makes it more readable. Its main purpose is to traverse the array or collection of elements. This loop is also called a For-Each loop.

It is also known as the for-each loop because it traverses each element one after another sequence and it makes the code readable. Enhanced for loops are simple to use. The break/continue statements can also be used to control the behavior of enhanced for loops.

Ex:

The usual way to go through all the elements of an array in order is by using the standard for loop

for(int i=0; i<myArray.length; i++)

{

System.out.println(myArray[i]);

}

But by using enhanced for loop is another way similar to the above

for(int arrayElement : array){

System.out.println(arrayElement);

}

Syntax

for(data_type variable : array | collection) {

// body of the for-each loop

}

Java Program

public class ForEachLoopDemo {
  public static void main(String[] args) {
    //declaring an array
    int arr[]= {10,20,30,40};

    //traversing the array with for-each loop
    for(int i:arr) {
      System.out.println(i);
    }		
  }
}

Screenshot

 

Program Output

10
20
30
40

 

The disadvantage of the Enhanced For loop is that it cannot traverse the elements in reverse order because here we do not have any option to skip any element, as it is not dependent on an index.

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version