Is a boolean primitive in java a type in its own right or can it be manipulated as an int? In other languages I have seen, boolean types can be manipulated as if false=0 and true=1 which can sometimes be quite convenient.
-
Related: [Why do Java and C# not have implicit conversions to boolean?](https://stackoverflow.com/questions/2951757/why-do-java-and-c-sharp-not-have-implicit-conversions-to-boolean) – Boann Aug 04 '14 at 01:28
3 Answers
Is a boolean primitive in java a type in its own right?
Yes. boolean
is a primitive type in its own right
can it be manipulated as an int?
No. It can not be implicitly or explicitly cast or otherwise used as an int
(Java ain't C)
If you wanted to "coerce" it to an int:
boolean b;
int i = b ? 1 : 0; // or whatever int values you care to use for true/false

- 412,405
- 93
- 575
- 722
-
More to the point: `int myInt = (b) ? 1 : 0;`, and `boolean myBool = (myInt != 0);` – FoggyDay Aug 04 '14 at 04:45
-
@FoggyDay why all the brackets? Why not just `int myInt = b ? 1 : 0` and `boolean myBool = myInt != 0;`. And why `myInt`? – Bohemian Aug 04 '14 at 05:13
No, in Java you can't treat an "int" as a boolean, nor can you cast an "int" to a boolean.
If you ever needed to evaluate an integer as true/false, the code is trivial. For example:
boolean isTrue = (i != 0);

- 11,962
- 4
- 34
- 48
No you cannot do that in Java. In Java, the boolean values true and false are not integers nor will they be automatically converted to integers. (In fact, it is not even legal to do an explicit type cast from the type boolean to the type int or vice versa.
boolean accepts only true or false.
Boolean to int
int i = myBoolean ? 1 : 0;
Int to Boolean
boolean b = (myInt == 1 ? true : false);

- 3,550
- 27
- 26
-
1More general (more "correct"): `boolean b = (myInt !=0) ? true : false;`. The reason is that "0" is *always* "false" but "1" isn't the only integer that can mean "true". – FoggyDay Aug 04 '14 at 04:51
-
That actually depends on the implementation. The question specifically mentions false=0 and true=1, which is normally used as flags when dealing with boolean values. – DanKodi Aug 04 '14 at 05:19