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

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

    as according to my understanding,

    Because you have to cast the type long to int , for the first option , i.e

    int i = (int) 5l;
    

    and in second case, as the value assignment to byte is same like assignment to int,

    you think i am assigning int value to byte here

    byte b= 5; ????
    

    no its not, its getting the value as byte itself, as byte have a range from -128 to 127,

    for further detail see HERE

提交回复
热议问题