Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

operator precedence

 
uzma Akbar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for (int i = 0; i++ < 2
System.out.print(i);


Can anyone explain that why the output is 12. Why the 2 get printed as it should be rejected at the check and also ++ operator has higher precedence as compared to < so isn't that i is incremented first and then checked for the value.?

Please help as it sounds quite easy but sometimes easy ones are tricky
Thanks
Uzma
 
Philippe Saint-Just
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i++ increments i after it has been evaluated.
++i increments it before it's evaluated.
 
Naresh Gunda
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for (int i = 0; i++ < 2
System.out.print(i);

i=0
i<2 true , postfix operator, i value becomes 1, s.o.p executed 1 is priented

i=1
i<2 true , postfix operator, i value becomes 2, s.o.p executed 2 is priented

i=2
i<2 false
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic