Make Selenium Easy

Frequently Asked Java Program 05: Swap two integer variables without using third variable

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a Java program to swap values of two integer variables without using third variable.

Problem Statement:

Write a java program to swap values of two integer variables without using third variable.

Solution:

It is very commonly asked interview program. In Fact it is less program more mathematics.

  1. Let’s assume there are two variables with some values:

             a =10

             b=20

     2. Now add a and b and store in a:

             a = a+b => 10+20 => 30

             b= 20

     3. Now subtract b from a and store in b:

            a= 30

            b = a – b => 30-20 => 10

     4. Now subtract b from a and store in a:

            a= a – b = > 30-10 = > 20

            b= 10

     5. Notice here that both variables a and b have interchange their values. 

Let’s convert above logic into a Java Program.

Java Program:

Output:

 

#HappyCoding

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

3 thoughts on “Frequently Asked Java Program 05: Swap two integer variables without using third variable

  1. Try with XOR option too as + may result in overflow –
    a=a^b ; ( a XOR B)
    b=a^b; ( a XOR B)
    a=a^b; ( a XOR B)

    =====================

    1 XOR 0 = 1
    0 XOR 1= 1
    0 XOR 0 = 0
    1 XOR 1 =0

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.