Search code examples
javabitwise-operatorsternary

bad operand types for binary operator &


I am trying to print even and then odd using bitwise & operator, but don't why it is not working with ternary operator.

class Geeks {
     static void evenOdd (int a,int b) 
     {
     int e = (a&1==0)?a:b;// error: bad operand types for binary operator '&'
     System.out.println(e);
     int o = (a&1==1)?a:b;// error: bad operand types for binary operator '&'
     System.out.print(o);
     }
}

Solution

  • It's due to the precedence of operators being used.

    Since == has higher precedence than &, 1==0 is evaluated. It evaluates to a boolean result. Since & is getting 2 operands - one boolean and one integer. It results in the compilation error as & can be performed on alike types.

    It is the same reason why multiplication is performed before addition(known as BODMAS)

    Parenthesis has to be used in such cases :

        System.out.println(e);
        int o = ((a&1)==1)?a:b;
        System.out.print(o);