Java Program to Swap Two Numbers

You are Here:

Java Program to Swap Two Numbers

In programming, there are two different techniques to swap any two numbers in a variable, they are

  • Swap using Temporary Variable
  • Swap without using Temporary Variable

Swap using Temporary Variable

In the following example, we will swap two numbers (25 and 50) using a temporary variable (temp).

Example

Java Compiler
public class myClass { public static void main(String[] args) { int num1 = 25; int num2 = 50; int temp = 0; temp = num1; num1 = num2; num2 = temp; System.out.println("After swapping..."); System.out.format("\nnum1 = %d", num1); System.out.format("\nnum2 = %d", num2); } }

Output

After swapping... num1 = 50 num2 = 25

Swap without using Temporary Variable

In the following example, we will swap two numbers (25 and 50) without using a temporary variable.

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { int num1 = 25; int num2 = 50; num1 = num1 - num2; num2 = num1 + num2; num1 = num2 - num1; System.out.println("After swapping..."); System.out.format("\nnum1 = %d", num1); System.out.format("\nnum2 = %d", num2); } }

Output

After swapping... num1 = 50 num2 = 25

Swap any Two Given Numbers

In the following example, we will swap any two given numbers without using a temporary variable (temp).

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter a (int) Number1: "); int num1 = reader.nextInt(); System.out.print("Enter a (int) Number2: "); int num2 = reader.nextInt(); int temp = 0; temp = num1; num1 = num2; num2 = temp; System.out.print("\nAfter swapping..."); System.out.format("\nnum1 = %d", num1); System.out.format("\nnum2 = %d", num2); } }

Output

Enter a (int) Number1: 25 Enter a (int) Number2: 36 After swapping... num1 = 36 num2 = 25

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author