Character Arithmetic in Java

During the game, I met something that seems strange to me:

Invalid Java code:

char x = 'A'; x = x + 1; //possible loss of precision 

because one of the operands is an integer, so the other operand is converted to an integer. The result cannot be assigned to a character variable ... while

 char x = 'A'; x += 1; 

valid because the resulting integer - automatically - is converted to a character.

So far so good. This seems clear to me, but ... why the following valid Java code?

 char x; x = 'A' + 1; 
+5
source share
2 answers

Because

 'A' + 1 

- constant expression. At compile time, it is known that the result will match char .

While

 'A' + 787282; 

will not match char and therefore will cause a compilation error.

+1
source

It is valid because it is an expression of a compile-time constant. If it were

 char x; char y = 'A'; x = y + 1; 

The compiler will give you a compile-time error, because now it is not an expression of the compile-time constant. But if you make the variable y as final , the expression will again return to the compile-time constant, so the code below will compile.

 char x; final char y = 'A'; x = y + 1; 

The moral of the story is that when you assign an integer to char, the compiler will resolve it as long as it is a compiler time constant, and it must match the char range.

+1
source

Source: https://habr.com/ru/post/1203543/


All Articles