Swap Two Numbers in Java
Swap the values of two variables using a temporary variable.
BeginnerModule 1: Basic Java ProgramsExample 3 of 20
swap-two-numbers.java
1public class Main {2 public static void main(String[] args) {3 int a = 5;4 int b = 10;56 System.out.println("Before swap: a = " + a + ", b = " + b);78 int temp = a;9 a = b;10 b = temp;1112 System.out.println("After swap: a = " + a + ", b = " + b);13 }14}
Output
Before swap: a = 5, b = 10 After swap: a = 10, b = 5
What's going on
temp = a, a = b, b = temp. Miss a step and both hold the same value.
Java has no a, b = b, a. People coming from Python look for it. It is not here.