Java中的最终字符 [英] final characters in Java
问题描述
以下代码段会导致编译时错误。
The following segment of code issues a compile-time error.
char c = 'c';
char d = c + 5;
第二行的错误是:
possible loss of precision
required: char
found: int
错误消息基于NetBeans IDE。
如果此字符 c
被声明为 final
,如下所示。
When this character c
is declared final
like as follows.
final char c = 'c';
char d = c + 5;
编译器时间错误消失。
它与最终字符串的情况无关
什么
推荐答案
原因是 JLS#5.2(作业转换)说如下:
如果表达式是byte,short,char类型的常量表达式(§15.28)或int,如果变量的类型是byte,short或char,则可以使用缩小的原语转换,并且常量表达式的值可以在变量的类型中表示。
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.
在您的示例中, char c ='c';
不是常数但 final char c =' c'; 是。
In your example, char c = 'c';
is not a constant but final char c = 'c';
is.
理由很可能是添加运算符 +
将其操作数转换为整数。所以操作可能溢出除非一切都是不变的,在这种情况下编译器可以证明没有溢出。
The rationale is probably that the addition operator +
first converts its operands to integers. So the operation could overflow unless everything is constant in which case the compiler can prove that there is no overflow.
这篇关于Java中的最终字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!