Question:
How can you swap two numbers in java?
Answer:
Swapping using temporary or third variable.
Code:
import java.util.Scanner; public class Swap { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first int: "); int i1 = sc.nextInt(); System.out.print("Enter first int: "); int i2 = sc.nextInt(); System.out.println("Value #1 " + i1); System.out.println("Value #2 " + i2); System.out.println("Swapping..."); int temp = i1; i1 = i2; i2 = temp; System.out.println("Value #1 " + i1); System.out.println("Value #2 " + i2); } }
Output:
$ java Swap Enter first int: 1 Enter first int: 4 Value #1 1 Value #2 4 Swapping... Value #1 4 Value #2 1