Here you will learn how Swap two numbers using the third Variable.
The program declares a temp variable to temporarily store the value of one of the two values. If you want to know how to swap numbers without using a third variable, click the link below.
Java Program to Swap two numbers using 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 25 26 27 28 29 | //swap two number import java.util.*; public class SwapTwoNumbersJava { public static void main(String []s) { int a, b, temp; Scanner sc=new Scanner(System.in); System.out.print("Enter value of a: "); a=sc.nextInt(); System.out.print("Enter value of b: "); b=sc.nextInt(); System.out.println("Values before swapping - a: "+ a +", b: " + b); //swap temp=a; a=b; b=temp; //displaying after swap System.out.println("Values after swapping - a: "+ a +", b: " + b); } } |
Output:
1 2 3 4 | Enter value of a: 24 Enter value of b: 25 Values before swapping - a: 24, b: 25 Values after swapping - a: 25, b: 24 |