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);
}
}
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
// Java program to swap two strings without using a temporary
// variable.
import java.util.*;
class Swap
{
public static void main(String args[])
{
// Declare two strings
String a = "Hello";
String b = "World";
// Print String before swapping
System.out.println("Strings before swap: a = " +
a + " and b = "+b);
// append 2nd string to 1st
a = a + b;
// store initial string a in string b
b = a.substring(0,a.length()-b.length());
// store initial string b in string a
a = a.substring(b.length());
// print String after swapping
System.out.println("Strings after swap: a = " +
a + " and b = " + b);
}
}
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);
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);
}
}