Search code examples
javadata-structurescompiler-errorsbit-manipulationbitwise-operators

Logical AND error in java. Not able to do binary AND


I am new to java and I am learning bitwise operators. When I run the below code it throws an error. I don't know what is the mistake. I replaced && by & it still gives an error.

class Main{
    
    public static void main(String []args){

      int n=5, k=3;
        if (n && (1<<(k-1)!=0))  //THIS LINE GIVING ERROR
            System.out.println("Mahima! bit is set");
        else
            System.out.println("Mahima!  bit is not set");
        
    
    }
}

Below is the error.

  Line 6: error: bad operand types for binary operator '&&' [in Main.java]
            if (n && (1<<(k-1)!=0))
                  ^
      first type:  int
      second type: boolean

When I use a single & I get the following error

Line 6: error: bad operand types for binary operator '&' [in Main.java]
        if (n & (1<<(k-1)!=0))  //THIS LINE GIVING ERROR
              ^
  first type:  int
  second type: boolean

Solution

  • First, you are right to change the && operator to &.
    && is the logical and operator. It takes two booleans and returns a boolean.
    & is the bitwise and operator. It takes two ints and returns an int.

    After changing && to &, you'll have to add some parenthesis, though, since != has a higher precedence than &:

    if ((n & (1<<(k-1))) !=0)
        System.out.println("Mahima! bit is set");
    else
        System.out.println("Mahima!  bit is not set");