5

Are you required to define a Long variable as

Long myUserId = 1L; ?

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

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Ben
  • 60,438
  • 111
  • 314
  • 488

2 Answers2

8
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.

Thilo
  • 257,207
  • 101
  • 511
  • 656
1

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

ziesemer
  • 27,712
  • 8
  • 86
  • 94