How to Swap Variables in Java: Complete Guide
There are two ways to achieve the exchange of values between two variables: using a third variable or through mathematical operations. Below are examples of both methods.
Option 1:
Method 1: Swap values using a third variable.
int a = 5;
int b = 10;
int temp;
System.out.println("Before swapping: a = " + a + ", b = " + b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping: a = " + a + ", b = " + b);
Option:
Method 2: Exchange values through mathematical operations.
int a = 5;
int b = 10;
System.out.println("Before swapping: a = " + a + ", b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping: a = " + a + ", b = " + b);
You can choose either of the above two methods to swap the values of two variables according to your preference.