Java 8 での算術オーバーフロー
Java 8 では算術オーバーフローを検出可能となるよっておはなしです。
Math クラスに算術オーバーフローを検出できるメソッドが追加されました。
ちょっとしたサンプルプログラムをのせておきます。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package jp.yucchi.exact; /**  *  * @author Yucchi  */ public class Exact {     public static void main(String[] args) {         System.out.println(Integer.MAX_VALUE + 1);         System.out.println(Integer.MIN_VALUE - 1);         try {             System.out.println(Math.addExact(Integer.MAX_VALUE, 1));         } catch (ArithmeticException ae) {             // G'catch! :p             ae.printStackTrace();         }         try {             System.out.println(Math.subtractExact(Integer.MIN_VALUE, 1));         } catch (ArithmeticException ae) {             // G'catch! :p             ae.printStackTrace();         }       } } | 
実行結果は次の通りになります。
-2147483648
2147483647
java.lang.ArithmeticException: integer overflow
at java.lang.Math.addExact(Math.java:790)
at jp.yucchi.exact.Exact.main(Exact.java:14)
java.lang.ArithmeticException: integer overflow
at java.lang.Math.subtractExact(Math.java:829)
at jp.yucchi.exact.Exact.main(Exact.java:20)
この他にも Java 8 で追加された便利なものがありますので興味のある方は API ドキュメントに目を通してみるといいですよ!
Hatena タグ: Java
TAGS: Java | 2014年1月29日5:00 PM | Comment : 0




 
 
 
 
