How can be possibly determine if squaring an integer is causing overflow. All the number greater than 46340 have square value greater than maximum integer value of java. Since java will wrap the numbers squaring 46431 gives -2147479015 whereas squaring 2147483647 gives 1, so that further complicates. Also unfortunately I cannot do this in Java 8 which would have thrown ArithmeticException. So is there any other possible way of checking if squaring an integer is causing overflow or not?
4 Answers
public class SecureSquare {
private static final double SECURE_SQUARE_LIMIT = Math.sqrt(Integer.MAX_VALUE);
public static int square(int number) {
if (Math.abs(number) > SECURE_SQUARE_LIMIT) {
throw new ArithmeticException("Square overflow exception!");
}
return number * number;
}
public static void main(String[] args) {
int number = square(-46340);
System.out.println(number);
}
}
Output for 43640:
2147395600
Output for 43641:
Exception in thread "main" java.lang.ArithmeticException: Square overflow exception!
at com.artofcode.test.SecureSquare.square(SecureSquare.java:9)
at com.artofcode.test.SecureSquare.main(SecureSquare.java:15)
...
2 Comments
Also unfortunately I cannot do this in Java 8 which would have thrown ArithmeticException.
That is not correct. Integer overflow does not cause an exception. You only get an exception on integer divide by zero. This applies for all extant versions of Java.
AFAIK, there is no general test to see if a primitive integer arithmetic operation1 has caused an overflow.
For any specific case you can devise a test either based on a mathematical analysis or by doing an equivalent operation sequence using long or BigInteger.
For example:
int number = ...
int square = number * number;
long longSquare = ((long) number) * ((long) number);
if (square != longSquare) {
System.out.println("Overflow occurred");
}
(I think: there might possibly be edge cases in the above involving Integer.MIN_VALUE. If you use BigInteger then there should not be any edge cases.)
In this case, the test to see if it will cause an overflow is trivial, and there is no need for more complicated alternatives.
1 - In Java 8, some new "exact" integer arithmetic methods were added to the Math class. These throw ArithmeticException in the event of overflow. However, the behaviour of the primitive arithmetic operators has not changed.