title: Will the Java compiler optimize out String.length() in a for-loop's condition?
body: <p>Consider the following Java code fragment:</p>
  
  <pre><code>String buffer = "...";
  for (int i = 0; i &lt; buffer.length(); i++)
  {
      System.out.println(buffer.charAt(i));
  }
  </code></pre>
  
  <p>Since <code>String</code> is immutable and <code>buffer</code> is not reassigned within the loop, will the Java compiler be smart enough to optimize away the <code>buffer.length()</code> call in the for loop's condition? For example, would it emit byte code equivalent to the following, where <code>buffer.length()</code> is assigned to a variable, and that variable is used in the loop condition? I have read that some languages like C# do this type of optimization.</p>
  
  <pre><code>String buffer = "...";
  int length = buffer.length();
  for (int i = 0; i &lt; length; i++)
  {
      System.out.println(buffer.charAt(i));
  }
  </code></pre>