• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

dose increment operator works differently at different places?

 
Ranch Hand
Posts: 401
Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 326
Android Mac OS X Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is no such thing as "the increment operator". There are two increment operators.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic