Search code examples
javalanguage-design

Why is boolean the only type for which there are no coercions or casts defined?


It seems reasonable to not allow

int a = 8;
boolean b = (boolean)a;

because that could lead to programmer errors, because the resulting boolean would be false for even integers, but why doesn't a widening coercion, e.g. int a = true work?

Edit:

According to the JVM specification, Section 3.3.4:

The Java virtual machine encodes boolean array components using 1 to represent true and 0 to represent false. Where Java programming language boolean values are mapped by compilers to values of Java virtual machine type int, the compilers must use the same encoding.

For example:

public static boolean returnFalse() {
    return false;
}

public static boolean returnTrue() {
    return true;
}

compiles to:

public static boolean returnFalse();
  Code:
     0: iconst_0
     1: ireturn

public static boolean returnTrue();
  Code:
     0: iconst_1
     1: ireturn

Solution

  • The internal representation isn't relevant.

    Java is strongly-typed: an int isn't a boolean, and a boolean isn't an int.

    This was a design decision--if you want to use true/false, use booleans; that communicates something.

    If you want to use an integer to represent true/false, use mathematical comparisons--that's fine too.

    The language doesn't support direct conversion because it doesn't, by design.


    Regarding the JVM spec and the internal representation of booleans, this sentence is interesting:

    Where Java programming language boolean values are mapped by compilers to values of Java virtual machine type int, the compilers must use the same encoding.

    To me, that reads:

    If the compiler/VM is using a VM integer to represent true/false, then it must use the 1/0 convention. With the implication being: If the compiler/VM isn't using a VM integer for true/false, this isn't a requirement.

    Clarification on this point would be interesting, but ultimately not related, really.