Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final characters in Java [duplicate]

Tags:

java

char

final

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?

like image 709
Tiny Avatar asked Mar 05 '14 18:03

Tiny


People also ask

How are duplicate characters found in a string?

The duplicate characters are found in the string using a nested for loop.

How do you remove duplicate characters in Java?

We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method.


1 Answers

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.

like image 188
assylias Avatar answered Sep 27 '22 16:09

assylias