Here we will see the swapping of two numbers using two different methods. In first method we exchange the values using the temporary variables and in second method Swapping of numbers without temporary variable.

Swapping of numbers is the way of exchanging the values in the variables. Suppose there are two variables a and b, The variable a has a value 15 and the variable b has the value 25. We need to exchange this values that is store the value 25 in variable a and store value 15 in the variable b. For simplicity see the below example

For example:

Numbers to swap: 15 and 25
Let a=15 and b=25

swapping logic:
temp=a=15
a=b=25
b=temp=15

After swapping:
a=25 b=15

In this below programs we specify the values of variables in the program itself. If you want to take this values from user, then you can use Scanner class and get input from user also. To know how to get input from user you can refer this article Addition of Two Numbers.

Program: Swapping of Two Numbers Using Temporary Variable

In this program we use one temporary variable temp for exchanging the values between two numbers a and b.

class SwapNumbers
{
public static void main(String[] args)
{
  int a=15,b=25,temp;
  System.out.println("Before Swapping: a="+a+" and b="+b);
  temp=a;
  a=b;
  b=temp;
  System.out.println("After Swapping: a="+a+" and b="+b);
}
}
 

Output:

Before swapping: a=15 and b=25
After swapping: a=25 and b=15
swapping of two numbers

Program: Swapping of Two Numbers without Using Temporary Variable

In this program we can not use any temporary variable for exchanging the values of variables. As all of you know it is possible to swap values without using temporary variable. For considering this we write the below code.

class SwapNumbers
 {  
 public static void main(string arg[]) 
 {  
  int a = 15, b = 25;  
  System.out.println("Before swapping: a="+a+" and b="+b);  
  a = a + b;  
  b = a - b;  
  a = a - b;  
  System.out.println("After swapping: a="+a+" and b="+b); 
 }  
}   

Output:

Before swapping: a=15 and b=25
After swapping: a=25 and b=15
swapping of two numbers

Both the programs produces the same output. But difference is that we use two different ways for exchange of values in variables.

If you are new in java programming and you don’t know how to run java program then must read How to Run a Java Program. There are some simple programs for beginners for this see this articles Simple programs.

I hope this contents are helpful for you! If you are having any doubt please comment me below and If you like this article please please comment me…

Thank You….

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top