This code demonstrates swapping two integer values, x
and y
. It uses a Scanner object to prompt the user to input the values for x
and y
. The values are then stored in the respective variables. The code then outputs the values of x
and y
before swapping, then swaps the values by storing x
in a temporary variable temp
, then assigning y
to x
and temp
to y
. Finally, the code outputs the values of x
and y
after swapping.
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);
}
}
Enter a value for x: 10
Enter a value for y: 20
Before swapping:
X: 10
Y: 20
After swapping:
X: 20
Y: 10
This is a Java program that swaps the values of two variables, x
and y
. The program uses a Scanner object reader
to read the values of x
and y
from the user’s input.
First, the program prints out a message asking the user to enter a value for x
, and then reads the user’s input using reader.nextInt()
. It then prints out another message asking the user to enter a value for y
, and reads the user’s input for y
in the same manner.
Next, the program prints out a message showing the values of x
and y
before swapping them. The actual swapping of values is done in the next few lines:
x = x + y;
y = x - y;
x = x - y;
Here, the values of x
and y
are swapped using arithmetic operations without using a temporary variable.
Finally, the program prints out a message showing the values of x
and y
after the swap.
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);
}
}
Enter a value for x: 4
Enter a value for y: 8
Before swapping:
X: 4
Y: 8
After swapping:
X: 8
Y: 4