5

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.

Euriloco
  • 253
  • 1
  • 4
  • 9
  • How Integer clock works - http://stackoverflow.com/questions/14020097/java-the-range-of-int @ 1st answer – Estimate Jun 03 '15 at 10:30

2 Answers2

8

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.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
5

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • And in case it exceeds `long`, use [`BigInteger`](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html). – Mordechai Jun 03 '15 at 10:20
  • 1
    @MouseEvent i think questions is why its pointing wrong value? you have any reason? – subash Jun 03 '15 at 10:22
  • @subash If you understand how the internals of digital arithmatic works, this is easy to understand. Too long to explain it in a comment. – Mordechai Jun 03 '15 at 10:28