Eypros
Eypros

Reputation: 5723

Binary Ones Complement Operator (or binary negation) for booleans?

I will ask a rather simple question that was's a surprise to me. I wanted to port a simple C code to java and in this code it used an int as boolean. Inside the code it inverted it several times like:

c = !c;

So naturally at first I thought a boolean will work fine. The invertion did not work though (using the Binary Ones Complement Operator ~).

I have tried byte also (after all I just needed a boolean) but the peculiar thing is that this code does not compile indicating an error Type mismatch:

byte c = 0;
c = ~c; //<= here is the error

The eclipse suggested solution was c = (byte) ~c; (conversion to byte).

So my question is whether there is a Binary Ones Complement Operator that operates on booleans and bytes? Should it be overloaded for different types? I just want to invert the value of a boolean that shouldn't be too hard.

P.S.1 long works smoothly with ~ though. P.S.2 I know how to work with int and then convert it to boolean but I thought a faster implementation should exist.

Upvotes: 0

Views: 124

Answers (1)

adjan
adjan

Reputation: 13652

Use boolean in Java and negate it with !.

Upvotes: 1

Related Questions