Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LONG integer types

Tags:

java

Are you required to define a Long variable as

Long myUserId = 1L; ?

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

like image 899
Webnet Avatar asked Dec 05 '11 04:12

Webnet


2 Answers

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.

like image 51
Thilo Avatar answered Oct 26 '22 02:10

Thilo


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. :-)

like image 39
ziesemer Avatar answered Oct 26 '22 02:10

ziesemer