import java.util.Scanner;
public class SwapNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
Enter the first number: 10
Enter the second number: 26
Before swapping:
num1 = 10
num2 = 26
After swapping:
num1 = 26
num2 = 10
Scanner
class to read two numbers input by the user. We then swap the values of the two numbers using a temporary variable called temp
. Finally, we print out the values of the two numbers before and after swapping.import java.util.Scanner;
public class SwapNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
Enter the first number: 26
Enter the second number: 32
Before swapping:
num1 = 26
num2 = 32
After swapping:
num1 = 32
num2 = 26
Scanner
class to read two numbers input by the user. We then swap the values of the two numbers without using a temporary variable. This is done by adding the two numbers together and storing the result in the first variable.