Win a copy of Secure Financial Transactions with Ansible, Terraform, and OpenSCAP this week in the Cloud/Virtualization forum!
  • 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
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

Post Increment

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
4. int i = 0;
5. i = i++;
6. System.out.println(i);
The above code prints 0. On line 5 the assignment of 0 is made but after that i does not appear to be incremented. Why?
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
check out these two threads -- they might help a bit:
how is this possible???
Strange behaviour of asignment operator
 
stable boy
Posts: 425
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In a nutshell a copy is taking at line 5 from the variable i. The copy is incremented and then the orginal value (=0) is assigned to i again.
The result is 0.
Many times this has been discussed here I believe, have a look in https://coderanch.com/t/241731/java-programmer-SCJP/certification/Assignment
This explains what is going on in the bytecode
Thomas De Vos
http://www.javacertificate.com
 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The postfix operator is evaluated after the assignment.
So i is assigned its old value and then incremented. This incremented value is lost.
Try this code:
 
I've read about this kind of thing at the checkout counter. That's where I met this tiny ad:
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic