简体   繁体   中英

Java LONG integer types

Are you required to define a Long variable as

Long myUserId = 1L; ?

How come you can't just do Long myUserId = 1; ?

Long myUserId = 1;   // error

does not work, because 1 is an int.

It will get auto-boxed to:

Integer myUserId = 1;   // ok

It will also get widened to:

long myUserId = 1;      // also ok

but not both.

So, yes, you have to say

Long myUserId = 1L;  

which is a long that can get autoboxed into a Long .

As to why it works that way (or rather does not work in this case): Most likely because auto-boxing was added later (in Java5), and had to be absolutely backwards-compatible. That limited how "smooth" they could make it.

Because otherwise, Java defaults all numeric types to an Integer.

The only reason "1L" is even allowed to be assigned to a Long (instead of the primitive long ) is due to the "auto-boxing" introduced with Java 5.

Without the "1L", behind-the-scenes, this looks like the following without the "L":

Long myUserId = Integer.valueOf(1);

... which I hope obviously explains itself. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM