0

Why the num3 += must be before num2 += num1 to print 17 not 5 like in this example?

public class Program { public static void main(String[] args) { int num1 = 4; int num2 = 8; int num3 = 5; num2 += num1 += num3; System.out.println(num3); } }

30th Oct 2019, 9:36 PM
Daniel
Daniel - avatar
3 Answers
+ 1
num2 += num1 += num3; means num1 = num1 + num3; num2 = num2 + num1; So num3 is not changed. It is evaluated from right to left, because by assignation you want to assign the rigt part to the left „part“/variable.
30th Oct 2019, 9:49 PM
halfpair
+ 1
As halfpair stated, the statement is evaluated from left to right >> In this case, value of num3 remains unchanged, and displays value of 5 when printed However, adding/assigning... int num4 = num2 += num1 += num3; then printing num4... Would give you that value of 17 I know, over explained and long winded, but it helps slow learners like myself 😊
30th Oct 2019, 10:11 PM
will
will - avatar
+ 1
...and like myself, thanks:)
30th Oct 2019, 11:29 PM
Daniel
Daniel - avatar