Java Program to Swap two Numbers - The Coding Shala

Home >> Java Programs >> Swap Two Numbers

 In this post, we will learn How to Swap Two Numbers in Java.

Swap Two Numbers in Java

We have to write a Java program to swap the values of the given two numbers.

Example:
Input:
num1: 10
num2: 20
Output:
num1 = 20
num2 = 10

Approach 1

Using temporary variable.

Java Program: 

public class Solution {
	public static void main(String[] args) {
		int num1 = 10;
		int num2 = 20;
		System.out.println("Before Swapping");
		System.out.println("First Number: " + num1);
		System.out.println("Second Number: " + num2);
		
		//swap
		int temp = num1;
		num1 = num2;
		num2 = temp;
		
		System.out.println("-----------");
		System.out.println("After Swapping");
		System.out.println("First Number: " + num1);
		System.out.println("Second Number: " + num2);
	}
}

Output:
Before Swapping
First Number: 10
Second Number: 20
-----------
After Swapping
First Number: 20
Second Number: 10

Approach 2

Without using a temporary variable.

Java Program: 

public class Solution {
	public static void main(String[] args) {
		int num1 = 10;
		int num2 = 20;
		System.out.println("Before Swapping");
		System.out.println("First Number: " + num1);
		System.out.println("Second Number: " + num2);
		
		//swap
		num1 = num1 - num2;
		num2 = num1 + num2;
		num1 = num2 - num1;
		
		System.out.println("-----------");
		System.out.println("After Swapping");
		System.out.println("First Number: " + num1);
		System.out.println("Second Number: " + num2);
	}
}

Output:

Before Swapping
First Number: 10
Second Number: 20
-----------
After Swapping
First Number: 20
Second Number: 10


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala