Google News
logo
Java Program to Swap Two Numbers

Example 1 : Swap two numbers using temporary variable :

Program :
import java.util.Scanner;

public class SwapNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        System.out.println("Before swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);

        int temp = num1;
        num1 = num2;
        num2 = temp;

        System.out.println("After swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
    }
}
Output :
Enter the first number: 10
Enter the second number: 26
Before swapping:
num1 = 10
num2 = 26
After swapping:
num1 = 26
num2 = 10
In this program, we use the Scanner class to read two numbers input by the user. We then swap the values of the two numbers using a temporary variable called temp. Finally, we print out the values of the two numbers before and after swapping.

Example 2: Swap two numbers without using temporary variable :

Program :
import java.util.Scanner;

public class SwapNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        System.out.println("Before swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);

        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;

        System.out.println("After swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
    }
}
Output :
Enter the first number: 26
Enter the second number: 32
Before swapping:
num1 = 26
num2 = 32
After swapping:
num1 = 32
num2 = 26
In this program, we use the Scanner class to read two numbers input by the user. We then swap the values of the two numbers without using a temporary variable. This is done by adding the two numbers together and storing the result in the first variable.

We then subtract the second number from the first variable to get the value of the second variable. Finally, we subtract the second variable from the first variable to get the value of the first variable. This effectively swaps the values of the two variables.