Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax of the enhanced for loop in Java?

Tags:

java

foreach

People also ask

Which of the following is the correct syntax of enhanced for loop?

for (Object obj : list); Enhanced For Each in arraylist (Java)

What is enhanced for loop explain with example?

The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse the array or collection elements.

What is the syntax a for loop?

Syntax of a For LoopThe initialization statement describes the starting point of the loop, where the loop variable is initialized with a starting value. A loop variable or counter is simply a variable that controls the flow of the loop. The test expression is the condition until when the loop is repeated.


Enhanced for loop:

for (String element : array) {

    // rest of code handling current element
}

Traditional for loop equivalent:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html


An enhanced for loop is just limiting the number of parameters inside the parenthesis.

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

Can be written as:

for (int myValue : myArray) {
    System.out.println(myValue);
}