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

前端 未结 3 1107
悲&欢浪女
悲&欢浪女 2020-12-31 05:28

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

相关标签:
3条回答
  • 2020-12-31 06:06

    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.

    0 讨论(0)
  • 2020-12-31 06:23

    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.


    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.

    0 讨论(0)
  • 2020-12-31 06:32

    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.

    0 讨论(0)
提交回复
热议问题