×

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

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 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.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.