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
//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:
Enter value of a: 24
Enter value of b: 25
Values before swapping - a: 24, b: 25
Values after swapping - a: 25, b: 24