What does the ^ operator do in Java?

前端 未结 17 1977
执念已碎
执念已碎 2020-11-22 03:27

What function does the ^ (caret) operator serve in Java?

When I try this:

int a = 5^n;

...it gives me:

17条回答
  •  无人共我
    2020-11-22 03:45

    Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like

    • XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
    • If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
    • Swapping values without using temporary variable
    • Finding missing number in the range 1 to n
    • Basic validation of data sent over the network.

    Lot many such tricks can be done using bit wise operators, interesting topic to explore.

提交回复
热议问题