Java check if squaring integers causes overflow -


how can possibly determine if squaring integer causing overflow. number greater 46340 have square value greater maximum integer value of java. since java wrap numbers squaring 46431 gives -2147479015 whereas squaring 2147483647 gives 1, further complicates. unfortunately cannot in java 8 have thrown arithmeticexception. there other possible way of checking if squaring integer causing overflow or not?

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 43640:

2147395600 

output 43641:

exception in thread "main" java.lang.arithmeticexception: square overflow exception!     @ com.artofcode.test.securesquare.square(securesquare.java:9)     @ com.artofcode.test.securesquare.main(securesquare.java:15)     ... 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -