Language basicseasy0-2 years

A beginner writes `x = y; y = x;` expecting to swap two variables, and it does not work. What actually happens, and why does `=` behave this way instead of the way algebra taught them?

= in Java is not the equals sign from math — it's an instruction: evaluate the right side, then overwrite whatever is on the left with the result. x = y destroys whatever x used to hold; it doesn't remember it. So by the time y = x runs, x already equals y, and the line just copies y's own value back into itself — the original x is gone, not swapped. Swapping needs a third variable to hold one value while the other is overwritten.

The lesson behind it →