How to swap/interchange two numbers in Java

In this example I'll show you two ways to swap the integer numbers.

import java.util.Scanner;

class SwapNumbers {
    public static void main(String args[]) {
        int x, y;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter x");

        x = in.nextInt();
        System.out.println("Enter y");
        y = in.nextInt();

        System.out.println("Before Swapping\nx = " + x + "\ny = " + y);

        x = x + y;
        y = x - y;
        x = x - y;

        // This is the second way to swap between two numbers
        /*
         * int temp = x; x = y; y = temp;
         */

        System.out.println("After Swapping\nx = " + x + "\ny = " + y);
    }
}


Output:

Enter x
10
Enter y
20
Before Swapping
x = 10
y = 20
After Swapping
x = 20
y = 10

2 comments: