문제

The following segment of code issues a compile-time error.

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

The error on the second line says,

possible loss of precision
  required: char
  found:    int

The error message is based on the NetBeans IDE.


When this character c is declared final like as follows.

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

The compiler-time error vanishes.

It is unrelated to the case of final strings

What does the final modifier make a difference here?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top