Java Program to swap two numbers without using third variable


In this program, You will learn how to swap two numbers without using third variable in Java.


Before swap: 10 20

After swap: 20 10


Example: How to swap two numbers without using third variable in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int a,b;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Two Numbers :");
        a = sc.nextInt();
        b = sc.nextInt();

        a = a + b;
        b = a - b;
        a = a - b;

        System.out.println("\nAfter Swapping a is :"+a);
        System.out.println("After Swapping b is :"+b);

    }
}

Output:

Enter Two Numbers :10 20
After Swapping a is :20
After Swapping b is :10