Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for Loop evaluation

Tags:

java

loops

I want to know if the condition evaluation is executed in for and while loops in Java every time the loop cycle finishes.

Example:

int[] tenBig = new int[]{1,2,3,4,5,6,7,8,9,10};

for(int index = 0;index < tenBig.length;index++){
    System.out.println("Value at index: "+tenBig[index]);
}

Will the index < tenBig.length be execute every time the loop cycle finishes?

Assumption and experience tells me yes.

I know that in this example the tenBig.length is a constant, so there won't be a performance impact.

But lets assume that the condition operation takes long in a different case. I know the logical thing to do then is to assign the tenBig.length to a variable.

Still I want to be sure that its evaluated every time.

like image 615
Koekiebox Avatar asked Oct 07 '10 12:10

Koekiebox


People also ask

How do I check for loop conditions?

Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements. Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.

What is evaluated only once when the for loop starts?

The initialization is an expression that initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false , the loop terminates.

What are the 3 types of loops in Java?

Looping in Java These three looping statements are called for, while, and do… while statements. The for and while statements perform the repetition declared in their body zero or more times. If the loop continuation condition is false, it stops execution.


1 Answers

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.

like image 66
Jon Skeet Avatar answered Oct 22 '22 11:10

Jon Skeet