Search code examples
javaoperator-precedenceboolean-operations

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


I am solving Hackerrank problem 'Maximizing xor'. (https://www.hackerrank.com/challenges/maximizing-xor)

I have used 'if' statement to check if i xor j is greater than 'max' as shown in code.

static int maxXor(int l, int r) {
    int max=0;
    for(int i=l;i<r;i++)
        for(int j=l;j<r;j++)
        {
            if(i^j>max)/*error part*/
            max=i^j;
        }
    return max;
}

But why am I getting this error?

the operator ^ is undefined for argument type(s) int,boolean'


Solution

  • You need to put parentheses around the expression:

    if ( (i ^ j) > max )
    

    According to Java's operator precedence table, the XOR operator ^ has lower precedence than the inequality operator >.

    Therefore your original written expression of i ^ j > max would be interpreted as i ^ (j > max). But here, the types are incorrect: i is an int, but (j > max) is a boolean. That's why you got that compiler error.


    As a side note, if you compiled this code in C/C++, it would have compiled but it would run with bizarre results. This is because in C/C++, the same operator precedence rules apply in this case, but the bool would be converted to an int of 0 or 1, and then the XOR would proceed. This would have been dangerous and wrong. The Java compiler stopped you from XORing an int with a boolean, which would be a nonsensical operation.