简体   繁体   中英

Operator ! cannot be applied to int

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 ?

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

! 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 .

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);

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