简体   繁体   中英

Java - error: incompatible types: int cannot be converted to boolean

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

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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM