Add two integers, checking for overflow in Java

Description

The following code shows how to add two integers, checking for overflow.

Example


/*from w w  w  . j  a va2 s . c o m*/
import java.io.File;

public class Main {

  /**
   * Add two integers, checking for overflow.
   * 
   * @param x an addend
   * @param y an addend
   * @return the sum <code>x+y</code>
   * @throws ArithmeticException if the result can not be represented as an
   *         int
   * @since 1.1
   */
  public static int addAndCheck(int x, int y) {
      long s = (long)x + (long)y;
      if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
          throw new ArithmeticException("overflow: add");
      }
      return (int)s;
  }
  public static void main(String[] argv){
    System.out.println(addAndCheck(Integer.MAX_VALUE, Integer.MAX_VALUE));
  }  
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Data Type »




Java Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger