I want to know if the condition evaluation is executed in for
and while
loops in Java every time the loop cycle finishes.
Example:
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.lenght;index++) {
/* ...body... */
}
This is the logical (not literal) equivalent:
int index = 0;
while (index < tenBig.length) { // happens on each loop
/* ...body... */
index++;
}
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);
}
Do you ask wether the compiler caches the tenBig.length value since he knows it won't change during the loop? Or you ask wether the compiler automatically knows that the whole expression index < tenBig.length does not need to be evaluated for the next 9 times?