3

int a = 200000;

double b = (double) (a*a);

I would like to be able to calculate if (aa) (integers) is already too large (stackOverflow) to hold in the variable; in this case I know that multiplying (aa) leads to an int that will not fit -> the number will be wrong;

What I do not understand is how I can calculate this off the top of my head. How can I see if a value will not fit in an int variable??

Is there a way to do this without using methods, by just using the plain code and common sense? ;-)

Best regards,

Wouter

Wouter Penris
  • 31
  • 1
  • 4

2 Answers2

5

Two possible solutions.

Catch exception thrown after a call to the Math.…Exact methods: Math.multiplyExact, Math.addExact, Math.decrementExact, and so on.

 int a = 200000;

  try {
      int result = Math.multiplyExact(x, y);

  } catch(ArithmeticException e) {
      //if you get here, it is too big
  }

Or, check against the constants for minimum and maximum possible integer values.

 long test = (long)a*(long)a;
 if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE)
    // Overflow!
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Justin
  • 1,356
  • 2
  • 9
  • 16
1

You could make use of the constant MAX_VALUE from the Integer wrapper class and cast to long instead (you will get a compile error if you cast to double but exceed it's range)

    int a = 200000;
    long b = (long) a * (long) a;
    if (b > Integer.MAX_VALUE) {
        // do something
    }

MAX_VALUE corresponds to the highest value an integer can be, (2^31)-1

PumpkinBreath
  • 831
  • 1
  • 9
  • 22