Operator ! cannot be applied to int

1.2k Views Asked by At

In C++, !1 means false which is equivalent to 0. I apply the same rule in Java, but IDE told me ! cannot be applied to int. Is there any way in Java to apply ! to int instead of just writing true or false?

3

There are 3 best solutions below

0
On BEST ANSWER

No, not in Java.
In java ! can operate only on boolean as negate operator, 1/0 are not considered as booleans in Java

0
On

! only applies to Boolean values in Java, or the results of conditional statements. The closest thing you could do is if (x == 1) or boolean y = x == 1.

0
On

Nope, operators do not work on primitive data types, with the exception of, of-course, booleans. Using !0 would simply result in an error. Even though 0s and 1s can be considered boolean values, they are not in Java. The negation operator is only for booleans. Something like !0 would be:

boolean alwaysfalse = (0 != 0);

or

boolean alwaysTrue = (0 == 0);