Make Selenium Easy

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

Last updated on January 2nd, 2019 at 09:51 am

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

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

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

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.

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

by Amod Mahajan time to read: 1 min
2
%d bloggers like this: