Domanda

I have 5 objects, a,b,c.d and e. The 5 objects hashcodes are as follows:

a => 72444
b => 110327396
c => 107151
d => 2017793190
e => 68574749

As you can see, all are positive values. However, when I sum them up into a long-variable, the result comes out negative:

long sum = a+b+c+d+e;
System.out.println(sum);     // prints -2098092366

The sum of these ints far below the max-value of long (9223372036854775807), yet it yields a negative result. Why?

È stato utile?

Soluzione

That happens because your variables are all ints, so you to int addition (which overflows), and then the final result is converted to long.

You can fix this by casting the first variable to long:

long sum = (long)a + b + c + d + e;

Altri suggerimenti

Integer values can be -2,147,483,648 to 2,147,483,647. The sum actually exceeds the max value and trancted for numeric overflow.

int x = 2147483647;
x++;
System.out.println(x);

It prints - -2147483648

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top