Java program to swap two numbers

Java program to swap two numbers is a very basic example and can be used in any programming language.

This is a beginner-level question for all programmers.

Here different ways are given for swapping two numbers.

All below java programs shows only method to implement this.

Swapping of two numbers can be done in any language.

1 Swapping two numbers using a third variable

This is a simple and most commonly used method where three variables are taken.

The first variable value is stored in the third variable now the second variable value is stored in variable first and again temporary variable (here c ) value is stored in the second variable.

Output

2. Swapping two numbers without using third variable

Here no extra variables are taken. two variables are added and stored in the first variable.

Now the second variable is subtracted from the first and stored in the second variable.

Similarly way second is again subtracted from the first and stored in the first variable.

Output

3. Swapping two numbers in a single line using addition and subtraction

Here all operation is performed in a single line as given b = (a + b) - (a = b)

Output

4. Swapping two numbers in a single line using multiplication and division

Here multiplication and division operation is used a=(a * b)/(b=a).

Output

5. Swapping two numbers using multiplication and division

Here numbers must be non zero

swapping of two numbers can also be achieved using multiplication and division operations as given above.

Output

6. Swapping two numbers using XOR operator

above operation can also be written as

Output

Here XOR short hand operator is used.

Output

Here Java program to swap two numbers are discussed.

Read More

  1. Sum of two numbers using command line arguments in java
  2. Java Scanner Class Getting Input from user and file
  3. Leap Year Program in Java
  4. for, while, do while and for each loops in Java