Home Java Beginners Swapping of two numbers in java

 
 

Share on Google+Share on Google+

Swapping of two numbers in java

Advertisement
In this example we are going to describe swapping of two numbers in java without using the third number in java. We have used input.nextInt() method of Scanner class for getting the integer type values from the command prompt.

Swapping of two numbers in java

In this example we are going to describe swapping of two numbers in java  without using the third number in java. We have used input.nextInt() method of Scanner class for getting the integer type values from the command prompt. The swapping of two numbers is based on simple arithmetic operation that has been described below in simple steps. Same logic has been applied in the programming as well.

Following is the method how to number are swapped:-

First we take two variable "a" and "b".

initially a = 15 and b= 20.

Step 1     a= a+b given a=15+20
               a=35

Step 2    b= a-b given b= 35-20
               b=15

Step 3    a = a-b given a= 35-15
               a =20

Finally   a=20 and b=15

Example

package SwappingNumber;
import java.util.Scanner;

public class SwappingNumber {
	 public static void main(String args[])
	   {
	      int a, b, num;
	      System.out.println("Enter the a vlaue:");
	      Scanner in = new Scanner(System.in);
	      a = in.nextInt();
	      System.out.println("Enter the b value:");
	      b = in.nextInt();
	 
	      System.out.println("Before Swapping value\nx = "+a+"\ny = "+b);
	 
	      num = a;
	      a = b;
	      b = num;
	 
	      System.out.println("After Swapping value\nx = "+a+"\ny = "+b);
	   }
	}

Output

Download source code

Advertisement


Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 18, 2013

Related Tutorials

Discuss: Swapping of two numbers in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com