Search code examples
javaxor

The operator ^ is undefined for the argument type(s) long, boolean


I am getting error when I am performing XOR (^) operation on long datatype in Java.

I am not sure if this is how Java works.

Here's the code generating error:

long a = 0, b = 0;
while (a < d) { // d is some value with datatype as long
    while (b < d) {
        if (a ^ b == c && a * b > max) { // error here (c is also some value with datatype as long)
            max = a * b;
        }
        b += 1;
    }
    a += 1;
}

Solution

  • You need to use parentheses like the following:

    if ((a ^ b) == c && a * b > max) { // error here (c is also some 
                                      // value with datatype as  long)
             max = a * b;
    }
    

    ^ has lower precedence than == so the compiler thinks you're trying to XOR with a boolean.