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

前端 未结 6 1538
天涯浪人
天涯浪人 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:27

    Just assuming here because there is unlikely to be a definitive answer.

    For

    int i = 5l;
    

    the compiler assumes there is a good reason you wrote 5l and not 5 and so it is an error.

    For

    byte b = 5;
    

    there is no byte literal way of writing 5 and so it would be needlessly pedantic to insist you write (byte) 5 every time and in fact it would be error prone.

    byte b = 222;        // is an error
    byte b = (byte) 222; // is NOT an error
    

提交回复
热议问题