Java Program to Swap two Numbers - The Coding Shala
Home >> Java Programs >> Swap Two Numbers
Other Posts You May Like
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
- Add Two Numbers in Java
- Java Program to find Sum of Digits of a Number
- Count Negative Numbers in Sorted Matrix
- Compare Two Strings by Ignoring whitespaces
- How to Reverse a String in Java
Comments
Post a Comment