The Java program swaps two numbers. There are two approaches to achieve this functionality, the first is using a temporary variable and the other is using (arithmetic operator ) without using a temporary variable.
Here’s is an example of swapping two numbers with the help of a temporary variable. It is also possible to interchange two numbers without using a temporary variable which we’ll be discussing later.
Program:
/* * Swapping numbers program using temporary variable in Java * */import java.util.Scanner; public class Swapwithtemp { public static void main(String[] args) { int number, number1,temp; Scanner ed = new Scanner(System.in); System.out.print("\n Enter two numbers:\n First number = "); number = ed.nextInt(); System.out.print("\n Second number = "); number1=ed.nextInt(); System.out.print("\n\n ****** Before Swapping *******\n"); System.out.print("\n First number = "+number+" \n Second number ="+number1); temp=number; number=number1; number1=temp; System.out.print("\n ********* After Swapping *****\n"); System.out.println("\n First number = "+number+" \n Second number ="+number1); } }
Output:
We saw swapping two numbers using a temporary variable. But we can also do it without the help of any third one.
In this approach, arithmetic operators are used which can be a combination of addition & subtraction and multiplication & division. However, we’ll go with addition & subtraction.
Program:
/* * Swapping numbers program without using temporary variable in Java * */ import java.util.Scanner; public class Swapwithouttemp { public static void main(String[] args) { int number, number1; Scanner ed = new Scanner(System.in); System.out.print("\n Enter two numbers:\n First number = "); number = ed.nextInt(); System.out.print("\n Second number = "); number1=ed.nextInt(); System.out.print("\n\n ****** Before Swapping *******\n"); System.out.print("\n First number = "+number+" \n Second number ="+number1); number = number +number1; number1=number-number1; number=number-number1; System.out.print("\n ********* After Swapping *****\n"); System.out.println("\n First number = "+number+" \n Second number ="+number1); } }
Output:
This post was last modified on December 27, 2020