title: How does for-each loop works internally in JAVA?
body: <p>I was trying to find the working of for-each loop when I make a function call. Please see following code,</p>
  
  <pre><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);
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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! </p>
  
  <p>Can anyone please explain <strong>how does it actually work</strong>? <strong>Which is more efficient/better</strong> when I code for complex objects?</p>