java - 为什么 boolean 是唯一没有定义强制或转换的类型?

标签 java language-design

不允许似乎有道理

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

因为这可能会导致程序员错误,因为即使是整数,生成的 boolean 值也会是假的,但为什么扩大强制转换,例如int a = true 工作?

编辑:

根据 JVM 规范,第 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.

例如:

public static boolean returnFalse() {
    return false;
}

public static boolean returnTrue() {
    return true;
}

编译为:

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

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

最佳答案

内部表示不相关。

Java 是强类型的:int 不是booleanboolean 也不是int.

这是一个设计决定——如果你想使用 true/false,使用 boolean 值;传达一些东西。

如果您想使用整数来表示真/假,请使用数学比较——这也很好。

该语言不支持直接转换,因为它在设计上不支持。


关于JVM规范和 boolean 值的内部表示,这句话很有意思:

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.

对我来说,那是:

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.

对这一点的澄清会很有趣,但最终不相关,真的。

关于java - 为什么 boolean 是唯一没有定义强制或转换的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954709/

相关文章:

swift - Swift 赋值求值无效的原因是什么?

c# - 为什么在 C# 中使用 out 关键字而不是赋值?

algorithm - 做 'if ALL items in collection pass test' 的好方法

c# - 为什么解析助手没有变得更易于使用?

java - 确定服务实例是否正在运行并终止它

Java套接字: Connection reset

java - Spring创建bean但不注入(inject)它

parsing - 用户定义的中缀运算符的解析器

java - 如何访问另一个类中的特定枚举值?

java - 具有用于构建实体的内部类的实体