gpt4 book ai didi

java - 在 Java 中打开非整数

转载 作者:搜寻专家 更新时间:2023-11-01 01:06:52 26 4
gpt4 key购买 nike

我无法弄清楚 Java 中开关的内部工作原理有人告诉我,对于所有基元,值都被提升为整数。

但是,在下面的示例中,我正在测试一个字节变量,任何大于 127 的情况都不会编译:

byte k = 5;
switch(k){
case 128: //fails to compile, possible loss of precision

我知道这是一个错误,对此没有任何问题。我的问题是:
如果 JVM 在测试每个案例之前采用“k”的值并将其提升为整数,那么 JVM 如何跟踪它正在切换一个字节?

最佳答案

switch 语句不限于int。 Java 语言规范 (JLS),section 14.11, The switch Statement , 状态

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.

因此,您的 byte 不会升级为 int。 JLS 继续说你正在做的事情会导致编译时错误:

Every case constant expression associated with a switch statement must be assignable to the type of the switch Expression.

...因为 128 不能分配给 byte

关于java - 在 Java 中打开非整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8684065/

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