In this post, we will see how to resolve bad operand types for binary operator & in java.
Problem
Let’s first reproduce this issue with the help of simple example of Even odd program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class BadOperatorTypeMain { public static void main(String[] args) { System.out.println(evenOdd(2)); } static int evenOdd (int num) { return (num&1==0)?0:1; // error: bad operand types for binary operator '&' } } |
We will get error bad operand types for binary operator
& at line 11.
Solution
We are getting this error due to precedence of the operators.
Since ==
has higher precedence than &, 1==0
will be evaluated first and will result in boolean. If you can notice, ‘&’ has two operands now – one boolean and another integer and it will result into compilation error due to different type of operands.
It is similar to why multiply is performed prior to addition.
You can fix this issue by using parenthesis properly.
Let’s fix this issue in above code snippet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class BadOperatorTypeMain { public static void main(String[] args) { System.out.println(evenOdd(2)); } static int evenOdd (int num) { return ((num&1)==0)?0:1; } } |
Output:
As you can see error is resolved now.
That’s all about how to resolve bad operand types for binary operator & in java