Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 double and int. Why doesn't Java include this feature?

like image 850
Jared Nielsen Avatar asked Apr 29 '13 14:04

Jared Nielsen


3 Answers

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 an application that that is written C or C++.

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

This doesn't work in all cases. For example (in Java):

if (flag = true) {
    ...
}

compiles. However, it does work in enough cases to be worthwhile. Furthermore, the idiomatic way to write the above in Java is:

if (flag) {
    ...
}

which avoids the pitfall entirely. Also, a checker like findbugs or pmd should flag the incorrect version as suspicious. (And a style checker ought to indicate that flag == true is bad style!)


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.

like image 116
Stephen C Avatar answered Sep 28 '22 08:09

Stephen C


Java supports widening conversions on primitive numeric types. However, boolean is not considered a numeric type.

The supported widening conversions are listed under "Widening Primitive Conversion" in the Java Language Specification.

like image 41
Andy Thomas Avatar answered Sep 28 '22 09:09

Andy Thomas


Because Java is strongly typed, a boolean and an int are two completely different data typesand one can not be casted to the other - it can not be casted, in fact.

like image 45
Óscar López Avatar answered Sep 28 '22 09:09

Óscar López