Q:

Java: How many times is arr.length called in a for-loop?

If arr is an array of size 10, in the following code block, how many times is arr.length accessed?
for (int i = 0; i < arr.length; ++i);

Once? Or every time it loops?
Thanks everyone! Here's what I ended up doing:
final int len = arr.length;
for (int i = 0; i < len; ++i);

A:

Eleven times....
10 times, the statement i < arr.length evaluates to true.
1 time it evalutes to false and the loop ends.

A:

Since you are permitted to change arr within the loop, it's usually evaluated every time the loop termination condition is evaluated.
An optimising compiler (or JIT) may recognise that you don't change arr within the loop, and then only evaluate arr.length once.

A:

Without compiler optimizations, 11 times (one per iteration + one after the last iteration). But the compiler will optimize the thing so there's going to be only one access. But what I said assumes your for loop has a body:
for (int i = 0; i < arr.length; ++i) {
   ...
}

In your case the loop has no body:
for (int i = 0; i < arr.length; ++i);

so it's a no-op and the compiler is going to remove it. So in that specific case you'll access the field zero times.
But don't rely on compiler optimizations because you don't really know what it does.

