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

后端 未结 2 1630
挽巷
挽巷 2021-01-18 06:17

I wanted to know why this snippet works.

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

In line 2, isn\'t the right hand side promoted

相关标签:
2条回答
  • 2021-01-18 06:51

    Because the Java Language Specification says:

    In addition, 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.

    So you're right in that the expression is promoted to int, but because it's a constant expression, the cast is not necessary. If it involved a variable (or its value did not fit into a char), it would be different.

    For this kind of question it's best to look at the language specification right away, as it's the authoritative source and quite readable for a specification.

    0 讨论(0)
  • 2021-01-18 06:52

    I'm using Eclipse at the moment. There are two things to note:

    • The compiler checks for bounds during initialization.
    • The compiler calculates the values of constant expressions, such as 3 * (2 + 1).

    This works:

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

    But this does not:

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

    This works:

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

    But this does not:

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

    And this does not, either:

    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 at least as large as an int. Therefore, you can't assign it to c. Unlike constant expressions, the compiler does not calculate variable expressions.

    The compiler would similarly complain for short and char - try it out yourself.

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

    final byte b = 1;
    byte c = b + 1; // works
    
    0 讨论(0)
提交回复
热议问题