int a = 3;
int b = (a=2)*a;
int c = b * (b=5);
System.out.println("a=" + a + " b=" + b + " c=" + c);
Can someone explain me why the output is:
a=2 b=5 c=20
instead of
a=2 b=4 c=20
Because assignment is an operator which returns the new value it set and, while it's normally last in precedence, the parentheses move it up before the non-parenthetical operators. Think of it like this:
a is set to 3.a is set to 2, returning 2. That is then multiplied by the new value of a, which is 2, setting b to 4.b) is multiplied by the result of b=5, which is 5. b is now 5, and c is set to the 4x5 value (20).You have reassigned b to a 5 in the second statement. As a result b will be 5 until it is assigned again. What part of this is confusing you?
You are assigning 5 to b, in the third line. So, that's what it contains.
b=5 inside of an expression and sort of assumed