Java Program to Swap Two Numbers Using Third Variable

Java program to swap two numbers using third variable can be implemented by using another variable apart from the variables which store the two given numbers. Swapping of two numbers means the exchanging of values between them.






1. Java Program & output of to Swap Two Numbers using Third Variable

Code has been copied
/*************************************************
        alphabetacoder.com
 Java program to swap two numbers using third variable
*************************************************/

import java.util.Scanner;
public class Swap {
    public static void main(String args[]) {
        int num1, num2, temp;
        // declare an instance of Scanner class
        Scanner sc = new Scanner(System.in);
        // take input
        System.out.print("Enter two numbers = ");
        num1 = sc.nextInt();
        num2 = sc.nextInt();
        System.out.print("Before swapping: number1=" + num1 + " and number2=" + num2 + "\n");

        //do swapping operation using temp
        temp = num1;
        num1 = num2;
        num2 = temp;

        System.out.print("After swapping: number1=" + num1 + " and number2=" + num2 + "\n");
    }
}

Output


Enter two numbers = 5 10

Before swapping: number1 = 5 and number2 = 10

After swapping: number1 = 10 and number2 = 5