这是怎么回事,
char ch = 9 + '0';
System.out.println(ch);
将导致,
9
但是,
int k = 9;
char ch = k + '0';
System.out.println(ch);
会回来
“类型不匹配:无法从 int 转换为 char”
最佳答案
这在 JLS Sec 5.2 中有描述:
5.2 Assignment Contexts
...
if the expression is a constant expression (§15.28) 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.
...
Example: The compile-time narrowing of constant expressions means that code such as:
byte theAnswer = 42;
is allowed.
这适用于您的示例,因为 9 + '0'
是一个常量,并且可以静态确定它适合 char
。因此,转换可以隐式完成。
另一方面,k
不是常量,因此编译器无法确定 k + '0'
是否适合 char
;因此,它需要显式转换。
关于java - 隐式变量转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685578/