What does the ^ operator do in Java?

前端 未结 17 1761
执念已碎
执念已碎 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:35

    That is because you are using the xor operator.

    In java, or just about any other language, ^ is bitwise xor, so of course,

    10 ^ 1 = 11. more info about bitwise operators

    It's interesting how Java and C# don't have a power operator.

    0 讨论(0)
  • 2020-11-22 03:41

    XOR operator rule =>

    0 ^ 0 = 0
    1 ^ 1 = 0
    0 ^ 1 = 1
    1 ^ 0 = 1
    

    Binary representation of 4, 5 and 6 :

    4 = 1 0 0 
    5 = 1 0 1
    6 = 1 1 0
    

    now, perform XOR operation on 5 and 4:

         5 ^ 4 => 1  0  1   (5)
                  1  0  0   (4)
                ----------
                  0  0  1   => 1
    

    Similarly,

    5 ^ 5 => 1   0   1    (5)
             1   0   1    (5)
           ------------
             0   0   0   => (0)
    
    
    5 ^ 6 => 1   0   1  (5)
             1   1   0  (6)
            -----------
             0   1   1  => 3
    
    0 讨论(0)
  • 2020-11-22 03:42

    It's bitwise XOR, Java does not have an exponentiation operator, you would have to use Math.pow() instead.

    0 讨论(0)
  • 2020-11-22 03:43

    You can use Math.pow instead:

    https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html#pow%28double,%20double%29

    0 讨论(0)
  • 2020-11-22 03:43

    It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.

    ex :-

    To use your example:

    The binary representation of 5 is 0101. The binary representation of 4 is 0100.

    A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

    0101 ^ 0100 = 0001 (5 ^ 4 = 1) .

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题