• 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

a problem of unary operator: ++

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
please see the code:
int i=0;
i=i++;
i=i++;
i=i++;
System.out.println("i="+i); // print out i=0;
i++;
System.out.println("i="+i); // print out i=1;
I am doubled why the i is 0. what is the different between i=i++ and i++?
Anybody help me? thank you.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!
The first time I encountered this in Java, I was also very surprised because, i=i++ in C (in my compiler) gives a value of 1 to i.
However, in Java what happens I think is this -->
saying i++ or ++i on its own has no problem. Both of them would increment i.
However, saying i++ as part of the expression is different. What happens is that i++ is evaluated giving a value of 0 (since it is post-increment), which for some some reason is stored in a temporary variable. Next, increment is performed, setting i to 1. And then lastly, the assignment is performed, fetching the value (that was saved) which was 0 and storing it in i. Thus final value is still 0. If i is not used in the left hand side, then it is not so confusing -->

int x = 0;
int i = 10;
x = i++; // makes x 10 and i 11
I hope this helps.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic