In the following code, I see no way in which T1 and T3 are different. Certainly my calculator says they are not.
public class longTest {
public static final long T1 = 24 * 60 * 60 * 1000 * 30;
public static final long T2 = 24 * 60 * 60 * 1000;
public static final long T3 = T2 * 30;
public static void main(String[] args) {
System.out.println(T1);
System.out.println(T2);
System.out.println(T3);
}
}
So why do I get output of:
-1702967296
86400000
2592000000
It’s not just System.out.println in this sample program either. When I have T1 in eclipse and mouse over the variable I get a gloss showing the same values.
java version “1.6.0_33” OSX
As paranoid-android says, it’s an
intoverflow issue. To understand why T3 is different, see below.All the numbers here are
ints so this is the same asThe
intpart overflows, so the implicit cast tolongarrives too late to avoid loss of precision.In
you have the same but its a smaller number that fits in both a 32 bit
int(31 bits for positive values) and in a 64 bitlong.This multiplies a
longby anintso does 64 bit arithmetic which is why it has a different value.It’s equivalent to
The implicit
longhere is early enough to prevent loss of precision.