Reputation:
I have the following line in my code :-
if (( checker & (1 << val)) ) return false;
where checker is of type int
and val is of type int
. When I try to compile the same I get the following :-
q11.java:38: incompatible types
found : int
required: boolean
if (( checker & (1 << val)) ) return false;
^
1 error
However if I modify the code to have :-
if (( checker & (1 << val)) > 0 ) return false;
then I'm able to compile the source. I'm however unable to understand why the code did not work initially. Some pointers on why this happens?
Upvotes: 0
Views: 112
Reputation: 533870
In Java, your condition must be a boolean i.e. true or false. It cannot be another type.
Your test should be as follow in case val == 31.
if ((checker & (1 << val)) != 0) return false;
BTW C doesn't have a boolean type as such. It uses an int value.
Upvotes: 2
Reputation: 121427
&
is a unary which applied to a two integers (in your if condition) produces another integer. However, Java requires boolean
values in conditions.
Upvotes: 3
Reputation: 727047
Unlike C and C++, where if
takes integers (among many other types) and interprets zeros as false
, Java requires boolean expressions in if
, while
, etc. Since &
is an operation that produces an integer, your first expression is not valid in the condition of the if
.
When you re-write C conditions like that in Java, you need to add != 0
, not > 0
. Otherwise, integers with the most significant bit set to 1
would fail your check.
Upvotes: 1