|
| 1 | +# long |
| 2 | + |
| 3 | +If an `int` is not big enough for your needs, a `long` is twice as big as an `int` |
| 4 | +and can represent numbers from `-2^63` to `2^63 - 1`. |
| 5 | + |
| 6 | +You can make a `long` from an integer literal, but integer literals do not |
| 7 | +normally allow for numbers that an `int` cannot store. |
| 8 | + |
| 9 | +```java,does_not_compile |
| 10 | +~void main() { |
| 11 | +// Smaller numbers work without issue |
| 12 | +long smallNumber = 5; |
| 13 | +System.out.println(smallNumber); |
| 14 | +// This is too big for an int |
| 15 | +long bigNumber = 55555555555; |
| 16 | +System.out.println(bigNumber); |
| 17 | +~} |
| 18 | +``` |
| 19 | + |
| 20 | +For those cases you need to add an `L` to the end of the literal.[^lforlong] |
| 21 | + |
| 22 | +```java |
| 23 | +~void main() { |
| 24 | +long smallNumber = 5; |
| 25 | +System.out.println(smallNumber); |
| 26 | +// But with an L at the end, its not too big for a long |
| 27 | +long bigNumber = 55555555555L; |
| 28 | +System.out.println(bigNumber); |
| 29 | +~} |
| 30 | +``` |
| 31 | + |
| 32 | +All operations with a `long` will result in a `long`. Conversions to `int` and |
| 33 | +other "smaller" integer types will be narrowing and require a cast. |
| 34 | + |
| 35 | +```java |
| 36 | +~void main() { |
| 37 | +long a = 5; |
| 38 | +int b = 3; |
| 39 | +// a long times an int will result in a long |
| 40 | +long c = a * b; |
| 41 | +System.out.println(c); |
| 42 | +~} |
| 43 | +``` |
| 44 | + |
| 45 | +And if you have need of a potentially nullable `long`, `Long` with a capital `L` is the boxed version. |
| 46 | + |
| 47 | +```java |
| 48 | +~void main() { |
| 49 | +// Can't have a null "long" |
| 50 | +// long l = null; |
| 51 | + |
| 52 | +// But you can have a null "Long" |
| 53 | +Long l = null; |
| 54 | +System.out.println(l); |
| 55 | +~} |
| 56 | +``` |
| 57 | + |
| 58 | +The reason you will likely end up using `int` more than `long` is that `int` |
| 59 | +works more with other parts of Java. Like array indexing - you can't |
| 60 | +get an item in an array with a `long`, you need an `int` for that. |
| 61 | + |
| 62 | +```java,does_not_compile |
| 63 | +~void main() { |
| 64 | +String[] sadRobots = { "2B", "9S", "A2" }; |
| 65 | +long index = 2; |
| 66 | +// Longs can't be used as indexes |
| 67 | +String sadRobot = sadRobots[index]; |
| 68 | +~} |
| 69 | +``` |
| 70 | + |
| 71 | +But there is nothing wrong with a `long`. If you need to represent a number that is potentially bigger than an `int` then it is useful. |
| 72 | + |
| 73 | + |
| 74 | +[^lforlong]: "L is for long" would be a total cop-out in a children's picture book. |
0 commit comments