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

1 comment:

  1. SEO makes a good effect on business and help businessman to grow their business. It helps in making traffic in seo field.
    Top SEO Company in Bangalore
    cheapest seo packages
    Online Marketing Services in bangalore

    ReplyDelete