final characters in Java [duplicate]

佐手、 提交于 2019-11-30 17:01:07
assylias

The reason is that the JLS #5.2 (Assignment conversion) says so:

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.

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.

Sotirios Delimanolis

When you apply the + operator to integral types

Binary numeric promotion is performed on the operands (§5.6.2).

In this case, the char values are promoted to int values.

Here

char c = 'c';
char d = c + 5;

because c is not a constant expression, the compiler cannot determine if the value of c + 5 which is an int will be able to fit in a char.

In this

final char c = 'c';
char d = c + 5;

where c is a constant expression, the compiler can determine that the value of c, which is 99, added to 5, which is 104 does fit in a char. Because of this guarantee, Java can safely perform a narrowing conversion from int to char.

If instead you had

final char a = Character.MAX_VALUE;     
char b = (a + 5);

you would see the similar behavior as your first test case as the value of a + 5 does not fit in a char. The compiler determines that the int value resulting from a + 5 would not fit in a char.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!