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 duplicate characters are found in the string using a nested for loop.
We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With