Skip to content
Tutorials Center
My learning

Topics

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.

Java
long population = 8_100_000_000L;
long seconds = 60L * 60 * 24 * 365;

Try it

Java Why the L suffix matters

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.

Java Exact arithmetic and conversions

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

Java
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 L suffix on any literal outside the int range; without it the code does not compile (integer number too large).
  • Widen before you multiply. a * b with two int operands is computed in 32 bits even if you assign it to a long. Make at least one operand long first.
  • Narrowing keeps the low bits. (int) someLong never throws; it just discards the high 32 bits. Math.toIntExact() throws when the value does not fit.
  • Exact arithmetic. Math.addExact(), subtractExact(), multiplyExact() and incrementExact() have long overloads that throw ArithmeticException instead of wrapping.
  • Beyond 64 bits use BigInteger.
  • Atomicity. Reads and writes of non-volatile long fields are not guaranteed atomic by the language on 32-bit JVMs. Declare them volatile or use AtomicLong for shared counters.
  • Time. System.currentTimeMillis() returns a long; Instant and Duration are usually better than raw longs.
  • Switching on a long is not allowed; switch accepts int, char, byte, short, their wrappers, strings and enums.