I'm just starting to learn Java in school and now I'm stuck.
public static void main(String[] args) {
int count = 0;
int point = 5;
while(point != count++){
System.out.println(count);
}
Console : 1 2 3 4 5
Why is number "5" still printed ? Isn't this while loop supposed to run only if point != count + 1 ? Then it should stop when 5 = 5, isn't it (and "5" wouldn't be printed) ?
Thank a lot.
point != count++
This means compare point
and current value of count
for inequality and then increment count
. So when count
is 4 :
point
(unequal)count
will become 5point
again (equal)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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With