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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With