|
| 1 | +package com.baeldung.overflow; |
| 2 | + |
| 3 | +import java.math.BigInteger; |
| 4 | + |
| 5 | +public class Overflow { |
| 6 | + |
| 7 | + public static void showIntegerOverflow() { |
| 8 | + |
| 9 | + int value = Integer.MAX_VALUE-1; |
| 10 | + |
| 11 | + for(int i = 0; i < 4; i++, value++) { |
| 12 | + System.out.println(value); |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + public static void noOverflowWithBigInteger() { |
| 17 | + |
| 18 | + BigInteger largeValue = new BigInteger(Integer.MAX_VALUE + ""); |
| 19 | + for(int i = 0; i < 4; i++) { |
| 20 | + System.out.println(largeValue); |
| 21 | + largeValue = largeValue.add(BigInteger.ONE); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public static void exceptionWithAddExact() { |
| 26 | + |
| 27 | + int value = Integer.MAX_VALUE-1; |
| 28 | + for(int i = 0; i < 4; i++) { |
| 29 | + System.out.println(value); |
| 30 | + value = Math.addExact(value, 1); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public static int addExact(int x, int y) { |
| 35 | + |
| 36 | + int r = x + y; |
| 37 | + if (((x ^ r) & (y ^ r)) < 0) { |
| 38 | + throw new ArithmeticException("int overflow"); |
| 39 | + } |
| 40 | + return r; |
| 41 | + } |
| 42 | + |
| 43 | + public static void demonstrateUnderflow() { |
| 44 | + |
| 45 | + for(int i = 1073; i <= 1076; i++) { |
| 46 | + System.out.println("2^" + i + " = " + Math.pow(2, -i)); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + public static double powExact(double base, double exponent) |
| 51 | + { |
| 52 | + if(base == 0.0) { |
| 53 | + return 0.0; |
| 54 | + } |
| 55 | + |
| 56 | + double result = Math.pow(base, exponent); |
| 57 | + |
| 58 | + if(result == Double.POSITIVE_INFINITY ) { |
| 59 | + throw new ArithmeticException("Double overflow resulting in POSITIVE_INFINITY"); |
| 60 | + } else if(result == Double.NEGATIVE_INFINITY) { |
| 61 | + throw new ArithmeticException("Double overflow resulting in NEGATIVE_INFINITY"); |
| 62 | + } else if(Double.compare(-0.0f, result) == 0) { |
| 63 | + throw new ArithmeticException("Double overflow resulting in negative zero"); |
| 64 | + } else if(Double.compare(+0.0f, result) == 0) { |
| 65 | + throw new ArithmeticException("Double overflow resulting in positive zero"); |
| 66 | + } |
| 67 | + |
| 68 | + return result; |
| 69 | + } |
| 70 | +} |
0 commit comments