Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Java) While-Loop condition

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.

like image 319
FaY Avatar asked Dec 23 '15 15:12

FaY


2 Answers

point != count++

This means compare point and current value of count for inequality and then increment count. So when count is 4 :

  1. it will be compared to point (unequal)
  2. count will become 5
  3. the while loop will run for one iteration
  4. it will be compared to point again (equal)
  5. the loop is terminated

the prefix increment operator ++count would increment before using the value in a comparison.

like image 171
Manos Nikolaidis Avatar answered Sep 20 '22 13:09

Manos Nikolaidis


because you are doing the comparison == before increment ++, if you want to fix it, change to ++count

like image 38
OPK Avatar answered Sep 21 '22 13:09

OPK