243

Primitive Data Types - oracle doc says the range of long in Java is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. But when I do something like this in my eclipse

long i = 12345678910;

it shows me "The literal 12345678910 of type int is out of range" error.

There are 2 questions.

1) How do I initialize the long with the value 12345678910?

2) Are all numeric literals by default of type int?

prayagupa
  • 30,204
  • 14
  • 155
  • 192
aamadmi
  • 2,680
  • 2
  • 18
  • 21

4 Answers4

475
  1. You should add L: long i = 12345678910L;.
  2. Yes.

BTW: it doesn't have to be an upper case L, but lower case is confused with 1 many times :).

MByD
  • 135,866
  • 28
  • 264
  • 277
  • 3
    Just in case someone was wondering: the same goes for hex, e.g. `0x200000000L` – user149408 Jun 04 '17 at 14:33
  • @Victor Long.valueOf(long) returns a Long, not a primitive long. MByD's solution avoids to rely on auto-boxing. – gouessej Oct 27 '17 at 08:30
  • @user149408 Perhaps you mean `0x20000000L`? – Pluto Apr 05 '18 at 23:26
  • 2
    @Pluto `0x20000000L` would work but can still be represented by `int` (a 32-bit integer), thus `0x20000000` would work just as well. `0x200000000L` breaks that boundary, making the trailing `L` necessary. – user149408 Apr 07 '18 at 15:55
71
  1. You need to add the L character to the end of the number to make Java recognize it as a long.

    long i = 12345678910L;
    
  2. Yes.

See Primitive Data Types which says "An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int."

Jack Edmonds
  • 31,931
  • 18
  • 65
  • 77
43

You need to add uppercase L at the end like so

long i = 12345678910L;

Same goes true for float with 3.0f

Which should answer both of your questions

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
20

To initialize long you need to append "L" to the end.
It can be either uppercase or lowercase.

All the numeric values are by default int. Even when you do any operation of byte with any integer, byte is first promoted to int and then any operations are performed.

Try this

byte a = 1; // declare a byte
a = a*2; //  you will get error here

You get error because 2 is by default int.
Hence you are trying to multiply byte with int. Hence result gets typecasted to int which can't be assigned back to byte.

Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
Suraj Dubey
  • 536
  • 6
  • 11