Java Program to Swap Two Numbers

Swapping two numbers means exchanging the values stored in two variables. If num1 starts with 12 and num2 starts with 87, then after the swap num1 contains 87 and num2 contains 12.

In Java, the clearest approach is to use a temporary variable. It preserves one value while the other variable is overwritten. You can also swap integer values without a third variable using arithmetic or bitwise XOR, but those techniques have limitations that are worth understanding.

Java Swap Syntax Using a Temporary Variable

The standard three-step swap is:

</>
Copy
temp = num1;
num1 = num2;
num2 = temp;

After these assignments, the original value of num1 is in num2, and the original value of num2 is in num1.

Example 1 – Swap Two Numbers using Temporary Variable

In this example, we take two numbers in two variables. Then we shall use a temporary variable to hold one of the numbers while we are trying to swap the values between the two variables.

Algorithm to Swap Two Numbers Using a Temporary Variable

Following is the algorithm we shall use to swap the given two numbers using a third variable.

  1. Start.
  2. Read a number in num1.
  3. Read a number in num2.
  4. Declare a variable temp.
  5. Assign temp with num1.
  6. Assign num1 with num2.
  7. Assign num2 with temp.
  8. Print num1 and num2.
  9. Stop.

Example.java

</>
Copy
/**
 * Java Program - Swap Two Integers
 */

public class Example {

	public static void main(String[] args) {
		//two numbers
		int num1 = 12;
		int num2 = 87;
		
		//temporary variable
		int temp;
		
		//swap two numbers
		temp = num1;
		num1 = num2;
		num2 = temp;
		
		//print the numbers
		System.out.println("num1 : "+num1);
		System.out.println("num2 : "+num2);
	}
}

Explanation

int num1 = 12; declares num1 as integer and initializes num1 with 12.

int num2 = 87; declares num2 as integer and initializes num2 with 87.

int temp; declares temp as integer. We shall use this as temporary variable to hold one of the values of the two numbers.

temp = num1; assigns value in num1 to temp variable. So, we are saving the value of of num1 to temp. Now we can do anything to num1, because we have its value stored in other variable temp. After this step, the variables have the values as shown in the following.

num1 = 12;
num2 = 87;
temp = 12;

num1 = num2; assigns the value of num2 to num1. So, num1 will have a value of 87 stored in it.

num1 = 87
num2 = 87
temp = 12

num2 = temp; assigns the value of temp to num2. So, num2 will have a value of 12 stored in it.

num1 = 87
num2 = 12
temp = 12

We started with num1 and num2 having values of 12 and 87 respectively. After swapping, we are left with num1 and num2 having values 87 and 12 respectively.

We swapped the values in the variables.

Run the above program, and you shall get the following output.

num1 : 87
num2 : 12

Example 2 – Swap Two Numbers Without a Third Variable Using Arithmetic

In this example, we take two numbers in two variables. We shall not use another temporary variable, but just these two variables to swap the numbers. Let us see how.

Example.java

</>
Copy
/**
 * Java Program - Swap Two Integers
 */

public class Example {

	public static void main(String[] args) {
		//two numbers
		int num1 = 12;
		int num2 = 87;
		
		//swap numbers
		num1 = num2+num1;
		num2 = num1-num2;
		num1 = num1-num2;
		
		//print the numbers
		System.out.println("num1 : "+num1);
		System.out.println("num2 : "+num2);
	}
}

Explanation

int num1 = 12; declares num1 as integer and initializes num1 with 12.

int num2 = 87; declares num2 as integer and initializes num2 with 87.

num1 = num2+num1; computes the sum of num1 and num2 and stores it in num1. Starting from 12 and 87, num1 becomes 99 while num2 remains 87.

num1 = 99
num2 = 12

Note: for the values used in this program, immediately after the first arithmetic statement the actual state is num1 = 99 and num2 = 87. A complete step-by-step trace appears below.

num2 = num1-num2; subtracts the current num2 from num1. With 99 - 87, num2 becomes 12, which is the original value of num1.

num1 = 99
num2 = 87

After the second arithmetic statement, the actual state is num1 = 99 and num2 = 12.

At this point, num1 is 99 and num2 is 12. The second variable now contains the original value of num1.

num1 = num1-num2; then evaluates 99 - 12, so num1 becomes 87. The final values are therefore num1 = 87 and num2 = 12.

num1 = 12
num2 = 87

After the third arithmetic statement, the actual state is num1 = 87 and num2 = 12.

The arithmetic operations have now exchanged the values stored in the two variables.

Run the above Java program. The swapped values are printed to the console as shown below.

num1 : 87
num2 : 12

Correct Value Trace for the Arithmetic Swap

For the initial values num1 = 12 and num2 = 87, the arithmetic swap executes in this order: after num1 = num2 + num1, the values are 99 and 87; after num2 = num1 - num2, they are 99 and 12; and after num1 = num1 - num2, they are 87 and 12.

Initial:     num1 = 12, num2 = 87
After step 1: num1 = 99, num2 = 87
After step 2: num1 = 99, num2 = 12
After step 3: num1 = 87, num2 = 12

This addition-and-subtraction method is limited by integer overflow. If num1 + num2 exceeds the range of the Java integer type being used, the intermediate value can overflow. For ordinary application code, the temporary-variable approach is clearer and avoids that particular risk.

Swap Two Numbers in Java Using Scanner Input

If the values should be entered at runtime, read both integers with Scanner and then perform the same temporary-variable swap.

</>
Copy
import java.util.Scanner;

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

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

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

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

        System.out.println("num1 : " + num1);
        System.out.println("num2 : " + num2);

        scanner.close();
    }
}

If the user enters 12 and 87, the output is:

Enter first number: 12
Enter second number: 87
num1 : 87
num2 : 12

Swap Two Integers in Java Using the XOR Operator

Two integer variables can also be swapped without a temporary variable by using the bitwise XOR operator ^. This works for Java integral types such as int and long, but it is generally less readable than a normal temporary-variable swap.

</>
Copy
int num1 = 12;
int num2 = 87;

num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;

System.out.println("num1 : " + num1);
System.out.println("num2 : " + num2);

Output

num1 : 87
num2 : 12

Unlike the addition-and-subtraction technique, XOR does not require an arithmetic sum that can overflow. However, it is intended for integral values and is usually harder to understand at a glance.

Swap Two Numbers Through a Java Method

Java passes primitive arguments such as int by value. A method cannot swap two caller variables merely by exchanging its local parameter variables. One simple approach is to return the swapped values and assign them in the caller.

</>
Copy
public class SwapWithMethod {

    static int[] swap(int first, int second) {
        return new int[] { second, first };
    }

    public static void main(String[] args) {
        int num1 = 12;
        int num2 = 87;

        int[] swapped = swap(num1, num2);
        num1 = swapped[0];
        num2 = swapped[1];

        System.out.println("num1 : " + num1);
        System.out.println("num2 : " + num2);
    }
}

Output

num1 : 87
num2 : 12

Which Java Number-Swapping Method Should You Use?

For most Java code, use a temporary variable. It works with primitive numeric types such as int, long, float, and double, and it makes the intent obvious. The arithmetic method avoids a third variable but may overflow for integer types. The XOR method avoids a temporary variable and arithmetic overflow, but it applies to integral types and is less readable.

When swapping values inside a method, remember that Java primitive parameters are copies of the caller’s values. Return the swapped values, store them in a mutable object or array, or redesign the operation around the data structure that owns those values.

Java Swap Two Numbers Summary

In this Java Tutorial, we learned how to swap two integers using a temporary variable, arithmetic operations, Scanner input, the bitwise XOR operator, and a method that returns the swapped values. For clear and maintainable code, the temporary-variable approach is usually the most straightforward choice.