Swap two numbers using third variable
Swapping is the exchanging the values of variables. For example, if a=25 and b=37 then after swapping the values are a=37 and b=25. In this program, we swap the two variables using the third variable. The third variable is a temporary variable which is used stored a value temporary. First we save the value of 'a' in 'temp', then b's value is store in 'a' and finally store the value of 'temp' in 'b'.
PROGRAM
PROGRAM
class SwappingUsingThirdVar {
public static void main(String[] args) {
int a = 10, b=20, 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);
}
}
OUTPUT
C:\>javac SwappingUsingThirdVar.java C:\>java SwappingUsingThirdVar Before swapping : a = 10 b = 20 After swapping : a = 20 b = 10