(Java) While-Loop condition
point != count++
This means compare point
and current value of count
for inequality and then increment count
. So when count
is 4 :
- it will be compared to
point
(unequal) count
will become 5- the while loop will run for one iteration
- it will be compared to
point
again (equal) - the loop is terminated
the prefix increment operator ++count
would increment before using the value in a comparison.
because you are doing the comparison ==
before increment ++
, if you want to fix it, change to ++count
I agree with the prior answers on the details of your problem assuming the current structure. However, it would be better to follow the advice in the Java Language Specification, 15.7. Evaluation Order, which says
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.
The count++
has a side effect and is not the outermost operation in its statement. That is ultimately the cause of your difficulty reasoning about your code. It would be clearer if you did the increment inside the loop, either before or after the println
call.
The key to reasoning about programs is to have simple, clear invariants. Here is an alternative version of your program, over-commented for exposition.
public class Test {
public static void main(String[] args) {
/*
* Initialize count to the first value that will be used in the loop
* payload.
*/
int count = 1;
int point = 5;
while (count < point) {
/*
* Loop payload - executed with the same value of count as the test above
*/
System.out.println(count);
/*
* Increment count for the next test and, if the test passes, payload
* execution.
*/
count++;
}
}
}
I am using "payload" to mean the code for which the loop exists, in this case just the println
call.
My invariants are:
- The value of
count
on arrival at the test is both the value that will be tested and, if it passes the test, the value that will be used in the payload. - After execution of the loop body, the value of
count
has been incremented by one.
The loop contains two operations with side effects, the call to println
and the count
increment. Each of them is the outermost operation in its statement.