- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
In order to swap two variable using single expression or in single line we could use bitwise XOR operator of Java.
As we now that in Java XOR functions as XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differs.
So for swapping of two variable we would use this operator as
Example
public class SwapUsingBitwise { public static void main(String[] args) { int a = 8 ; int b = 10; System.out.println("Before swaping : a = " + a + " b = "+b); a = a^b^(b = a); System.out.println("After swaping : a = "+ a + " b = " + b); } }
Output
Before swaping : a = 8 b = 10 After swaping : a = 10 b = 8
- Related Articles
- Swap two variables in one line in using Java
- Swap two variables in one line using C#
- Swap two variables in one line in C/C+
- Swap two variables in one line in using Python?
- Swap two variables in one line in C/C++, Python, PHP and Java
- How to swap two variables in JavaScript?
- How to Swap Two Variables using Python?
- How to swap two files in Linux command line?
- How to swap two String variables without third variable.
- How to swap variables with destructuring in JavaScript?
- Java program to swap two integers
- Java Program to Swap Two Numbers.
- How to swap variables using Destructuring Assignment in JavaScript?
- Swap two numbers in C#
- Swap two Strings without using third user defined variable in Java

Advertisements