
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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);
Advertisements