
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
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
Advertisements