Java for Loop evaluation

Yes, it will logically evaluate the whole of the middle operand on every iteration of the loop. In cases where the JIT knows better, of course, it can do clever things (even potentially removing the array bounds check within the loop, based on the loop conditions).

Note that for types that the JIT doesn't know about, it may not be able to optimize specifically like this - but may still inline things like fetching the size() of an ArrayList<T>.

Finally, I generally prefer the enhanced for loop for readability:

for (int value : tenBig) {
    ...
}

Of course, that's assuming you don't need the index for other reasons.


Yes, the expression must be evaluated for each iteration of the loop to determine whether to stay inside the loop or continue program execution.

Remember, you can do things like this:

for(int a = 0, z = 26; a < z; a++, z--){
    // Do some work
}

In that case, both sides of the expression will change and must be evaluated for each iteration.

And you're right, if you have calculations in the for loop condition that can be moved out to a separate variable, you should do that:

for(int i = 0; i < ((someCount / 2) * 21.6); i++){
}

Could easily be:

int maxVal = (someCount / 2) * 21.6;

for(int i=0; i < maxVal; i++){
{

Yes. Specifically, the condition part is executed before each loop body. So it's entirely possible that you never enter the body of the loop at all.

So taking your example:

for(int index = 0;index < tenBig.length;index++) {
    /* ...body... */
}

This is the logical (not literal) equivalent:

int index = 0;
while (index < tenBig.length) { // happens on each loop
    /* ...body... */

    index++;
}

Tags:

Java

Loops