0

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?

4
  • 5
    No. Java doesn't let you treat anything other than boolean or Boolean as a boolean. Aug 25, 2019 at 20:42
  • 2
    ...and I am glad about that.
    – MC Emperor
    Aug 25, 2019 at 20:44
  • 1
    Why not just use i != 0 instead of !i? Aug 25, 2019 at 20:45
  • Official doc ! Logical complement operator; inverts the value of a boolean Aug 25, 2019 at 20:48

3 Answers 3

4

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

1

! 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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.