Java Integer out of range

I learn Java and I try to make small programs. I have a problem with this:

/*
 Compute the number of cubic inches
 in 1 cubic mile.
*/
class Inches {
    public static void main(String args[]) {
        int ci;
        int im;

        im = 5280 * 12;

        ci = im * im * im;

        System.out.println("There are " + ci + " cubic inches in cubic mile.");
    }
}

Conclusion:

There are 1507852288 cubic inches in cubic mile.

I knew the width in bits for an integer 32, so the range is -2,147,483,648 to 2,147,483,647

Why is the conclusion 1507852288? It should be 2,147,483,647.

Thank.

+4
source share
2 answers

When the result crosses the maximum values ​​of int, it overflows, i.e. integer overflow . You can better use longinstead int.

You may be interested to read: Integer overflow and overflow in Java.

32- . 32 ( , int), 32 . MSB ( ) 1, .

+5

int (, ) , max int, (.. 32 int), , int . , int, .

, longs.

+5

All Articles