Java Program to Swap Two Numbers Without Using a Temp Variable

1. Introduction

Swapping two numbers means interchanging their values. This tutorial will guide you on how to write a Java program to swap two numbers without using a temporary variable.

2. Program Steps

1. Define a class named SwapNumbers.

2. In the main method, declare two variables and initialize them with the numbers you want to swap.

3. Perform the swapping of the numbers using arithmetic operations.

4. Print the values of the numbers after swapping.

3. Code Program

public class SwapNumbers { // Step 1: Define a class named SwapNumbers

    public static void main(String[] args) { // Main method

        int num1 = 20; // Step 2: Declare and initialize the first number
        int num2 = 30; // Declare and initialize the second number

        System.out.println("Numbers before swapping: " + " num1 = " + num1 + ", num2 = " + num2);

        // Step 3: Perform the swapping using arithmetic operations
        num1 = num1 + num2; // num1 now holds the sum of num1 and num2
        num2 = num1 - num2; // num2 now holds the original value of num1
        num1 = num1 - num2; // num1 now holds the original value of num2

        // Step 4: Print the values after swapping
        System.out.println("Numbers after swapping: " + " num1 = " + num1 + ", num2 = " + num2);
    }
}

Output:

Numbers before swapping:  num1 = 20, num2 = 30
Numbers after swapping:  num1 = 30, num2 = 20

4. Step By Step Explanation

Step 1: A class named SwapNumbers is defined.

Step 2: Two integer variables num1 and num2 are declared and initialized with the values you want to swap.

Step 3: The swapping of num1 and num2 is performed using arithmetic operations without using a temporary variable. The sum of num1 and num2 is stored in num1, then num2 is calculated by subtracting the current num2 from num1, and finally, num1 is calculated by subtracting the new num2 from num1.

Step 4: The values of num1 and num2 are printed after the swap.

Comments