jojuk
jojuk

Reputation: 127

Java operands usage

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

Upvotes: 1

Views: 78

Answers (4)

thegrinner
thegrinner

Reputation: 12243

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).

Upvotes: 2

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

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);

Upvotes: 1

Darius X.
Darius X.

Reputation: 2937

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

Upvotes: 1

ford prefect
ford prefect

Reputation: 7388

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?

Upvotes: 1

Related Questions