Wednesday, 15 February 2017

Math : ToIntExactMethod

public class ToIntExactMethod {

    public static void main(String[] args) {

        // initialize long variables        long value1 = 123l;        long value2 = 3147483647l;

        // direct conversion from long to int        int intVal1 = (int) value1;        int intVal2 = (int) value2;
        // print the result        System.out.println("Direct conversion val1:"+intVal1);        System.out.println("Direct conversion val2:"+intVal2);

        // use Math.toIntExact()        try{
            intVal1 = Math.toIntExact(value1);            System.out.println("Using toIntExact val1:"+intVal1);        }catch(ArithmeticException e){
            System.out.println("value1 overflows an int");        }

        try{
            intVal2 = Math.toIntExact(value2);            System.out.println("Using toIntExact val2:"+intVal2);        }catch(ArithmeticException e){
            System.out.println("value2 overflows an int");        }


    }
}

No comments:

Post a Comment