• 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

Increment operator

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class counter{
int i=10;
public static void main(String args[]){
counter c1 = new counter();
c1.i=c1.i++;
System.out.println(c1.i);
}}
When I checked o/p is 10. I thought it first assigns the value to the variable and then increments , if this is the case 10 should have been put in i and the same variable should be incremented to show the result as 11.
 
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!
in this assignment right side is still 10.
if you want get 11 change to
c1.i=++c1.i;
Cheers
[This message has been edited by Vladimir Kositsky (edited December 12, 2000).]
 
Meena Rao
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the reply.
Yeah, I have tried with ++c1.i. But, what I wanted to know is why the c1.i++ does not increment the value of i and store it in i.
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Meena,
This is because the when you do
c1.i=c1.i++;

The value 10 is first assigned to to i and then after it is incremented, hence the value still remains 10.
whereas if you do ( as per Vladimir )
c1.i=++c1.i;
i is first incremneted and then assigned. Hence the new value is 11
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
c.i=c.i++;
Breaking this down, what it really does is:
int x = c.i;
c.i = c.i + 1;
c.i = x;
if c.i had a value of 10, it will still have the value 10. Notice that c.i was 11 but got written over by the original value.
Post increment returns the starting value and then increments by 1. Pre increment increments by 1 and then returns the final value.
 
Acetylsalicylic acid is aspirin. This could be handy too:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic