Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
int a=5;
int a=a++ ;
System.out.println(a);
the answer is 5 and not 6.can someone explain the logic of use and change operator

What I have tried:

i thought it was 6 but it seems to be 5
Posted
Updated 19-Mar-18 4:14am
Comments
Richard Deeming 19-Mar-18 10:08am    
The answer is "compiler error" - you can't have two variables with the same name.

Assuming the duplicated variable name is a typo in your question, the explanation is in the documentation:
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

Java
int a = 5;
int b = a++; // a = 6, b = 5
int c = ++a; // a = 7, c = 7
 
Share this answer
 
Comments
Maciej Los 19-Mar-18 10:21am    
5!
The compiler uses an internal temporary variable when processing the postfix increment. If you extend the code by using an additional variable like the compiler does you can see why it happens:
Java
int a = 5;
// int temp = a++;
// is the same as
int temp = a;
a = a + 1;
// Finally the value of the temp variable is assigned
a = temp;
 
Share this answer
 
Comments
Maciej Los 19-Mar-18 10:21am    
5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900