Home > front end >  Java - error: incompatible types: int cannot be converted to boolean
Java - error: incompatible types: int cannot be converted to boolean

Time:01-18

Considering operation: (7>>1)&1

When we put into print statement it works: System.out.println((7>>1)&1); // works

But if we put in if condition there is error:

if((7>>1)&1) System.out.println('Here'); # shows error

error: incompatible types: int cannot be converted to boolean if((7>>1)&1) System.out.println(123);

I am unable to understand what could be the issue? Since same works in C ..

I tried assigning to a variable int a=(7>>1)&1

if(a==1) System.out.println('works'); // it works here but not when passed directly

CodePudding user response:

Java does not interpret the integers 1 and 0 as equivalent to the booleans true and false, unlike C

See Why boolean in Java takes only true or false? Why not 1 or 0 also? for more information.

CodePudding user response:

As SmallPepperZ stated, in java, if statements do not accept any argument except the boolean primitive type, or a statement that can be evaluated to the boolean primitive type.

To expand on SmallPepperZ answer, the reason for your second issue, requiring that the variable a be used, is due to the fact that the expression gets evaluated in the following way:

if( (7>>1)&1 == 1 )
if( 3 & 1 == 1 )
if( 3 & true )

The error you would have seen should have been the following:

The operator & is undefined for the argument type(s) int, boolean

To fix this, add a set of parenthesis around the expression on the left

if( ((7>>1)&1) == 1 ) System.out.println("Here");

which gets evaluated in the following way:

if( ((7>>1)&1) == 1 )
if( ((3)&1) == 1 )
if( (3&1) == 1 )
if( 1 == 1 )
if( true )
  • Related