bad operand types for binary operator "&" java

user3364498 picture user3364498 · Apr 15, 2014 · Viewed 158.8k times · Source

The error shows this line

 if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

This is the whole code:

public class Ex4 {

  public static void main(String[] args) {
  int [] a = new int [3];
  if(args.length == 3)
  {
      try{
        for(int i = 0; i < args.length; i++)
        {
        a[i] = Integer.parseInt(args[i]);
        }
        }
        catch(NumberFormatException e){
            System.out.println("Wrong Argument");
       }
      if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){
        System.out.println("yes");
      }
    else {
        System.out.println("no");
    }
  }
  else{
      System.out.println("Error");
    }
}
}

I've fixed the code:

if ((a[0] & 1) == 0 && (a[1] & 1) == 0 && (a[2] & 1) == 0){

Was an issue with the brackets, updated for anyone in the future.

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Apr 15, 2014

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.