Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does misusing 1 instead of 1.0 from an int exceeding limits effect the value we get when we convert it to a double

This is the code I will be using…

public class foo {
    
    public static void main(String [] args){
        int a = (int) Math.pow(2, 30);

        double d = (a + a - 1.0);
        double f = (a + a - 1);

        System.out.println(d);
        System.out.println(f);
    }


}

The outputs are -2.147483649E9 and 2.147483647E9.

I do not understand why these values are printed out. It is my understanding that a + a will exceed the limits of int and therefore will switch to being negative, however, f is positive. I would expect both to be negative but f would be fractional whilst d would be an double with a point 0 due to integer division.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the first case a + a overflows to Integer.MIN_VALUE, then you switch to a double context with -1.0 which gives a negative number (Integer.MIN_VALUE - 1), since a double can hold a number smaller than Integer.MIN_VALUE.

In the second example you stay in an int context, which means that a + a overflows to Integer.MIN_VALUE, then subtracting 1 from that underflows and takes you back to Integer.MAX_VALUE.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading