Write a java program to swap two numbers

Ex: Write a java program to swap two numbers. How to write a java program to swap two numbers using temp variable. java program to swap two numbers using temp variable.


Java program to swap two numbers:

import java.util.Scanner;

public class Swap {

    public static void main(String[] args) {

        int num1;
        int num2;
        int temp;

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number1: ");
        num1 = sc.nextInt();
        System.out.println("Enter the number2: ");
        num2 = sc.nextInt();

        System.out.println("Before swapping\n number1 = "+num1+" \n number2 = "+num2);

        temp = num1;
        num1 = num2;
        num2 = temp;

        System.out.println("After sewapping\n number1 = "+num1+" \n number2 = "+num2);
    }
}

Above java program shows the following Output:

Enter the number1: 11
Enter the number2: 22

Before swapping 
number1 = 11
number2 = 22

After swapping
number1 = 22
number2 = 11

No comments:

Post a Comment

If you have any doubts, please discuss here...👇