The code:
int r=1;
System.out.println(r + (r=2));
The output is: 3. But I expected 4 because I thought the code inside the parentheses is executed first?
The code:
int r=1;
System.out.println(r + (r=2));
The output is: 3. But I expected 4 because I thought the code inside the parentheses is executed first?
The value of statement
r=2
is 2. Nested expressions between brackets are processed first though.For instance:
Output:
Why? Because
r = 2 + 1
returns3
.Same as:
Output still
6
because(2 + 1)
is evaluated before multiplication.Use this if you want 4
Official Docs on Operators says
So
+
is evaluatedleft-to-right
,where as assignment operators are evaluatedright to left.
Associativity of
+
is left-to-right , and the value of the expression(r=2)
is2
.Refer JLS 15.7
it's like this