In this tutorial you will learn about the Java Program to Swapping Two Numbers without Using a Temporary Variable and its application with practical example.
Java Program to Swapping Two Numbers without Using a Temporary Variable
In this tutorial, we will learn to create a Java program that will be Swapping Two Numbers without using a Temporary Variable 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.
- Arithmetic Operations in Java Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Take the input numbers from the user. 3. Swap Two numbers. 4. Print the output swapped numbers to the user. 5. End the program. |
Swapping Two Numbers without using a Temporary Variable.
In today’s tutorial, we will learn to create a java program that will swap two numbers. First, we will take the numbers in input from the user. Then we will pass that number to the arithmetic equations to swap the numbers without the third variable. At last, we will print the swapped numbers to the user using the print function.
With the help of this program, we can Swap Two Numbers without using a Temporary Variable.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//Java Program to Swapping Two Numbers without Using a Temporary Variable //Importing the util package for input output class functions import java.util.*; //Main class of the program class Swap { //Body of Main function of the program. public static void main(String a[]) { //Declaring the required variabnle for the program. int x,y; //Taking the input from the user System.out.println("Enter the value of x and y"); Scanner sc = new Scanner(System.in); /*Define variables*/ x = sc.nextInt(); y = sc.nextInt(); //Printing the numbers before the swapping of the values. System.out.println("before swapping numbers: "+x +" "+ y); /*Swapping the two numbers using the code*/ x = x + y; y = x - y; x = x - y; //Printing the output swapped number to the user. System.out.println("After swapping: "+x +" " + y); } } |
Output:-
In the above program, we have first initialized the required variable.
- x = it will hold the integer value.
- y = it will hold the integer value.
Taking input numbers from the user.
Swapping the numbers without using the third variable in the program.
Printing the numbers after swapping.