

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap two variables in one line in using Java
Two variables can be swapped in one line in Java. This is done by using the given statement.
x = x ^ y ^ (y = x);
where x and y are the 2 variables.
A program that demonstrates this is given as follows −
Example
public class Example { public static void main (String[] args) { int x = 12, y = 25; System.out.println("Original values of x and y"); System.out.println("x = " + x); System.out.println("y = " + y); x = x ^ y ^ (y = x); System.out.println("Swapped values of x and y"); System.out.println("x = " + x); System.out.println("y = " + y); } }
Output
Original values of x and y x = 12 y = 25 Swapped values of x and y x = 25 y = 12
Now let us understand the above program.
First, the original values of x and y are printed. The code snippet that demonstrates this is given as follows.
int x = 12, y = 25; System.out.println("Original values of x and y"); System.out.println("x = " + x); System.out.println("y = " + y);
The x and y are swapped in a single line. Finally, the swapped values of x and y are displayed. The code snippet that demonstrates this is given as follows.
x = x ^ y ^ (y = x); System.out.println("Swapped values of x and y"); System.out.println("x = " + x); System.out.println("y = " + y);
- Related Questions & Answers
- Swap two variables in one line in Java
- Swap two variables in one line using C#
- Swap two variables in one line in using Python?
- Swap two variables in one line in C/C+
- Swap two variables in one line in C/C++, Python, PHP and Java
- How to Swap Two Variables using Python?
- How to swap two String variables without third variable.
- How to swap variables using Destructuring Assignment in JavaScript?
- Java program to swap two numbers using XOR operator
- Swap two Strings without using third user defined variable in Java
- Java program to swap two integers
- Java Program to Swap Two Numbers.
- Swap two numbers in C#
- Next higher number using atmost one swap operation in C++
- Swap two Strings without using temp variable in C#
Advertisements