×

Swapping Program in Java

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

// importing the Scanner class
import java.util.Scanner;
public class SwappingExample
{
    public static void main(String argvs[])
    {
        // define three variables
        int i, j, k;       
        // Creating an object of the Scanner class
        Scanner scnr = new Scanner(System.in); 
         //reading the values of i and j from the user
         System.out.println("Provide the values of i and j ");
         i = scnr.nextInt();
         j = scnr.nextInt();
         System.out.println("Before swapping, the values of i and j are: " + i + " and " + j );
         // interchanging values of the variables i and j using the third variable k
         k = i;
         i = j;
         j = k;
         // displaying the result
         System.out.println("After swapping, the values of i and j are: " + i + " and " + j );
    }
} 

Output 1:

 Provide the values of i and j
Before swapping, the values of i and j are: 2 and 3
After swapping, the values of i and j are: 3 and 2 

Output 2:

 Provide the values of i and j
Before swapping, the values of i and j are: 9 and 0
After swapping, the values of i and j are: 0 and 9 

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

// importing the Scanner class
import java.util.Scanner;
public class SwappingExample1
{
    public static void main(String argvs[])
    {
        // define two variables
        int a, b;
        // Creating an object of the Scanner class
        Scanner scnr = new Scanner(System.in); 
         // asking user to provide the values to the two variables
         System.out.println("Provide the values of a and b ");
         a = scnr.nextInt();
         b = scnr.nextInt();
         System.out.println("Before swapping, the values of a and b are: " + a + " and " + b );
         // swppaing the values of a and b
         // by taking the reference of steps defined above
         a = a + b;
         b = a - b;
         a = a - b;
         // displaying the result
         System.out.println("After swapping, the values of a and b are: " + a + " and " + b );
    }
} 

Output1:

 Provide the values of a and b
Before swapping, the values of a and b are: -2 and 3
After swapping, the values of a and b are: 3 and -2 

Output2:

 Provide the values of a and b
Before swapping, the values of a and b are: 1 and 3
After swapping, the values of a and b are: 3 and 1 

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.


Related Topics

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.