What happens to
b
?
Nothing happens to b
.
When you do
a = b;
you’re copying the value stored in b
and putting it in a
. (You’re not making a
an alias of b
.)
When you then do a += 1;
you’re changing the value stored in a
(and the value stored in b
remains unchanged).
You can verify this by printing the final values after your code snippet:
System.out.println(a); // prints 8
System.out.println(b); // prints 7
What happens if you change the variable
b
, or what if you changea
. What does the order have to do with anything.
a
and b
are two independent variables and changing one will never affect the other.
The order matters since when you do a = b
the value of b
is copied into a
and whatever a
stored before is discarded. If you had done a += 1
prior to a = b
, then a
would have been restored to 7 again.
2
solved If a = b, what happens if each value changes respectively?