1

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?

  • 4
    `long v = 9_223_372_036_854_775;` Have you even tried running this? – Marv Mar 02 '19 at 10:51
  • https://stackoverflow.com/questions/769963/javas-l-number-long-specification – Om Sao Mar 02 '19 at 10:54
  • The postfix `L`is needed for `long` numbers that are above the range of an `int`. On a side note: Is is preferrable to use `L` instead of `l`, because `l` can easily get misread as `1` for most fonts. – Dorian Gray Mar 02 '19 at 11:14
  • 1
    For long numbers outside the int range, 999999999999L, and for contexts that can have both int and long - seldom – Joop Eggen Mar 02 '19 at 11:16
  • @DorianGray, for that same reason you'll also see `d` preferred to `D` when working with doubles. – Matt Mar 02 '19 at 11:18
  • @Dorian Gray I reckon you answered your own question. Clarity is king and so where permitted L. – TJA Mar 02 '19 at 11:19
  • @TJA What do you mean woth " I reckon you answered your own question." ? I didn't ask a question. – Dorian Gray Mar 02 '19 at 11:22
  • It is for the benefit of the compiler so it knows whether the literal should be an int or a long. – Mark Rotteveel Mar 02 '19 at 12:08
  • @Dorian Gray sorry was tired and misread your statement. – TJA Mar 02 '19 at 23:32

1 Answers1

1

int literal

If 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;

Note

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

Zabuzard
  • 25,064
  • 8
  • 58
  • 82