Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dose increment operator works differently at different places?

 
Rauhl Roy
Ranch Hand
Posts: 401
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



May i know why Line number 5 and 7 are giving incremented result but not line number 8 and 9.

why the result of increment (@ 8 and 9 lines) is not being directly reflecting on the output.
 
Ove Lindström
Ranch Hand
Posts: 326
Android Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is the way Java reads your code.

Line 4: the variable i, increase it
Line 5: print variable i.
Line 6, increase variable i.
Line 7: print variable i.
Line 8: with i, increase it then print it
Line 9: print variable i, then increase it.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15484
43
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The postfix increment operator, where the ++ is after the variable name, will return the old value of the variable. So if i = 5, and you print the value of i++, you will get 5 (and i is incremented to the value 6).

The prefix increment operator, where the ++ is before the variable name, will return the new value of the variable. So if i = 5, and you print the value of ++i, you will get 6 (and i is incremented to the value 6).
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is why after running this code:



i will still be 3. the i++ says 'return the old value, but increase it by 1. So we set i to 4 (due to the ++), we return the old value of 3, and then assign 3 to i.

Therefore, never never never write line 2.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50217
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no such thing as "the increment operator". There are two increment operators.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic