java奇怪的赋值规则

标签 java char integer variable-assignment

short s = 'a';       // valid
Short ss = 'a';      // valid
int i = 'a';         // valid
Integer ii = 'a';    // invalid

为什么 Integer ii = 'a' 无效,但 int i = 'a' 有效?为什么 Short ss ='a' 有效,但 Integer ii = 'a' 无效?


另一套问题:

byte b;
final short s = 1;
final Short ss = 1;
final int i =1;
final Integer ii = i;
final long L = 1;
final Long LL =1L;

b = s;     // valid
b = ss;    // invalid
b = i;     // valid
b = ii;    // invalid
b = L;     // invalid
b = LL;    // invalid  

为什么 b = L;无效,而 b = s;有效的 ?

请不要说这都是因为JLS这么说的。我想知道为什么 JLS 有这些不一致和不直观的规则。我错过了什么?

最佳答案

所以,行:

Short s = 'a'; // is valid ...

因为 char 是无符号 16 位值(最大值为 65,536)而 short 是有符号 16 位值(最大值为 32,767),所以有缩小原始转换(char 到 short),然后是装箱转换(short 到 Short)。

short s = 'a'; // is valid - this is a narrowing primitive conversion (char -> short)

这些是 special cases :

In addition, if the expression is a constant expression of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:

  • Byte and the value of the constant expression is representable in the type byte.

  • Short and the value of the constant expression is representable in the type short.

  • Character and the value of the constant expression is representable in the type char.

让我们转到下一个示例:

Integer ii = 'a'; // is invalid - not a special case according to Oracle docs
int i = 'a';      // is valid - widening primitive conversion (char -> int) is allowed

还有一个来自您问题的案例:

byte b;
final long L = 1;
b = L // error - incompatible types

为什么行 b = L 无效?因为它不是上述的特殊情况,而且我们可能会在转换过程中丢失信息,所以您必须显式执行它:

b = (byte) L; // is valid - narrowing primitive conversion (long -> byte)

另外,看看很有帮助的 table .

JLS 文档中有很多关于所有这些规则的信息,您无需担心所有这些规则。关于你的最后一个问题,我能说的是,如果没有隐式缩小转换,在接下来的情况下,任何整数文字都需要强制转换:

// Cast is permitted, but not required - profit!
byte  b = (byte)  100;
short s = (short) 100;

多亏了这一点,我们可以将其更改为:

byte  b = 100;
short s = 100;

关于java奇怪的赋值规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43398912/

相关文章:

java - 相对布局以编程方式添加一个 View ,另一个 View 未正确对齐

java - int和string的类型转换,java

java - 如何从其他系统访问系统 jboss bin 中的文件

java - 声明变量、方法和类?

java - JPA 2 : Referential integrity constraint violation while saving entity with undirectional OneToMany relationship

C 将字符数组转换为整数

c++ - 是否可以使用 C 创建结构,例如只能设置一次的字符串 (char *) 数据?

c# - 枚举所有可能的字符

javascript - 似乎无法在 javascript 中添加两个整数?

python - 找到许多文件中最大的版本号文件?