How to swap variables in Java with and without a third variable

Overview

Swapping variables means assigning the value of one variable to another programmatically. It is a very common and important operation in programming languages. In this shot, we are going to see how to swap two variables with and without the help of a third variable.

Swapping with the help of a third variable

Syntax

int a,b,c;
c = a;
a = b;
b = c;
Syntax for swapping numbers with a third variable

In the code above, a and b are the two variables that we want to swap. The third variable c will help us to swap a and b.

Code example

class HelloWorld {
public static void main( String args[] ) {
// create and initialize variables
int no1, no2, no3;
no1 = 10;
no2 = 20;
// print values before swapping
System.out.println("Before swapping - no1: "+ no1 +", no2: " + no2);
// swap numbers
no3 = no1;
no1 = no2;
no2 = no3;
// print values after swapping
System.out.println("After swapping - no1: "+ no1 +", no2: " + no2);
}
}

Explanation

  • Lines 4–6: We create our number variables and initialize them.
  • Line 9: We print the values before swapping.
  • Lines 12–14: We swap the variable values.
  • Line 17: We print the swapped values.

Swapping without the help of a third variable

Syntax

To do this, we first add the values of the two variables that we want to swap and make the sum equal to a. Then we get the value of b by subtracting it from a. Finally, we get the value of a by obtaining the difference between b and the previous value of a.

int a,b;
a = a + b;
b = a - b;
a = a - b;
Syntax for swapping numbers without a third variable

Code example

class HelloWorld {
public static void main( String args[] ) {
// create and initialize variables
int no1, no2;
no1 = 10;
no2 = 20;
// print values before swapping
System.out.println("Before swapping - no1: "+ no1 +", no2: " + no2);
// swap numbers
no1 = no1 + no2;
no2 = no1 - no2;
no1 = no1 - no2;
// print values after swapping
System.out.println("After swapping - no1: "+ no1 +", no2: " + no2);
}
}

Explanation

  • Lines 4–6: We create our number variables and initialize them.
  • Line 9: We print the values before swapping.
  • Lines 12–14: We swap the variable values using the method described above.
  • Line 17: We print the swapped values.