gpt4 book ai didi

java - JVM 中 `boolean` 类型的用途是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:46 24 4
gpt4 key购买 nike

因为它saidJVMS8 中:

Although the Java Virtual Machine defines a boolean type, it only providesvery limited support for it. There are no Java Virtual Machine instructions solelydedicated to operations on boolean values. Instead, expressions in the Javaprogramming language that operate on boolean values are compiled to use valuesof the Java Virtual Machine int data type.

的确,这两个方法:

boolean expr1(boolean a, boolean b) {
return a || b;
}

int expr2(int a, int b) {
return ((a != 0) || (b != 0)) ? 1 : 0;
}

将产生相同的字节码(方法签名除外)

  boolean expr1(boolean, boolean);
Signature: (ZZ)Z
Code:
0: iload_1
1: ifne 8
4: iload_2
5: ifeq 12
8: iconst_1
9: goto 13
12: iconst_0
13: ireturn

int expr2(int, int);
Signature: (II)I
Code:
0: iload_1
1: ifne 8
4: iload_2
5: ifeq 12
8: iconst_1
9: goto 13
12: iconst_0
13: ireturn

所以,我不明白为什么JVM 需要boolean 类型。是否仅用于方法签名的运行时检查?

最佳答案

至少需要支持方法重载。比如说,我们在同一个类中有两个方法

boolean a(boolean x) {...}

boolean a(int x) {...}

它们可以有不同的内部逻辑,所以在字节码中应该通过它们的签名来区分它们。

关于java - JVM 中 `boolean` 类型的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34510037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com