Swap two numbers in java using third or temporary variable (example)

  • Given two input numbers, swap numbers using temporary variable.
    • e.g. Given two input numbers x = 10 & y = 30
    • exchange two variables using temporary variables
    • After swapping we should get out x = 30 & y = 10.
  • We have shown swapping of two variables in Fig 1.
swap variables java
Fig 1: Swap two variables

1. Program: swap two variable using temporary (third) variable in java

package org.learn;

import java.util.Scanner;

public class DemoSwapNumbers {

 public static void main(String[] args) {
  try (Scanner scanner = new Scanner(System.in)) {
   
   System.out.printf("1. Enter first number : ");
   int x = scanner.nextInt();
   
   System.out.printf("2. Enter second number : ");
   int y = scanner.nextInt();
   
   System.out.printf("3. Numbers before swapping: x = %d, y = %d \n", x, y);

   int temp = x;
   x = y;
   y = temp;

   System.out.printf("4. Numbers after swapping: x = %d, y = %d \n", x, y);

  }
 }

}

2. Output: swap two variables using third variable in java

1. Enter first number : 50
2. Enter second number : 100
3. Numbers before swapping: x = 50, y = 100 
4. Numbers after swapping: x = 100, y = 50 

1. Enter first number : 27
2. Enter second number : 55
3. Numbers before swapping: x = 27, y = 55 
4. Numbers after swapping: x = 55, y = 27 
Scroll to Top