Swapping of two numbers in Java

Created with Sketch.

 

Swapping of two numbers in Java

Java program to swap two numbers with and without using an extra variable. Swapping is frequently used in sorting techniques such as bubble sort, quick sort, and other algorithms.

Swapping program in Java

import java.util.Scanner;

class SwapNumbers
{
public static void main(String args[])
{
int x, y, t;
System.out.println(“Enter two numbers (x & y)”);
Scanner in = new Scanner(System.in);

x = in.nextInt();
y = in.nextInt();

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

t = x;
x = y;
y = t;

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

Output of program:
Java program to swap numbers output

Swapping without an extra variable

import java.util.Scanner;

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

x = in.nextInt();
y = in.nextInt();

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

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *