Class SafeMath


  • public final class SafeMath
    extends Object
    Math routines that check for overflow conditions.
    Author:
    AO Industries, Inc.
    • Method Summary

      All Methods Static Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      static int avg​(int... values)
      Computes the average of multiple values without overflow or underflow.
      static int avg​(int value1, int value2)
      Computes the average of two values without overflow or underflow.
      static byte castByte​(int value)
      Casts int to byte, looking for any underflow or overflow.
      static byte castByte​(long value)
      Casts long to byte, looking for any underflow or overflow.
      static int castInt​(long value)
      Casts long to int, looking for any underflow or overflow.
      static short castShort​(int value)
      Casts int to short, looking for any underflow or overflow.
      static short castShort​(long value)
      Casts long to short, looking for any underflow or overflow.
      static long multiply​(long... values)
      Multiplies any number of longs, looking for any overflow.
      static long multiply​(long value1, long value2)
      Deprecated.
    • Method Detail

      • castByte

        public static byte castByte​(int value)
                             throws ArithmeticException
        Casts int to byte, looking for any underflow or overflow.
        Throws:
        ArithmeticException - for underflow or overflow
      • castByte

        public static byte castByte​(long value)
                             throws ArithmeticException
        Casts long to byte, looking for any underflow or overflow.
        Throws:
        ArithmeticException - for underflow or overflow
      • castShort

        public static short castShort​(int value)
                               throws ArithmeticException
        Casts int to short, looking for any underflow or overflow.
        Throws:
        ArithmeticException - for underflow or overflow
      • castShort

        public static short castShort​(long value)
                               throws ArithmeticException
        Casts long to short, looking for any underflow or overflow.
        Throws:
        ArithmeticException - for underflow or overflow
      • castInt

        public static int castInt​(long value)
                           throws ArithmeticException
        Casts long to int, looking for any underflow or overflow.
        Throws:
        ArithmeticException - for underflow or overflow
      • avg

        public static int avg​(int value1,
                              int value2)
        Computes the average of two values without overflow or underflow.
      • avg

        public static int avg​(int... values)
        Computes the average of multiple values without overflow or underflow.
        Throws:
        ArithmeticException - When values is empty (due to resulting division by zero)