xxxxxxxxxx
public class SwapNumbers {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
// Swapping logic
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
xxxxxxxxxx
int a=4;
int b=5;
a=a+b; // 4 + 5 = 9
b=a-b; // 9 - 5 = 4
a=a-b; // 9 - 4 = 5
xxxxxxxxxx
int a = 5;
int b = 6;
int temp = a;
a = b;
b = temp;
// now a is 6 and b is 5.
xxxxxxxxxx
int a, b, c;
a = 5;
b = 3;
System.out.println("Before SWAP a = " + a + ", b = " + b);
c = a;
a = b;
b = c;
System.out.println("After SWAP a = " + a + ", b = " + b);
java program to swap 2 numbers without using 3rd variable
xxxxxxxxxx
import java.util.*;
class Swap
{
public static void main(String a[])
{
System.out.println("Enter the value of x and y");
Scanner sc = new Scanner(System.in);
/*Define variables*/
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("before swapping numbers: "+x +" "+ y);
/*Swapping*/
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping: "+x +" " + y);
}
}