This week's book giveaway is in the Reactive Progamming forum.
We're giving away four copies of Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams and have Adam Davis on-line!
See this thread for details.
Win a copy of Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams this week in the Reactive Progamming forum!
    Bookmark Topic Watch 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar
  • Likes 3
  • Mark post as helpful
  • send pies
  • Report post to moderator
Why does this code produce the output "0" instead of "1"?





Let's take a close look at what the line "i = i++;" does:


  • "i++" is evaluated. The value of "i++" is the value of i before the increment happens.
  • As part of the evaluation of "i++", i is incremented by one. Now i has the value of 1;
  • The assignment is executed. i is assigned the value of "i++", which is the value of i before the increment - that is, 0.


  • That is, "i = i++" roughly translates to



    With other words, it is a common misconception that the increment is happening last. The increment is executed immediately when the expression gets evaluated, and the value before the increment is remembered for future use inside the same statement.

    Solution:

    You don't need the assignment at all, just use



    Reason:

    The post-increment operator increments the value of your integer "i" after the execution of your "System.out..." statement so use "++i" (pre-increment operator)..




    See also

  • https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.14.2
  • https://coderanch.com/t/244938/java-programmer-SCJP/certification/post-increment-confusion
  • http://web.archive.org/web/20070305125534/http://radio.javaranch.com/corey/2004/06/03/1086277171000.html

  •  
    This tiny ad is wafer thin:
    Java file APIs (DOC, XLS, PDF, and many more)
    https://products.aspose.com/total/java
      Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!