Java Program to Swap Two Numbers

« Previous Program Next Program »

Swap Two Numbers

To swap two numbers in Java Programming, you have to first ask to the user to enter the two number, make a swap variable of the same type. Now place the first number in the variable swap, then place second number in the first, and then place swap in the second.

Java Programming Code to Swap Two Numbers

Following Java Program ask to the user to enter the two number to swap them and display the swapped result on the screen :

/* Java Program Example - Swap Two Numbers */
import java.util.Scanner;

public class JavaProgram
    public static void main(String args[])
        int num1, num2, swap;
        Scanner scan = new Scanner(;
        System.out.print("Enter Two Number : ");
        System.out.print("\nFirst Number : ");
        num1 = scan.nextInt();
        System.out.print("Second Number : ");
        num2 = scan.nextInt();
        swap = num1;
        num1 = num2;
        num2 = swap;
        System.out.print("The Value of the First and Second Number after Swapping is \n");
        System.out.print("First Number = " +num1);
        System.out.print("\nSecond Number = " +num2);

When the above Java Program is compile and executed, it will produce the following output:

Java Program to swap two numbers

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

Java Online Test

« Previous Program Next Program »

© Copyright 2021. All Rights Reserved.