• Post Reply Bookmark Topic Watch Topic
  • New Topic

Core Java: auto-increments  RSS feed

 
Hardik Patel p
Ranch Hand
Posts: 40
Hibernate Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

System.out.println(a++ +" "+ ++a);
System.out.println(++b +" "+ b++);

Output
0 2
1 1

Please Explain this.

Thank
hardik

 
Tim Cooke
Marshal
Posts: 4048
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The CodeRanch FAQ article might help: PostIncrementOperatorAndAssignment
 
Hardik Patel p
Ranch Hand
Posts: 40
Hibernate Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for reply but I cant understood the description which are in your link.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those are not called autoincrements. That is a databases term.

The problem is that there are two values in i++ and ++i. There is the value of i and the value of the whole expression.

In the case of ++i, it is easy to understand. Both values are the same, equals to the “new” value of i.What you don't realise is that you cannot get the value of i directly. Only the value of the whole expression.

It is harder to understand with i++ because the value of the whole expression i++ is equals to the “old” value of i. SoLet's look at the code you showed earlierIt is the values shown after i++ and ++ which you print. You never see the value of i directly. Not until later.

The moral of the story is: using preincrement and postincrement inside other expressions can be confusing and you should avoid it unless you understand it fully.
 
Hardik Patel p
Ranch Hand
Posts: 40
Hibernate Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Campbell Ritchie

You gave super explanation.

Thank you
Hardik
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!