int b = 2;
c= b++;
System.out.Println("C :"+c+"B"+b);
c will be 2 and b will be 3.
int b = 2;
b= b++;
System.out.Println("B:"+b);
Here I wonder what is getting incremented. and where does that incremented value goes.
int b = 2;
c= b++;
System.out.Println("C :"+c+"B"+b);
c will be 2 and b will be 3.
int b = 2;
b= b++;
System.out.Println("B:"+b);
Here I wonder what is getting incremented. and where does that incremented value goes.
Well this is tricky. Let's take a look what the post-increment operator does. The JLS states:
The value of the postfix increment expression is the value of the variable before the new value is stored.
So in your code b++ has the value 2, independently from the incrementation of b.
If you do an assignment, the right-hand side expression is evaluated first and then its value is stored into the variable.
It's straightforward if you do c = b++. The expression b++ has the value 2 which gets assigned to c. After that statement b has the incremented value 3. But that's a little simplified. What actually happens is, that b++ is evaluated first, meaning b is incremented before the assignment takes place, not after.
So what happens when you do b = b++? Well, it's just the same: The b++ is evaluated first, meaning b is incremented. After that the assignment takes place and the value of the expression b++ is assigned to b. This is still 2 and overwrites your incremented b.
Fun fact: If I enter your second code in my Eclipse, Findbugs issues the following warning:
Bug: Overwritten increment in MyClass.main(String[])
The code performs an increment operation (e.g., i++) and then immediately overwrites it. For example, i = i++ immediately overwrites the incremented value with the original value.
I guess you just don't get what happens here:
int b = 2;
b= b++;
System.out.println("B:"+b);
And more specifically, this line:
b = b++;
The compiler sees that this is an assignment statement, so it tries to evaluate the expression on the right first:
b++
Since ++ here is a post increment operator, the expression just evaluates to b, i.e. 2. Immediately after the evaluation, b is incremented to 3.
We're not done yet! This is an assignment statement remember? Now that the right side is evaluated, the expression now looks like this:
b = 2;
Great! Now b is assigned the value of 2.
int b=2
b = b++
Is like you are running this code
int b = 2;
int temp = b;
b = b + 1;
b = temp;