class a {
public static void main(String arg[]){
int a=10000000;
int b=1000;
int c=a*b;
System.out.println(c);
}
}
The output is 1410065408. Can anyone help to justify it?
class a {
public static void main(String arg[]){
int a=10000000;
int b=1000;
int c=a*b;
System.out.println(c);
}
}
The output is 1410065408. Can anyone help to justify it?
Here is a tiny example what is actually happening, by using a loop. You will notice that the multiplication and the loop reduce the same result. Basicly this is happening because the multiplication exceeds the limit of Integer.MAX_VALUE
. If this limit is overflown, which means the calculated number is greater then this specific value, then your number will be equal to Integer.MIN_VALUE+theRestOfTheNumber
and the calculation will be going on with this number.
public static void main(String[] args) {
final int start_value = 10000000;
final int multiplier = 1000;
int result1 = 0, result2 = 0;
for(int i = 0;i<1000;++i) {
result1 += start_value;
if(result1 < 0) {
System.out.println("Overflow happend, starting at Integer.MIN_VALUE " + Integer.MIN_VALUE + " again. You did exceed the number " + Integer.MAX_VALUE);
}
}
result2 = start_value * multiplier;
System.out.println("RESULT1: " + result1);
System.out.println("RESULT2: " + result2);
}
O/P
Overflow happend, starting at Integer.MIN_VALUE -2147483648 again. You did exceed the number 2147483647
Overflow happend, starting at Integer.MIN_VALUE -2147483648 again. You did exceed the number 2147483647
Overflow happend, starting at Integer.MIN_VALUE -2147483648 again. You did exceed the number 2147483647
// MANY MANY MORE OVERFLOWS, 429 to be exact.
Overflow happend, starting at Integer.MIN_VALUE -2147483648 again. You did exceed the number 2147483647
RESULT1: 1410065408
RESULT2: 1410065408