8
long l2 = 32;

When I use the above statement, I don't get an error (I did not used l at the end), but when I use the below statement, I get this error:

The literal 3244444444 of type int is out of range

long l2 = 3244444444;

If I use long l2 = 3244444444l;, then there's no error.

What is the reason for this? Using l is not mandatory for long variables.

TylerH
  • 20,799
  • 66
  • 75
  • 101
PSR
  • 39,804
  • 41
  • 111
  • 151

2 Answers2

7

3244444444 is interpreted as a literal integer but can't fit in a 32-bit int variable. It needs to be a literal long value, so it needs an l or L at the end:

long l2 = 3244444444l; // or 3244444444L

More info:

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 1
    But i declared as long.How it interpreted as integer – PSR Jul 19 '13 at 04:46
  • 1
    @PSR the variable is integer, the literal value is interpreted as `int` and when being assigned to the `long` variable it will become a `long` value. Refer to the link in my answer for further info. – Luiggi Mendoza Jul 19 '13 at 04:48
0

Note that while int literals will be auto-widened to long when assigning to a long variable, you will need to use an explicit long literal when expressing a value that is

  1. greater than Integer.MAX_VALUE (2147483647)

    (or)

  2. less than Integer.MIN_VALUE (-2147483648):

    long x1 = 12; //OK
    long x2 = 2147483648; // not OK! That's not a valid int literal
    long x3 = 2147483648L; // OK
    
Community
  • 1
  • 1
Ganesh Rengarajan
  • 2,006
  • 13
  • 26