Swapping two numbers program in Java
What is Swapping
In programming, "swapping" refers to the act of exchanging the values of two variables. This is often done as part of an algorithm or process that requires the values of the variables to be exchanged in some way.
For example, you might want to swap the values of two variables in order to sort them in ascending or descending order. Or you might want to swap the values of two variables in order to perform some other operation on them.
Swapping the values of two variables typically involves using a temporary variable to store the value of one of the variables while the values are being exchanged. This is because most programming languages do not allow you to directly exchange the values of two variables in a single operation.
Here is a simple program in Java that swaps the values of two variables:
Method 1:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of a: ");
int a = scanner.nextInt();
System.out.print("Enter the value of b: ");
int b = scanner.nextInt();
System.out.println("Before swapping, the value of a is " + a + " and the value of b is " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After swapping, the value of a is " + a + " and the value of b is " + b);
}
}
This program declares two integer variables
a
and b
, and assigns them the values taking user input. It then swaps the values of a
and b
using a temporary variable temp
. Finally, it prints the values of a
and b
after the swap to confirm that the values have been swapped.Method 2:
To run the program, you will need to compile it using a Java compiler and then run the resulting class file.