Why can I assign an int to a char variable without an explicit cast?

I wanted to know why this snippet works.

char ch1; ch1 = 'a' + 1; System.out.println(ch1); 

Line 2 does not have the right side advanced to int , and then to assign int is char , do we need an explicit listing?

In the same way, I understand what happens when you do ch1 = 65 . But since Java does not allow automatic conversion of type down, we do not need to explicitly distinguish from int to char ?

+7
source share
2 answers

Because the Java language specification says:

Also, if the expression is a constant expression (ยง15.28) of type byte, short, char or int:

Narrowing down a primitive conversion can be used if the type of the variable is a byte, short, or char, and the value of the constant expression is represented in the type of the variable.

So, you are correct that the expression advances to int , but since it is a constant expression, casting is not required. If he included the variable (or its value did not fit into char ), it would be different.

For these kinds of questions, it is best to take a look at the language specification right away, as it is an authoritative source and readable for the specification.

+10
source

I am using Eclipse at the moment. Two things to note:

  • The compiler checks the bounds during initialization.
  • The compiler calculates the values โ€‹โ€‹of constant expressions, for example 3 * (2 + 1) .

It works:

 byte b = 127; // works, range of a byte is [-128, 127] 

But this is not so:

 byte b = 128; // does not work, outside of range 

It works:

 byte b = 100 + -228; // works, 100 + -228 = -128 

But this is not so:

 byte b = 1; byte c = b + 1; // does not work, why not? 

And this is not so:

 byte b = 1; byte c = b + (byte) 1; // does not work, why not? 

Note that b is a variable expression. If a variable expression is involved, the result of the + operator is no less than int. Therefore, you cannot assign it c . Unlike constant expressions, the compiler does not evaluate variable expressions.

The compiler will also complain about short and char - try it yourself.

And finally, using final for a variable effectively turns it into a constant expression, so this will work:

 final byte b = 1; byte c = b + 1; // works 
+3
source

All Articles