Swap two Values with third Variable
import java.util.Scanner;
class SwapValues {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int x, y, temp;
System.out.print("Enter a value for x: ");
x = reader.nextInt();
System.out.print("Enter a value for y: ");
y = reader.nextInt();
reader.close();
System.out.println("Before swapping:\nX: " + x + "\nY: " + y);
// swapping numbers
temp = x;
x = y;
y = temp;
System.out.print("After swapping:\nX: " + x + "\nY: " + y);
}
}
Output
Enter a value for x: 10
Enter a value for y: 20
Before swapping:
X: 10
Y: 20
After swapping:
X: 20
Y: 10
Swap two Values without third Variable
import java.util.Scanner;
class SwapValues {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int x, y;
System.out.print("Enter a value for x: ");
x = reader.nextInt();
System.out.print("Enter a value for y: ");
y = reader.nextInt();
reader.close();
System.out.println("Before swapping:\nX: " + x + "\nY: " + y);
// swapping numbers
x = x + y;
y = x - y;
x = x - y;
System.out.print("After swapping:\nX: " + x + "\nY: " + y);
}
}
Output
Enter a value for x: 4
Enter a value for y: 8
Before swapping:
X: 4
Y: 8
After swapping:
X: 8
Y: 4