Java LONG Integer Types

It is required to define the Long variable as

Long myUserId = 1L; ?

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

+4
source share
2 answers
 Long myUserId = 1; // error 

does not work because 1 is an int.

It will be automatically loaded:

 Integer myUserId = 1; // ok 

It will also expand to:

 long myUserId = 1; // also ok 

but not both.

So yes you have to say

 Long myUserId = 1L; 

which is long , which can be auto-boxed in long .

As for why it works this way (or rather doesn't work in this case): Most likely because the auto-box was added later (in Java5) and should be absolutely compatible with feedback. This limited how they could be β€œsmoothed out”.

+7
source

Since otherwise Java defaults to all numeric types assigned to Integer.

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

Without β€œ1L”, off-screen, it looks like this without β€œL”:

 Long myUserId = Integer.valueOf(1); 

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

+1
source

Source: https://habr.com/ru/post/1384639/


All Articles