Gary Greenhorn
Gary Greenhorn

Reputation: 103

Why is Char implicitly converted to a Int?

In Java, why is a char primitive implicitly converted to an int primitive? People say it's because of a widening conversion - that a 2-byte char will fit in an 4-byte int, but what about booleans? Booleans certainly take up less than 2 bytes, yet they are not implicitly converted.

Upvotes: 2

Views: 933

Answers (3)

Joni
Joni

Reputation: 111349

A conversion from char to int is needed because no operators are defined for chars: you can't check if a char is greater than another or if a char is in a given range without converting to int first.

The same is true for booleans on the JVM level, the difference is that you don't need to do these operations on them (true > false seems a little arbitrary) while operations on chars are needed to implement things like character encoding conversion and case conversion.

Upvotes: 0

Manikandan Sigamani
Manikandan Sigamani

Reputation: 1984

Java developers didn't want Boolean to convert into any int type implicitly, as it was ambiguous in C language. Please see this question

Upvotes: 1

isnot2bad
isnot2bad

Reputation: 24454

A boolean is not a numerical datatype, so an implicity conversion is not defined.

But fortunately it is easy to convert a boolean to any int you'd like:

int value = b ? 1 : 2; // if b is true, value will be 1, else 2.

Upvotes: 1

Related Questions