Can I manipulate booleans like ints in Java?

Is a boolean primitive in java a type in its own right, or can it be manipulated like an int? In other languages ​​I've seen, booleans can be manipulated as if false = 0 and true = 1, which can sometimes be quite convenient.

+3


source to share


3 answers


Is a boolean primitive in java a native type?

Yes. boolean

is a primitive type in its own right

can it be manipulated like an int?



Not. It cannot be implicitly or explicitly applied or otherwise used like int

(Java is not C)

If you want to "force" it to an int:

boolean b;
int i = b ? 1 : 0; // or whatever int values you care to use for true/false

      

+4


source


No, you cannot do this in Java. In Java, the boolean values ​​true and false are not integers, and they will not be automatically converted to integers. (In fact, it's not even legal to explicitly cast from boolean to int or vice versa.

boolean only accepts true or false .

Boolean value for int



int i = myBoolean ? 1 : 0;

      

Int to Boolean

boolean b = (myInt == 1 ? true : false);

      

+1


source


No, in Java you cannot treat "int" as boolean, and you cannot overlay "int" with boolean.

If you've ever needed to evaluate an integer as true / false, the code is trivial. For example:

  boolean isTrue = (i != 0);

      

+1


source







All Articles