1
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
jojuk
  • 127
  • 1
  • 3
  • 14

4 Answers4

2

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:

  1. a is set to 3.
  2. a is set to 2, returning 2. That is then multiplied by the new value of a, which is 2, setting b to 4.
  3. 4 (old 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).
Community
  • 1
  • 1
thegrinner
  • 11,546
  • 5
  • 41
  • 64
1

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?

ford prefect
  • 7,096
  • 11
  • 56
  • 83
  • Oh now I get it. I forgot about the second assignment. Such a stupid question I've asked.. – jojuk Nov 11 '13 at 15:46
1

You are assigning 5 to b, in the third line. So, that's what it contains.

Darius X.
  • 2,886
  • 4
  • 24
  • 51
1

b is 5 because of this (b=5);

a is 2 because of this (a=2)

c is 20 because of this 4 * (b=5);

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64