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 the error "The literal 1111111111111111 of type int is out of range" what am I doing wrong?
3 Answers
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 5 Comments
L ;)Long.valueOf instead, like: long testInt = Long.valueOf(inputBox.getText().toString());. Otherwise your input value will either be truncated to Integer.MAX_VALUE` or (more likely) will fail to parse entirely.The problem is that numeric literals are ints 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.
1 Comment
L is preferable for visual reasons.