Here you will get java program to swap numbers using temporary variable.
It can be done in following way.
temp = a
a = b
b = temp
Also Read: Java Program to Swap Two Numbers Without Using Third Variable
import java.util.Scanner; public class JavaSwapNumbers { public static void main(String args[]){ int a, b, temp; Scanner sc = new Scanner(System.in); System.out.print("Enter first number: "); a = sc.nextInt(); System.out.print("Enter second number: "); b = sc.nextInt(); System.out.print("\nBefore swap:\na = " + a + "\nb = " + b); temp = a; a = b; b = temp; System.out.print("\n\nAfter swap:\na = " + a + "\nb = " + b); } }
Output
Enter first number: 5
Enter second number: 8
Before swap:
a = 5
b = 8
After swap:
a = 8
b = 5