Swap Two Numbers in Java (With & Without 3rd Variable)

Introduction

In this tutorial, we will learn how to write a Java program to swap the values of two numbers. We will explore two different approaches for swapping two numbers in Java:

  • Swapping two numbers using a third variable.
  • Swapping two numbers without using a third variable.

Let’s explore both approaches step by step and understand how each one works.

Swap Two Numbers With Using a Temporary Variable in Java

Problem Statement

Write a Java program that reads two integers from the user and swaps their values using a third, temporary variable. After swapping, display the values of both variables on the console.

For example, if the user enters 10 and 20, after swapping, the console output is:

  • The first variable should contain 20.
  • The second variable should contain 10.

The program should use a temporary variable to temporarily store one of the values during the swapping process.

Input Format

The program should read two integers from the user:

  • First number
  • Second number

Output Format

Display the values of the two variables after swapping:

First number after swapping: <value>
Second number after swapping: <value>

Constraints

  • The input values must be integers.
  • Both numbers can be positive, negative, or zero.
  • Use the int data type to store the numbers in Java.
  • Use a temporary variable to swap the values in Java.

Expected Solution Approach of the Program

The simplest and most straightforward approach for beginners is to use a temporary variable to swap the values.

Suppose the initial values are:

firstNumber = 10
secondNumber = 20

Step 1: Store the first number in the temporary variable named temporary.

temporary = firstNumber;

Now, the values of variables are:

temporary = 10
firstNumber = 10
secondNumber = 20

The original value of firstNumber is now safely stored in a temporary variable.

Step 2: Assign the second number to the first variable like this:

firstNumber = secondNumber;

Now, the values of variables are:

temporary = 10
firstNumber = 20
secondNumber = 20

The value of secondNumber variable has been copied into the variable firstNumber.

Step 3: Assign the original first number to the second variable.

secondNumber = temporary;

Now, the values of variables are:

temporary = 10
firstNumber = 20
secondNumber = 10

The two values of variables have now been successfully swapped.

Why Do We Need a Temporary Variable?

In programming, a variable can only store one value at a time in memory. A temporary variable is used to preserve the original value of firstNumber before it is overwritten.

The Overwrite Problem: Without a temporary variable, if you assign secondNumber directly to firstNumber (firstNumber = secondNumber), the original value of firstNumber is immediately overwritten and lost. Due to which, the first number is unavailable for the final assignment to secondNumber.

The Solution: During the swapping process, a temporary variable acts as an intermediate storage holder to preserve the initial value of firstNumber before the overwrite happens:

  • temporary = firstNumber; (Preserve the original value of firstNumber)
  • firstNumber = secondNumber; (Copy secondNumber into firstNumber)
  • secondNumber = temporary; (Assign the preserved value to secondNumber)

Complete Java Program to Swap Two Numbers with 3rd Variable

Here is the step-by-step and complete program to swap two numbers in Java with a third variable.

import java.util.Scanner;
public class SwapTwoNumbers {

    public static void main(String[] args) {
        // Create a Scanner object for user input.
        Scanner scanner = new Scanner(System.in);

        // Read the first number from the user.
        System.out.print("Enter the first number: ");
        int firstNumber = scanner.nextInt();

        // Read the second number from the user.
        System.out.print("Enter the second number: ");
        int secondNumber = scanner.nextInt();

        // Temporarily store the value of the first number.
        int temporary = firstNumber;

        // Assign the second number to the first variable.
        firstNumber = secondNumber;

        // Assign the original first number to the second variable.
        secondNumber = temporary;

        // Display the values after swapping.
        System.out.println("First number after swapping: " + firstNumber);
        System.out.println("Second number after swapping: " + secondNumber);

        // Close the Scanner object.
        scanner.close();
    }
}

Console Output:

Enter the first number: 10
Enter the second number: 20
First number after swapping: 20
Second number after swapping: 10

Step-by-Step Explanation of the Java Program

This Java program reads two integers from the user, swaps their values using a temporary variable, and then displays the values after swapping.

Step 1: Import the Scanner class

import java.util.Scanner;

The Scanner class is imported from the java.util package. It is used to read input from the keyboard.

Step 2: Declare the class

public class SwapTwoNumbers {

This statement declares a class named SwapTwoNumbers. The class contains the main() method, where program execution begins.

Step 3: Define the main() method

public static void main(String[] args) {

The main() method is the entry point of the Java program. The JVM starts executing the program from this method.

Step 4: Create a Scanner object

Scanner scanner = new Scanner(System.in);

A Scanner object named scanner is created to read input from the standard input stream (System.in), which is normally the keyboard.

Step 5: Read the first and the second numbers

System.out.print("Enter the first number: ");
int firstNumber = scanner.nextInt();

System.out.print("Enter the second number: ");
int secondNumber = scanner.nextInt();

The program prompts the user to enter the first and second integer numbers. The nextInt() method reads the entered integer values and stores them in the firstNumber and secondNumber variables.

Step 6: Store the first number temporarily

int temporary = firstNumber;

The original value of firstNumber is stored in the temporary variable.

Now:

temporary = 10
firstNumber = 10
secondNumber = 20

This is important because the value of firstNumber will be overwritten in the next step.

Step 7: Assign the second number to the first variable

firstNumber = secondNumber;

The value of secondNumber is assigned to firstNumber.

Now:

temporary = 10
firstNumber = 20
secondNumber = 20

The original value of firstNumber is still available in temporary.

Step 8: Assign the original first number to the second variable

secondNumber = temporary;

The original value of firstNumber, which was stored in temporary, is assigned to secondNumber.

Now:

temporary = 10
firstNumber = 20
secondNumber = 10

The two numbers have been successfully swapped.

Step 9: Display the swapped values

System.out.println("First number after swapping: " + firstNumber);
System.out.println("Second number after swapping: " + secondNumber);

These statements display the values of firstNumber and secondNumber on the console after the swap. For input 10 and 20, the output will be:

  • First number after swapping: 20
  • Second number after swapping: 10

Step 10: Close the Scanner

scanner.close();

This closes the Scanner object and releases the resources associated with it.

Overall Logic

The swapping process can be summarized as:

temporary = firstNumber
firstNumber = secondNumber
secondNumber = temporary

This is the standard and easiest-to-understand approach for beginners because the temporary variable preserves the original value while the two variables exchange their values.

Swap Two Numbers Without Using a Third Variable in Java

Problem Statement

Write a Java program that reads two integers from the user and swaps their values without using a third (temporary) variable. The swapping operation must be performed using only the two original integer variables.

For example, if the input is

firstNumber = 10
secondNumber = 20

Then, after swapping, the output should be

firstNumber = 20
secondNumber = 10

Constraints

  • Both numbers can be positive, negative, or zero.
  • Use the int data type to store both numbers.
  • Do not use a third variable to perform the swapping operation.

Expected Solution Approach

We can swap two numbers without using a third variable by using addition and subtraction.

Suppose the initial values are:

firstNumber = 10
secondNumber = 20

Step 1: Add both numbers

Add the two numbers and store the result in firstNumber:

firstNumber = firstNumber + secondNumber;

Now:

firstNumber = 30
secondNumber = 20

The original values are still recoverable because their sum is stored in firstNumber.

Step 2: Recover the original first number

Subtract secondNumber from firstNumber and store the result in secondNumber:

secondNumber = firstNumber - secondNumber;

The calculation is:

secondNumber = 30 - 20 = 10

Now:

firstNumber = 30
secondNumber = 10

The original value of firstNumber has been recovered and stored in secondNumber.

Step 3: Recover the original second number

Subtract the new secondNumber from the firstNumber:

firstNumber = firstNumber - secondNumber;

The calculation is:

firstNumber = 30 - 10 = 20

Now:

firstNumber = 20
secondNumber = 10

The values have been successfully swapped without using a third variable.

Why Does This Logic Work?

Let’s trace the algebraic steps to verify the logic:

Initial State

  • firstNumber = A
  • secondNumber = B

Step 1: firstNumber = firstNumber + secondNumber

  • firstNumber = A + B
  • secondNumber = B

Step 2: secondNumber = firstNumber - secondNumber

  • secondNumber = (A + B) - B = A
  • Now:
    • firstNumber = A + B
    • secondNumber = A

Step 3: firstNumber = firstNumber - secondNumber

  • firstNumber = (A + B) - A = B
  • Now:
    • firstNumber = B
    • secondNumber = A

Result:

  • firstNumber = B
  • secondNumber = A

The two values are successfully swapped without using a third variable in Java.

Important Note: Integer Overflow

In Java, every int variable has a maximum limit:

  • Minimum: -2,147,483,648
  • Maximum: 2,147,483,647 (Integer.MAX_VALUE)

What is the problem?

When you add two very large numbers (firstNumber + secondNumber), the sum can exceed the maximum limit. This causes integer overflow, meaning the number wraps around into a negative value.

Why does this matter?

  • In Java: Due to how binary numbers work (two’s complement), the addition and subtraction still give the correct swapped values at the end.
  • In other languages or data types: Integer overflow can crash the program, throw an error, or cause incorrect values (especially with decimals/floating-point numbers).

Best Practice: To completely avoid overflow risks, programmers often use the Bitwise XOR (^) operator instead of addition (+) and subtraction (-).

Complete Java Program to Swap Two Numbers

Here is the complete Java program to swap two numbers without using third variable with step by step comment.

import java.util.Scanner;
public class SwapTwoNumbersWithoutThirdVariable {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read the first number from the user.
        System.out.print("Enter the first number: ");
        int firstNumber = scanner.nextInt();

        // Read the second number from the user.
        System.out.print("Enter the second number: ");
        int secondNumber = scanner.nextInt();

        // Add both numbers and store the result in the variable firstNumber.
        firstNumber = firstNumber + secondNumber;

        // Recover the original firstNumber and store it in the variable secondNumber.
        secondNumber = firstNumber - secondNumber;

        // Recover the original secondNumber and store it in the variable firstNumber.
        firstNumber = firstNumber - secondNumber;

        // Display the swapped values.
        System.out.println("First number after swapping: " + firstNumber);
        System.out.println("Second number after swapping: " + secondNumber);

        scanner.close();
    }
}

Console Output:

Enter the first number: 10
Enter the second number: 20

First number after swapping: 20
Second number after swapping: 10

Follow-Up Challenge

Try another version of this problem to test your understanding:

Challenge: Swap two integers without using a third variable and without using addition (+) or subtraction (-).

Hint: Consider using the Bitwise XOR (^) operator.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.