Jared Nielsen Jared Nielsen - 2 months ago 9
Java Question

Why Doesn't Java Allow Casting Boolean -> Int?

I was wondering why Java doesn't allow casting from a boolean to an int, like so:

boolean foo = true;
int bar = (int)foo;

This can be done in one line of code, for example,

bar = foo ? 1 : 0;

but it seems like an better and easier-to-read way would be to allow type-casting, as with
. Why doesn't Java include this feature?


It doesn't allow this because the Java designers (correctly) recognized that the boolean / integer overloading in C and C++ was a significant source of errors.

(I recall seeing that in writing in some design rationale, but I can't find it.)

For instance:

if (i = 0) {

is legal but probably a bug in C or C++.

Java avoid this and other problems by making boolean and the integer datatypes different types that cannot be converted from one to the other. Thus, the above is a compilation error in Java.

Now this doesn't explain why you cannot explicitly type cast a boolean to an int. But I think that can be understood by observing the following:

  • You rarely need to do that in real Java programs.

  • Number <-> boolean casting wouldn't jell with the way that other type casts work. In particular, for other types there are up-casts and down-casts, and up-casts1 in Java don't require an explicit type cast.

  • You can't typecast between numbers and string either, or between strings an other objects. These are conversions, not type casts. And int <-> boolean is too.

1 - I am being sloppy with my terminology here (deliberately). The correct Java terminology is "widening" and "narrowing". Narrowing conversions require an explicit type cast with a limited exception for literals. Widening conversions don't require a type cast.