title: For loop optimizing in Java
body: <p>I have read the below code today in Java Tutorials.</p>
  
  <pre><code>StackTraceElement elements[] = e.getStackTrace();
  for (int i = 0, n = elements.length; i &lt; n; i++) {
      logger.log(Level.WARNING, elements[i].getMethodName());
  }
  </code></pre>
  
  <p>I might write the code like as following as a newbie.</p>
  
  <pre><code>StackTraceElement elements[] = e.getStackTrace();
  
  for (int i = 0; i &lt; elements.length; i++) {
      logger.log(Level.WARNING, elements[i].getMethodName());
  }
  </code></pre>
  
  <p>Or like as following.</p>
  
  <pre><code>int n = elements.length;
  for (int i = 0; i &lt; n; i++) {
      logger.log(Level.WARNING, elements[i].getMethodName());
  }
  </code></pre>
  
  <p>I just want to ask what's the difference between them? Are there other more excellent approaches to optimize the for loop in Java?</p>