import java.util.Scanner;
public class Swap
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x, y, t;
System.out.print("Enter the first variable: ");
x = input.nextInt();
System.out.print("Enter the second variable: ");
y = input.nextInt();
System.out.printf("Values before the swap -> x = %d, y = %d\n", x, y);
t = x;
x = y;
y = t;
System.out.printf("Values after the swap -> x = %d, y = %d\n", x, y);
}
}
Explanation:
Import the Scanner class
Create a Scanner object to be able to get input from the user
Declare the variables, x, y, and t - the variable t will be used as temporary variable that will hold the value of x
Ask the user to enter the first and second variables
Print the values before swap
Assign the value of x to the t
Assign the value of y to the x (Now, x will have the value of y)
Assign the value of the t to the y (Since t holds the value of x, y will have the value of x)
Print the values after the swap