Java Program to Swap Two Numbers

In this program, you'll learn two techniques to swap two numbers in Java. The first one uses a temporary variable for swapping, while the second one doesn't use any temporary variables.

1. Swap two numbers using a temporary variable

package com.javaguides.java.tutorial; import java.util.Scanner; /**  * Java Program to Swap Two Numbers  *   * @author https://www.sourcecodeexamples.net/  *  */ public class JavaProgram { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter first number:"); int first = scanner.nextInt(); System.out.print("Enter second number:"); int second = scanner.nextInt(); System.out.println("--Before swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); // Value of first is assigned to temporary int temporary = first; // Value of second is assigned to first first = second; // Value of temporary (which contains the initial value of first) is assigned to // second second = temporary; System.out.println("--After swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); } } }
Output:
Enter first number:10 Enter second number:20 --Before swap-- First number = 10 Second number = 20 --After swap-- First number = 20 Second number = 10

2. Swap two numbers without using a temporary variable

package com.javaguides.java.tutorial; import java.util.Scanner; /**  * Java Program to Swap Two Numbers  *   * @author https://www.sourcecodeexamples.net/  *  */ public class JavaProgram { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter first number:"); int first = scanner.nextInt(); System.out.print("Enter second number:"); int second = scanner.nextInt(); System.out.println("--Before swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); first = first - second; second = first + second; first = second - first; System.out.println("--After swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); } } }
Output:
Enter first number:10 Enter second number:20 --Before swap-- First number = 10 Second number = 20 --After swap-- First number = 20 Second number = 10

Related Java Programs


Comments