If I want to save a long variable, why do I have to write an L or l at the end of the value?
For example:
9_223_372
long v = 9_223_372L;
But if I save it:
long v = 9_223_372;
it's still a long variable. So why do I have to write L or l?
If I want to save a long variable, why do I have to write an L or l at the end of the value?
For example:
9_223_372
long v = 9_223_372L;
But if I save it:
long v = 9_223_372;
it's still a long variable. So why do I have to write L or l?
int literalIf you do not write it, Java will create it as int and from there cast to long:
long number = 10;
// Is the same as
long number = (long) 10;
// i.e.
int asInt = 10;
long number = (long) asInt;
This works as long as the number you are writing is an int and will fail if its not, for example a very high number:
// Fails, "integer number too large"
long number = 10_000_000_000_000_000;
With L (or l) you tell Java that this literal is a long and not an int in the first place. Which also gets rid of the unnecessary conversion:
long number = 10_000_000_000_000_000L;
The same also works for floating numbers, when you want a float instead of a double, you add F (or f). Technically, you can also add D or d for a double, but a floating number literal is already double by default, so this is not needed:
float asFloat = 0.5F;
double asDouble = 0.5D;
double alreadyDoubleByDefault = 0.5;
By the way, please do not use l (small L), it gets easily confused with 1 (one).