Why is “int i = 2147483647 + 1;” OK, but “byte b = 127 + 1;” is not compilable?

后端 未结 4 1032
囚心锁ツ
囚心锁ツ 2020-12-12 18:45

Why is int i = 2147483647 + 1; OK, but byte b = 127 + 1; is not compilable?

4条回答
  •  醉话见心
    2020-12-12 19:25

    JLS3 #5.2 Assignment Conversion

    ( variable = expression )

    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.


    Without this clause, we wouldn't be able to write

    byte x = 0;
    char c = 0;
    

    But should we be able to do this? I don't think so. There are quite some magic going on in conversion among primitives, one must be very careful. I would go out of my way to write

    byte x = (byte)0;
    

提交回复
热议问题