- 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
Importance of XOR operator in Java?
Bitwise XOR (exclusive or) "^" is an operator in Java that provides the answer '1' if both of the bits in its operands are different, if both of the bits are same then the XOR operator gives the result '0'. XOR is a binary operator that is evaluated from left to right. The operator "^" is undefined for the argument of type String.
Example 1
public class XORTest1 { public static void main(String[] args) { boolean x = false; boolean y = false; boolean xXorY = x ^ y; System.out.println("false XOR false: "+xXorY); x = false; y = true; xXorY = x ^ y; System.out.println("false XOR true: "+xXorY); x = true; y = false; xXorY = x ^ y; System.out.println("true XOR false: "+xXorY); x = true; y = true; xXorY = x ^ y; System.out.println("true XOR true: "+xXorY); } }
Output
false XOR false: false false XOR true: true true XOR false: true true XOR true: false
Example 2
public class XORTest2 { public static void main(String[] args) { String str1 = "1010100101"; String str2 = "1110000101"; StringBuffer sb = new StringBuffer(); for (int i = 0; i < str1.length(); i++) { sb.append(str1.charAt(i)^str2.charAt(i)); } System.out.println(sb); } }
Output
0100100000
Advertisements