Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java looping example with increment operator

I have a little doubt here,i have a code as

 int num=0;
 for(int i=0;i<5;i++){
   num=num++;
   System.out.print(num);
 }

why is the output always 00000

like image 710
Hmahwish Avatar asked Dec 01 '22 20:12

Hmahwish


1 Answers

The ++ operator increments num last, so when num is 0, you are setting it to 0 again.

It has to deal with how the ++ operator increments num, and what num is truly pointing to. To avoid it, just use num++

Interestingly enough, num=++num will correctly increment and assign the incremented value, though the whole purpose of the ++ operator, either pre or post, is that it modifies the value directly. You do not have to re-assign it back to the value.

like image 197
hotforfeature Avatar answered Dec 04 '22 10:12

hotforfeature