# Swap two variables in one line in C/C++, Python, PHP and Java

PythonServer Side ProgrammingProgrammingPHPC++

In this tutorial, we are going to learn how to swap two variables in different languages. Swapping means interchanging the values of two variables. Let's see an example.

## Input

a = 3 b = 5

## Output

a = 5 b = 3

Let's see one by one.

## Python

We can swap the variable with one line of code in Python. Let's see the code.

## Example

Live Demo

# initializing the variables
a, b = 3, 5
# printing before swaping
print("Before swapping:-", a, b)
# swapping
a, b = b, a
# printing after swapping
print("After swapping:-", a, b)

## Output

If you run the above code, then you will get the following result.

Before swapping:- 3 5
After swapping:- 5 3

In the languages like C/C++, PHP, and Java, we will use xor operator to make swapping operation easy. And it helps to complete swapping with one line of code. Let's see the steps involved in writing the program.

• Initialize the variables with two different values.
• Perform xor operation on two variables and assign the result to the first variable.
• Again perform xor operation and assign the result to the second variable.
• Again perform xor operation and assign the result to the first variable.
• The variables will be swapped.

Let's see code in different languages

## Example

Live Demo

# include <stdio.h>
int main() {
int a = 3, b = 5;
printf("Before Swapping:- %d %d", a, b);
(a ^= b), (b ^= a), (a ^= b);
printf("After Swapping:- %d %d", a, b);
return 0;
}

## Output

If you run the above code, then you will get the following result.

Before swapping:- 3 5
After swapping:- 5 3

## Example

class Swap {
public static void main (String[] args) {
int a = 3, b = 5;
System.out.println("Before Swapping:- " + x + " " + y);
a = a ^ b ^ (b = a);
System.out.println("After Swapping:- " + x + " " + y);
}
}

## Output

If you run the above code, then you will get the following result.

Before swapping:- 3 5
After swapping:- 5 3

## Example

Live Demo

<?php
$a = 5;$b = 10;
echo "Before Swapping:- ", $a, " ",$b;
($a ^=$b);
($b ^=$a);
($a ^=$b);
echo "After Swapping:- ", $a, " ",$b;
?>

## Output

If you run the above code, then you will get the following result.

Before Swapping:- 5 10After Swapping:- 10 5

## Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on 11-Jul-2020 08:06:36