Why can I assign a number to an int which is too large and how does Java handle it?

StackOverflow https://stackoverflow.com/questions/23152167

  •  05-07-2023
  •  | 
  •  

Question

Usually, when assigning a number to an int larger than 2,147,483,647, then the code won't compile. But in the following snippet, result is larger than (2^31)-1, and it can still print. I know that the "correct" result is obtained by letting result be long , but how come this still prints something and what happens behind the scenes? Thanks in advance.

public class intAssigning
{
   static int n = 500000;
   static int i;
   static int result;
   //static long result;
   static boolean [] array = new boolean [n];

   public static void main(String[] args)
   {
      for (i = 0; i<n; i++)
      {
         array[i] = true;
      }

      for (i=2; i<n; i++)
      {
         if (array[i])
         {
            result+=i;
         }
      }
      System.out.println(result);
      //result with long: 124999750000
      //result with int: 445698416
   }
}
Était-ce utile?

La solution

If you try to assign a constant that is longer that the maximum size of the int you'll face a compiler error, and if you try to do this at runtime with a variable or some arithmetic manipulations that the compiler cannot detect the exceedance, it will over flow.

E.g. :

int i = Integer.MAX_VALUE;
i = i+1;
System.out.println(i);

output: -2147483648

Autres conseils

The value cannot be assigned, meaning it can't appear at the right of the assignment operator, because it's a compile-time constant and is known to be out of the integer bounds, so it's not even a valid int literal, in a sense (btw, beside assignment, it cannot appear in expressions, argument to method calls, and anywhere an int is expected)

However, when arithmetics are performed on integers inside the JVM, values can wrap and you'll have negative numbers or otherwise unrelated figures, depending on the particular operation (addition, multiplication) and operands involved.

This happens because the value overflows. This means when you do this

int i = Integer.MAX_VALUE;
i = i+1

then the value overflows, which means it goes back to the minimum value (Integer.MIN_VALUE) and continues from there. If it underflows, it goes back to the maximum value and continues from there.

Your other problem is a feature of the compiler. It prevents you to assign a "bad" value at the first place.

For your behind the scenes (with int 4bytes):enter image description here

It's eaiser to understand arithmetical operation with overflow if we use binary representation, consider this

    long l = 0x7FFFFFFF;  // 2147483647
    l = l + l;
    System.out.printf("%x %d %n", l, l);

    int i = 0x7FFFFFFF;  // 2147483647
    i = i + i;
    System.out.printf("%x %d %n", i, i);

output

fffffffe 4294967294 
fffffffe -2 

that is during int overflow bits above 32 are lost

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top