1.5K
In this program, you’ll learn to make Java Program to Swap Two Numbers using temporary variable and well as without using temporary variable.
Swap two numbers using temporary variable
public class SwapNumbers {
public static void main(String[] args) {
float first = 1.22f, second = 2.45f;
System.out.println("Before swap:");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
// Value of first is assigned to temporary
float temporary = first;
// Value of second is assigned to first
first = second;
// Value of temporary (which contains the initial value of first) is assigned to second
second = temporary;
System.out.println("After swap:");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
What You get as Output , After running the program
Before swap:
First number = 1.22
Second number = 2.45
After swap:
First number = 2.45
Second number = 1.22
Swap two numbers without using temporary variable
public class SwapNumbers {
public static void main(String[] args) {
float first = 12.0f, second = 24.5f;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
first = first - second;
second = first + second;
first = second - first;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
What You get as Output , After running the program
--Before swap--
First number = 12.0
Second number = 24.5
--After swap--
First number = 24.5
Second number = 12.0