All Methods to Swap two numbers in Java

If you have started learning any programming language then the program to swap two numbers is one of the most important programs. In this blog, we will discuss all methods to swap two numbers in Java.
And if you do not know anything about java and have no IDE on your computer. First, read the Introduction and Installation of Java on Windows.
After knowing the basics, try to run some basic programs like Program to add two numbers in Java and Java Program to Calculate the Factorial of a number.
Method 1 – Swap two numbers in Java
In this program, we will take two variables and will use the third variable to store one variable at a time and will swap the numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.*; class SwappingNumbers { public static void main(String args[]) { int x, y, temp; System.out.println("Enter two numbers x and y"); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); System.out.println("Before Swapping x = "+x+"y = "+y); temp = x; x = y; y = temp; System.out.println("After Swapping x = "+x+"y = "+y); } } |
The Output of the Program – Enter two numbers x and y 15 25 Before Swapping x= 15 y= 25 After Swapping x=25 y =15
Method 2 – Without Using Extra Variable –
In this method, we will not use any third variable to store one variable and will do some manipulations on two variables.
This program is asked in various placement interviews and you should focus on this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.Scanner; class SwappingNumbers { public static void main(String args[]) { int a, b; System.out.println("Enter a and b"); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); 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); } } |
The output of the Program – Enter two numbers x and y 15 25 Before Swapping x= 15 y= 25 After Swapping x=25 y =15
For running the Program on an online Integrated Development Environment. Please check the link here.
Frequently Asked Questions –
Yes, swapping without using the third variable is the most important.
In java, the integer is of 32 bits and 4 bytes.
No, it is enough to know only two methods. Your purpose will be solved.