34

I'm trying to declare a long value in Java, which unfortunately does not work.

This is my code. It results in the following error message: "The literal 4294967296 of type int is out of range".

long bytes = 4294967296;

I need this value to make a file filter that filters out files that are bigger than 4294967296 bytes (4GB). The other way round works without any issues (long size = file.length()) with every file size, which is why I can't figure out why my declaration is not working.

matt5784
  • 3,065
  • 2
  • 24
  • 42
Peter
  • 617
  • 1
  • 7
  • 13

6 Answers6

76

Add L to the end of the number:

long bytes = 4294967296L;
icktoofay
  • 126,289
  • 21
  • 250
  • 231
28

To answer your question title, the maximum value of a long can be obtained via the constant:

Long.MAX_VALUE

To solve your problem - add the l (L) literal after the number.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
19

long literals are followed by the letter L or l (see: JLS 3.10.1). Uppercase is better because it's more legible, lowercase l looks too similar to 1.

For your particular number, it's probably easier to write:

 long bytes = (1L << 32);

This way, someone who reads the code can quickly tell that bytes is exactly 2 to the power of 32.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 1
    Right, cause that's the first thing everyone thinks of when they see 1L << 32 -- oh hey that's 2^32...rofl. – Uncle Iroh Jul 02 '14 at 21:52
18

try long bytes = 4294967296L; to indicate to the compiler that you are using a long.

Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75
4

The answer to your question "why" is because of 4294967296 is not a long. By default java look on any number as on int or double type (depending on if it has or hasn't dot). And only then convert this number to specified type (long in your case). So the error that you see means that your number is bigger then max value fot int. Adding literal attribute at the end let compiller know which type to use (b - bytes, s - short, l - long, f - float)

2

Soufiane is correct. Here is a doc that shows how to declare literals of the various types of numbers in Java:

http://www.janeg.ca/scjp/lang/literals.html

Doug Porter
  • 7,721
  • 4
  • 40
  • 55