In the Java programming language, are the following two loops equivalent for any expression exp and and loop body body? Only side condition should be that the freshly introduced variable b does not appear elsewhere in the method (and does not hide an attribute, …)
while(exp) {
body
}
and
for(boolean b = exp; b; b = exp) {
body
}
Yes, under those assumptions.
The
forconstruct checks the condition before the first iteration, so ifbisfalse, then the body will never be executed. To put it another way, in your code example,expis evaluated precisely once before each loop iteration, and the result used to decide whether to execute that iteration or not.But why would you want to write code like this?