Not getting integer overflow in Clojure?

I run Clojure 1.3.0 with La Clojure in IntelliJ IDEA while reading The Joy Of Clojure, and in section 4.1.3 (p. 64) the authors demonstrate an integer overflow with the following code:

(+ Integer/MAX_VALUE Integer/MAX_VALUE) ;=> java.lang.ArithmeticException: integer overflow 

However, when I try to execute REPL, I get instead

 user=> (+ Integer/MAX_VALUE Integer/MAX_VALUE) 4294967294 user=> Integer/MAX_VALUE 2147483647 

What's going on here? Why are my integers being added correctly and not overflowing?

+7
source share
2 answers

(edited) Clojure (at least 1.3.0) automatically converts an integer to a long one, if necessary. For more information about automatic support for boxing, promotion, and primitive numeric type in Clojure 1.3.0, see the Documentation for Clojure 1.3.0 Numerics .

The reason you don't get overflow is because Clojure automatically converts the integer to long, therefore (+ Integer/MAX_VALUE Integer/MAX_VALUE) adds two longs:

 user> (type Integer/MAX_VALUE) java.lang.Long 
+8
source

In Clojure, all primitive integers are primitive long , and the documentation on the page with numbers refers to this. in 1.3 you just need large numbers to get an overflow.

 user=> (+ Long/MAX_VALUE Long/MAX_VALUE) ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1374) 

This important part is that older versions of Clojure automatically moved to a large int, and it was decided that the cost was not worth the extremely rare cases when this is desired. if you really want to promote mathematical use +'

 user=> (+' Long/MAX_VALUE Long/MAX_VALUE) 18446744073709551614N 
+8
source

All Articles