Java Program to Swap Two Numbers Without Third Variable

Java programs to swap two numbers without using third variable have been shown here. The algorithm, pseudocode and time complexity of the programs have been covered here. Check here the flowchart of the programs.






1. Java Program & output to Swap Two Numbers Without Third Variable (Using Addition and Subtraction)

Code has been copied
/***********************************************
        alphabetacoder.com
 Java program to swap two numbers without third
 variable but using arithmetic operators + and -
************************************************/

import java.util.Scanner;
public class Main {
    public static void main(String args[]) {
        int num1, num2;
        //System.in is a standard input stream
        // sc is the object
        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 using + and -
        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;

        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




2. Java Program & output to Swap Two Numbers Without Third Variable (Using Multiplication and Division)

Code has been copied
/***********************************************
        alphabetacoder.com
 Java program to swap numbers without third
 variable but using arithmetic operator * and /
***********************************************/

import java.util.Scanner;
public class Main {
    public static void main(String args[]) {
        int num1, num2;
        //System.in is a standard input stream
        // sc is the object
        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 using * and /
        num1 = num1 * num2;
        num2 = num1 / num2;
        num1 = num1 / num2;

        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