In this tutorial you will learn about the Java Program to swap two Numbers and its application with practical example.
Java Program to Swap two Numbers
In this tutorial, we will learn to create a Java program that will Swap Two Numbers in Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- While loop in Java programming.
Program to Swap the Numbers:-
As we all know, Java is a very powerful language. With the help of the Java programming language, we can make many programs. We can perform many input-output operations using Java programming. In today’s tutorial, we take the input numbers from the user. Then we will swap the Numbers with the help of operators in the Java programming language.
With the help of this program, we can swap the Numbers.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Taking the input numbers from the user. 3. Swapping that number using third variable. 4. Print the Result. 5. End the program. |
Program to Swap to Numbers using a third variable:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.*; class Swap_With { public static void main(String[] args) { //Declaring the required variables for the program. int first, second, flag;// first and second are to input numbers //Taking the input numbers from the user. Scanner sc = new Scanner(System.in); System.out.println("Enter the value of X and Y"); //Scanning the input numbers first = sc.nextInt(); second = sc.nextInt(); System.out.println("before swapping numbers: "+first +" "+ second); //Swapping the numbers one from two. flag = first; first = second; second = flag; //printing the swapped numbers to the user. System.out.println("After swapping: "+first +" " + second); System.out.println( ); } } |
Output:-
In the above program, we have first initialized the required variable.
- first= it will hold the integer value.
- second = it will hold the integer value.
- flag = it will hold the integer value.
Taking the input number 1 and 2 from the user.