Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment operator ++ [duplicate]

Possible Duplicate:
post increment operator java
What is x after “x = x++”?

Can somebody explain me the result of each one of the following small programs? :

public static void main(String[] args) {
    int a = 10;
    a = a++;
    System.out.println(a);
}

The result is: 10

Why not 11 since a should have been increased after the assignment? Is that the fact that it comes to different variables left and right of the opeartor = ?

The next one:

public static void main(String[] args) {
    int a = 10;
    a = ++a;
    System.out.println(a);
}

The result is: 11

Comprehensible, but the compiler presents the warning: "The assignment to variable a has no effect". The result dissents though.

Update:

I do not modify my original question but I add this comment to clarify that now I catch the meaning of the warning. That is, even without the assignment (by a plain statement ++a) the result would be the same (11).

like image 451
arjacsoh Avatar asked Jan 22 '26 11:01

arjacsoh


1 Answers

The value of a++ is a. ++ has higher precedence than =. So:

  1. The value of a is taken.
  2. a is incremented.
  3. The value as at (1) is stored into a.

So the value of a doesn't change.

You can figure out yourself what happens in the second case.

like image 74
user207421 Avatar answered Jan 25 '26 01:01

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!