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
First, you are right to change the &&
operator to &
.
&&
is the logical and operator. It takes two boolean
s and returns a boolean
.
&
is the bitwise and operator. It takes two int
s 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");