Java long Numbers Help
So at the top of my code I declared the variable
private long counter;
And when I try to give it a number that's really long it gives an error, Im trying to do this
counter = 1111111111111111;
Thats 16 "1"s and I keep getting开发者_Python百科 the error "The literal 1111111111111111 of type int is out of range" what am I doing wrong?
Try it like this:
counter = 1111111111111111l;
Note that the last character there is the letter 'L' (lowercase, of course), and not the number one. Here is a clearer example:
counter = 2222222222222222L;
As others have pointed out, an uppercase 'L' also works and is much more clear. All integer literals in Java are interpreted as ints
unless you suffix them with an 'L' (or 'l') to tell the compiler to interpret it as a long
.
A similar thing happens with literal floating-point numbers, which are interpreted as doubles
by default unless you suffix them with an 'f' to tell the compiler to interpret it as a float
. As in:
double num1 = 1.0; //1.0 is treated as a literal double
float num2 = 1.0; //1.0 is still treated as a literal double; the compiler may complain about loss of precision
float num3 = 1.0f; //1.0 is treated as a float, and the compiler is happy
The java compiler reads any number as an integer by default. 11111111111 is obviously outside the range of an integer. Type counter=11111111111L;
to get the compiler to read the value correctly.
The problem is that numeric literals are int
s by default. To make the numeric literal a long you have to finish it with the alpha character l
(lower-case L). So:
long counter = 1111111111111111l;
In C# you can also use an upper-case L. I'm not sure about Java.
精彩评论