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.
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.println("After swap x is:" + x);
System.out.println("After swap y is:" + y);
}
}
Output:
Enter two numbers:10 20
After swap x is:20
After swap y is:10