Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+22 votes

int x;
x = 3;
int y = x;
x = 5;
y = y + x;
System.out.println(x);
System.out.println(y);

The output is:
5
8

asked in CSC211_Winter2018 by (8 points)

1 Answer

+10 votes

This is because of the order in which java reads the code. So, y = x when x = 3. After this line x is then changed to 5; however, y is still 3 because that is what x was when y = x.

If the statement "y = x;" would have come after "x = 5;" then y would equal 5.

In other words, the statement "y = x;" in java is not the same as saying y will always be equal to x. y is merely set to whatever value x currently holds.

answered by (8 points)
+5

Yes, it might help if you read "=" as "is assigned the value of", instead of "equals".

+4

Thank you, it helps a lot !!

...