算术赋值没有隐式转换?

问题描述 投票:0回答:1

在处理缩小转换的JLS 5.2中,它说:

此外,如果表达式是byte,short,char或int类型的常量表达式(第15.28节):

如果变量的类型是byte,short或char,则可以使用缩小的基元转换,并且常量表达式的值可以在变量的类型中表示。 ...

"In other words, for the non-long integer-like values, you can implicitly narrow them iff the value you're narrowing is a constant that fits within the type you're specifying."

  byte a = 1; // declare a byte
  a = a*2; //  you will get error here

在第一个语句中,在字节范围内的整数1被分配给字节a并且存在隐式转换。

在第二个语句中,值为1的字节a乘以整数2。由于Java中的算术规则,值1的字节a被转换为值1的整数。将这两个整数(1 * 2)相乘的结果是整数2。

为什么第二个语句中没有隐式转换会导致错误?

Main.java:14: error: incompatible types: possible lossy conversion from int to byte
  a = a*2; 
java implicit-conversion
1个回答
2
投票

因为,在你的例子中,a*2不是constant expression

如果a提到constant variable,这将是一个不变的表达式:

final byte a = 1;
byte b = a * 2; // compiles fine
© www.soinside.com 2019 - 2024. All rights reserved.