• 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

Java Postfix Operator

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all ,

why is the result of following code = 5 ? while ++i gives the result as 6 !

int i = 5;
i = i++;
System.out.println(i);

Regards
SONAL
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here you go...
 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sonal,

int i=5;
i=i++;
System.out.println(i);

the value of i will be 5 only.
In the line i=i++; means i=5 then increment by 1;
so i will again assigned a value of 5,
but i will be incremented by 1 after the assignment but it will not be stored anywhere and it will be lost.
But if u say
int i=5;
i++;
System.out.println(i);
now i will print 6.
Here in the line i++; the var i will be incremented and will be stored in i.

And if u change
i=i++; to i=++i;
i=++5;
Here the value is incremented before(preincrement) and then is assigned to i, so this prints 6.

Hope this helps you.
 
reply
    Bookmark Topic Watch Topic
  • New Topic