Swapping Program in Java

The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the execution of the swapping program will interchange their values, i.e., X = 24 and Y = 12.

There are two approaches to interchange values between the two variables.

  • Using Third Variable
  • Using Addition and Subtraction

Using Third Variable

The different steps required to interchange values between the given variables are mentioned below.

STEP 1: Define three variables x, y, and z.

STEP 2: Assign values to any of the two variables. Let’s assign the values in x and y.

STEP 3: Print the values of x and y.

STEP 4: Assign the value of x to the third variable z, i.e., z = x; Now, x and z both contain the same value.

STEP 5: Assign the value of y in x, i.e., x = y;

STEP 6: Assign the value of z in y, i.e., y = z;

STEP 7: Again, print the values of x and y. The values swapped.

The following Java program uses the above steps to interchange the values of the two variables.

Filename: SwappingExample.java

Output 1:

Output 2:

Explanation: In the above program, we are providing values to the variables i and j. The variable k acts as the third variable. On the basis of the above-mentioned steps, we are doing accomplishing the swapping of numbers between the variables i and j.

Using the Addition and Subtraction

In this approach, the usage of the extra variable is not required. We do only the addition and subtraction operations on both numbers in such a way that numbers contained in both the variables get swapped.

There are the following steps to swap the two numbers using addition and subtraction.

STEP 1: Define two variables, a and b.

STEP 2: Assign values to the variables.

STEP 3: Display values of the variables a and b.

STEP 4: Update the value of variable a by doing the addition operation, i.e., a = a + b

STEP 5: Update the value of variable b by doing the subtraction operation, i.e., b = a – b

STEP 6: Again, update the value of the variable a by doing the subtraction operation, i.e., a = a – b

STEP 7: Again, display the values of variables a and b. This time values of the variables a and b get swapped.

The following Java program illustrates the above-written steps.

Filename: SwappingExample1.java

Output1:

Output2:

Explanation: In the code, we are providing values to the variables a and b. Then, we are swapping the values of variables a and b using the steps defined above. Finally, we are displaying the result.

Note: The second approach is more important than the first one. The second approach is usually asked in interviews.

Pin It on Pinterest

Share This