第8章 その他の Java 8 機能を理解する : 問題 2 : 厳密な算術演算
問題
Math.negateExact(int n)
が例外をスローする整数 n の値は何か?
解答
これは一つしかない
Integer.MIN_VALUE
、即ち である
private void exercise2() { int n = Integer.MIN_VALUE; // -2^31 n = Math.negateExact(n); }
実行すると
java.lang.ArithmeticException: integer overflow at java.lang.Math.negateExact(Math.java:977) at javase8.chapter8.AllExercises.exercise2(AllExercises.java:66)
普通に反数をとると、オーバーフローして同じ値になる
int n = Integer.MIN_VALUE; // -2^31 System.out.println(n); // -2147483648 System.out.println(-n); // -2147483648