liveBook · Manning

Long

As explained in Clojure: The Essential Reference

A Java long is a signed 64-bit primitive integer type with a fixed representable range.

A Clojure long represents a signed 64-bit integer, useful when ordinary integer values need a fixed Java-compatible range. It stores values from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. section 5.13 section 5.1

The important boundary and arithmetic behaviors are:

  • Checked arithmetic such as + throws on overflow, while unchecked-* operations use Java-style long arithmetic and wrap around. section 5.1 section 5.13
  • Incrementing Long/MAX_VALUE produces Long/MIN_VALUE with unchecked-inc; decrementing Long/MIN_VALUE produces Long/MAX_VALUE with unchecked-dec. section 5.13
  • Mixed numeric operations follow type-promotion or contagion rules, with the result determined by the most precise operand type. section 5.13
  • Applications requiring values beyond the long range can use Clojure's arbitrary-precision operators such as +'. section 5.1

Boundary wrap-around

(unchecked-inc (long (Math/pow 2 63))) ;; -9223372036854775808 (unchecked-dec (long (- (Math/pow 2 63)))) ;; 9223372036854775807 Use this deliberate wrap-around behavior for workloads such as hashing, but use arbitrary-precision arithmetic when overflow would be incorrect. section 5.13

[(long (- (Math/pow 2 63))) (long (Math/pow 2 63))] ; #1
;; [-9223372036854775808 9223372036854775807]

Inspect the exact minimum and maximum long values produced by converting powers of two. section 5.13

How Clojure: The Essential Reference covers it

How deep it goes
Explains the 64-bit range, overflow wrap-around, type promotion, and arbitrary-precision alternative through executable examples.
Examples
Demonstrates exact boundaries, unchecked increment and decrement, and long-based string hashing.
What you can do after
Evaluate fixed-width integer boundaries, choose checked or wrapping arithmetic, and recognize when arbitrary precision is required.
How it connects
Connects long values to integer overflow, unchecked arithmetic, type promotion, arbitrary-precision arithmetic, and hashing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.