The preceding Java code is for swapping of numbers.
- import java.util.Scanner;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.IOException;
- class Swapping {
- public static void main(String args[]) throws Exception {
- try {
- BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
- System.out.println("1-Swapping with temp variable");
- System.out.println("2-Swapping without temp variable");
- System.out.println();
- System.out.print("Select any option: ");
- int select = Integer.parseInt(br.readLine());
- switch (select) {
- case 1:
- int x, y, temp;
- System.out.print("Enter x and y: ");
- Scanner input = new Scanner(System. in );
- x = input.nextInt();
- y = input.nextInt();
- System.out.println("Before Swapping\nx = " + x + "\ny = " + y);
- temp = x;
- x = y;
- y = temp;
- System.out.println("After Swapping\nx = " + x + "\ny = " + y);
- break;
- case 2:
- int a, b;
- System.out.print("Enter x and y: ");
- Scanner in = new Scanner(System. in );
- a = in .nextInt();
- b = in .nextInt();
- System.out.println("Before Swapping\nx = " + a + "\ny = " + b);
- a = a + b;
- b = a - b;
- a = a - b;
- System.out.println("After Swapping\nx = " + a + "\ny = " + b);
- break;
- default:
- System.out.println("Wrong choice");
- }
- } catch (IOException e) {
- System.out.println("main method:" + e);
- }
- }
- }
Thank you, keep learning and sharing .