Why is assigning 'int constant -> byte variable' valid, but 'long constant -> int variable' is not?

前端 未结 6 1546
天涯浪人
天涯浪人 2021-01-19 06:23

I have this code snippet:

int i = 5l; // not valid (compile error)
byte b = 5; // valid

What do you think about it?

Why?

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 07:06

    Language specification allows that (note that 5, 127 or 128 is an integer literal):

        byte b = 127; 
    

    this will generate error:

        byte b = 128;
    

    this is called implicit narrowing primitive conversion, and is allowed by JLS:

    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.

    http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

    so, below is compiler error because of above statement

    int i = 5l;
    

    5l is long and not constant expression (§15.28) of type byte, short, char, or int. Also it fails to be correct becasue it is an int, bacause if the type of the variable is byte, short, or char.

提交回复
热议问题