Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does for-each loop works internally in JAVA?

Tags:

java

I was trying to find the working of for-each loop when I make a function call. Please see following code,

public static int [] returnArr()
{
    int [] a=new int [] {1,2,3,4,5};
    return a;
}

public static void main(String[] args)
{
    //Version 1
    for(int a : returnArr())
    {
        System.out.println(a);
    }

    //Version 2
    int [] myArr=returnArr();
    for(int a : myArr)
    {
        System.out.println(a);
    }
}

In version 1, I'm calling returnArr() method in for-each loop and in version 2, I'm explicitly calling returnArr() method and assigning it to an array and then iterating through it. Result is same for both the scenarios. I would like to know which is more efficient and why.

I thought version 2 will be more efficient, as I'm not calling method in every iteration. But to my surprise, when I debugged the code using version 1, I saw the method call happened only once!

Can anyone please explain how does it actually work? Which is more efficient/better when I code for complex objects?

like image 577
Abhishek Avatar asked Feb 09 '15 07:02

Abhishek


People also ask

How does forEach work internally in Java 8?

Simply put, the Javadoc of forEach states that it “performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.” And so, with forEach, we can iterate over a collection and perform a given action on each element, like any other Iterator.

How does the forEach version of the for loop work in Java?

How it works? The Java for-each loop traverses the array or collection until the last element. For each element, it stores the element in the variable and executes the body of the for-each loop.

How does the for loop works?

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.


1 Answers

The Java Language Specification shows the underlying compilation

Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement.

The enhanced for statement is equivalent to a basic for statement of the form:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

where Expression is the right hand side of the : in an enhanced for statement (your returnArr()). In both cases, it gets evaluated only once: in version 1, as part of the enhanced for statement; in version 2, because its result is assigned to a variable which is then used in the enhanced for statement.

like image 114
Sotirios Delimanolis Avatar answered Oct 11 '22 18:10

Sotirios Delimanolis