java - 隐式变量转换

标签 java char

这是怎么回事,

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/

相关文章:

java - 可点击的textView不起作用

c - 如何在 C 中创建固定长度 "strings"的数组?

c++ - 二维动态字符数组cpp

java - 解压 GZIP

java - java中如何停止一个线程

java - 找不到适合学生的构造函数(无参数)

java - 逐字符比较java中的两个字符串

java:结合了instanceof和cast?

c++ - 从 char 获取字节值

c - "Save 38% now"C 字符串中止程序