Rose Perrone
Rose Perrone

Reputation: 63556

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

Upvotes: 2

Views: 237

Answers (3)

Dave Newton
Dave Newton

Reputation: 160191

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.

Upvotes: 8

Celeritas
Celeritas

Reputation: 15053

It's just a convention that in languages such as C++ 0 is false and all other integers are true. Java doesn't have any convention specifying a boolean value to any integers.

I'm confused by "why doesn't a widening coercion, e.g. int a = true work" are you wondering why they didn't make it so this would assign 1 to a?

Upvotes: 0

David Mathias
David Mathias

Reputation: 335

Java is not C++ to hold one 0 for false and 1 for true. In java boolean is a different data type. C++ need at least 1 byte to have a boolean. In java it depends on the JVM implementation.

Upvotes: 0

Related Questions