Written by Sai Sandeep Thota on July 19, 2013 in Java > Programming

Java Program to Swap two Numbers

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This is a very simple Java Program to Swap two Numbers. We are taking input from the user into the two variables a, b and using the third variable temp for swapping the values.

Java Program to Swap two Numbers

import java.util.Scanner;

class swapNumber {
	public static void main(String args[])
	{
		int a, b, temp;
		Scanner get = new Scanner(System.in);
		System.out.println("Enter Two integer values to swap:");
		a = get.nextInt();
		b = get.nextInt();
		
		temp = a;
		a = b;
		b = temp;		
		
		System.out.print("Values of A & B after swapping: A = "+a+" B = "+b);
	}
}

Output:
Java Program to Swap Two Numbers

Java Program to Swap Two Numbers without using Third variable

This program doesn’t use the third variable temp. Instead we use just use the two variables and swap the values. This reduces space complexity.

import java.util.Scanner;

class swapNumber2 {
	public static void main(String args[])
	{
		int a, b;
		Scanner get = new Scanner(System.in);
		System.out.println("Enter two integer values to Swap the values:");
		a = get.nextInt();
		b = get.nextInt();
		
		a = a + b;
		b = a - b;
		a = a - b;
		
		System.out.println("Values of A & B after swapping: A = "+a+" B = "+b);
	}
}

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: