Java for Loop evaluation

Viewed 11683

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.

9 Answers

Short Answer: the condition is evaluated every time so:

WRONG:

for (int i = 0; i < Math.random() * 50; i++) {
    System.out.println("" + i);
}

CORRECT:

double random = Math.random();
for (int i = 0; i < random * 50; i++) {
    System.out.println("" + i);
}
Related