Java Reference ยท Types and Literals
The long type
Reference for Java long: the 64-bit signed integer type, when to choose it over int, the L suffix, overflow, exact arithmetic and common uses like timestamps.
long is a 64-bit signed integer. It ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, roughly plus or minus 9.2 quintillion. Use it for file sizes, millisecond timestamps, database ids, factorials and any count that may exceed two billion.
A literal is an int unless it ends in L. Write the suffix in uppercase: a lowercase l looks like the digit 1. Like int, long arithmetic wraps around silently on overflow.
long population = 8_100_000_000L; long seconds = 60L * 60 * 24 * 365;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
long name = value; // value may be an int expression or end in L
| Property | Value |
|---|---|
| Size | 64 bits |
| Minimum | Long.MIN_VALUE = -263 |
| Maximum | Long.MAX_VALUE = 263 - 1 |
| Default value | 0L |
| Wrapper class | java.lang.Long |
Usage notes
- Use the
Lsuffix on any literal outside theintrange; without it the code does not compile (integer number too large). - Widen before you multiply.
a * bwith twointoperands is computed in 32 bits even if you assign it to along. Make at least one operandlongfirst. - Narrowing keeps the low bits.
(int) someLongnever throws; it just discards the high 32 bits.Math.toIntExact()throws when the value does not fit. - Exact arithmetic.
Math.addExact(),subtractExact(),multiplyExact()andincrementExact()havelongoverloads that throwArithmeticExceptioninstead of wrapping. - Beyond 64 bits use
BigInteger. - Atomicity. Reads and writes of non-volatile
longfields are not guaranteed atomic by the language on 32-bit JVMs. Declare themvolatileor useAtomicLongfor shared counters. - Time.
System.currentTimeMillis()returns along;InstantandDurationare usually better than raw longs. - Switching on a
longis not allowed;switchacceptsint,char,byte,short, their wrappers, strings and enums.