Java Program to swap two numbers without using third variable
In this program, You will learn how to swap two numbers without using third variable in java.
Before swap: 10 20
After swap: 20 10
Example: How to swap two numbers without using third variable in java.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
int a,b;
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers:");
a = sc.nextInt();
b = sc.nextInt();
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping a is:"+a);
System.out.println("After swapping b is:"+b);
}
}
Output:
Enter two numbers:10 20
After swapping a is:20
After swapping b is:10