Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer out of range [duplicate]

Tags:

java

integer

I'm learning Java and I'm trying little programs. I have a problem with this one:

/*
 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.");
    }
}

The output is:

There are 1507852288 cubic inches in cubic mile.

I known the width in bits for a integer is 32, so the range is: -2,147,483,648 to 2,147,483,647

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

Thank you.

like image 311
Euriloco Avatar asked Dec 19 '22 03:12

Euriloco


2 Answers

When the result crosses the maximum values of an int then it is overflowed ie, integer overflow. You may better want to use long instead of int.

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

Arithmetic integer operations are performed in 32-bit precision. When the resultant value of an operation is larger than 32 bits (the maximum size an int variable can hold) then the low 32 bits only taken into consideration and the high order bits are discarded. When the MSB (most significant bit) is 1 then the value is treated as negative.

like image 188
Rahul Tripathi Avatar answered Jan 04 '23 18:01

Rahul Tripathi


When the result of an int operation (such as multiplication) is higher than the max int value, it overflows (i.e. doesn't fit within the 32 bits of an int variable), which means the value assigned to the int variable is incorrect. You have no reason to expect it to return the max int value if the correct result is higher.

If you want a correct result, use longs.

like image 39
Eran Avatar answered Jan 04 '23 17:01

Eran