java 不允许布尔型转换int,为什么Java不允许转换布尔值 - > Int?

本文探讨了Java不支持布尔类型直接转换为整数的原因,归结于Java设计者避免C/C++中布尔/整型混淆带来的错误。通过比较不同类型的转换规则,解释了Java为何保持类型区分,以及这种设计如何影响代码的清晰度和一致性。
摘要由CSDN通过智能技术生成

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?

解决方案

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 C or C++.

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值