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

5
  • what do you mean by too large or too big Commented Nov 9, 2018 at 20:49
  • In Java plain code should be inside a method. Commented Nov 9, 2018 at 20:50
  • 1
    You can convert to long, do the calculation, and determine if the value is larger than Integer.MaxValue Commented Nov 9, 2018 at 20:51
  • 2
    Do you mean integer overflow instead of stack overflow? Commented Nov 9, 2018 at 20:51
  • Too large for what? If a is a long, float, or double, your calculations will not overflow. Perhaps if your code has said int a = 200000;, it wouldn't be ambiguous. Commented Nov 9, 2018 at 21:00

2 Answers 2

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!
Sign up to request clarification or add additional context in comments.

1 Comment

You only need to cast explicitly one operand to long, though.
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

1 Comment

I think this won't work, as the conversion to long is done after the int multiplication.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.