×

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

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.