Assigning an int literal to a long wrapper class in java

夙愿已清 提交于 2019-12-02 19:29:14

问题


Why is there a compilation error with Long l = 3 and not with Long l = 3L?

The primitive data type long accepts both 3 and 3l. I understand that 3 is an int literal - but it can't be assigned to a Long wrapper object? int is only 32 bits shouldn't it fit in a 64 bit integer type?


回答1:


Because there isn't an int to Long widening and autoboxing conversion, autoboxing converts from long to Long (but first the value must be widened from an int to a long). You could do 3L as you have, or

Long l = Long.valueOf(3);

or

Long l = (long) 3;



回答2:


For additional answer:

3L is equals to (long)3 --> parse it to 3L as it is a long literal

3 is a integer literal

3L is a long literal

in a nutshell, they are different from each other that's why you need to parse int to long or vice versa.



来源:https://stackoverflow.com/questions/45558224/assigning-an-int-literal-to-a-long-wrapper-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!