Java Swap Two Local Values
Swapping local values is a useful trace exercise. Use a temporary variable so the original first value is not overwritten before it can be assigned elsewhere.
Understand the idea
The temporary value preserves one side of the exchange. This simple version avoids arithmetic swaps that can overflow and bitwise tricks that obscure intent. Swapping variables in a helper receiving primitive parameters does not change the caller’s own variables; return a result or operate on deliberately shared storage if that is the actual requirement.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
public static void main(String[] args) {
int morning = 9, evening = 4;
int previousMorning = morning;
morning = evening;
evening = previousMorning;
System.out.println(morning + ":" + evening);
}
}
Expected output
4:9The temporary receives nine, morning receives four, then evening receives the preserved nine. The order of these assignments matters. If morning were overwritten first without saving it, both variables could end up containing four and the original nine would be lost.
Check the official Java documentation for detailed contracts and supported options.