The <code>long</code> Primitive in Java — 64-bit Integer

long is a 64-bit signed integer — range -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807. You reach for it any time a value could exceed ~2.1 billion: Unix timestamps in milliseconds, file sizes, database IDs, counters that might wrap.

The L suffix matters

long big = 3_000_000_000;        // ❌ compile error — int overflow before assignment
long ok  = 3_000_000_000L;        // ✅ L forces long literal
long ms  = 1_700_000_000L * 1000;  // ✅ compute as long from the start

// Common trap:
long ns  = 1000 * 1000 * 1000 * 60 * 60 * 24;  // ❌ overflows int mid-calculation
long ok2 = 1000L * 1000 * 1000 * 60 * 60 * 24; // ✅ first L makes the rest long

Epoch time is long

long ms  = System.currentTimeMillis();  // ms since 1970-01-01 UTC
long ns  = System.nanoTime();            // monotonic — for intervals only
Instant.ofEpochMilli(ms);                // convert to java.time

Try the Epoch Timestamp Converter for this exact conversion.

When long still isn't enough

For IDs past 9.2×10¹⁸, monetary amounts with arbitrary precision, or cryptographic values, use BigInteger. For arbitrary-precision decimals, BigDecimal.

Formatting

long n = 1_234_567_890_123L;
String.format("%,d", n);           // "1,234,567,890,123"
Long.toHexString(n);               // "11f71fb04cb"
Long.toUnsignedString(-1L);         // "18446744073709551615" — treat as unsigned

Common mistakes

  • Missing L on large literals — int overflow happens at compile time, not runtime.
  • Multiplying ints into a long — if all operands are int, the multiplication happens in 32 bits first. Put the L early.
  • Using currentTimeMillis() for timing — it's affected by NTP. Use nanoTime() for intervals.

Related

Pillar: Java primitives. See also int, the Timestamp tool, and arithmetic operators.