Java Program to swap two numbers in a single line


In this program, You will learn how to swap two numbers in a single line in Java.


Before swap: 10 20

After swap: 20 10


Example: How to swap two numbers in a single line in Java

Run it Now
import java.util.Scanner;

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

        int x, y;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Two Numbers :");
        x = sc.nextInt();
        y = sc.nextInt();

        x = x ^ y ^ (y = x);

        System.out.print("\nAfter Swap x is :" + x);
        System.out.print("\nAfter Swap y is :" + y);

    }
}

Output:

Enter Two Numbers :10 20
After Swap x is :20
After Swap y is :10