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

4 Answers 4

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).
Sign up to request clarification or add additional context in comments.

Comments

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?

1 Comment

Oh now I get it. I forgot about the second assignment. Such a stupid question I've asked..
1

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

2 Comments

@Cruncher I don't think it's assignment as comparison just a misunderstanding of scope
@inquisitiveIdiot Oh, I didn't even look that close. I just saw b=5 inside of an expression and sort of assumed
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.