Ad Infinitum Ad Infinitum - 1 month ago 12
Java Question

The effect of assigning parameter types on integer overflow

I am having difficulty of understanding the behavior of the java in the following scenario. For example, I have a multiply method, which simply multiplies two int value and print the result to the screen.

private static void multiply() {

int firstValue = Integer.MAX_VALUE;
int secondValue = 2; //double secondValue=2

double result = firstValue * secondValue;

System.out.println("Result is: " + result);
}


and because of the fact that Integer overflow, the result is -2. However, here the calculation result is assigned to a double, which accepts much bigger value than than multiplication of firstValue and secondValue.

My questions to this issue are;

1- Why is Integer overflow happening, although the result is assigned to a double?

2- When I change the type of secondValue to double (mentioned in the comment), the result is correct. Why do Java behave differently when the type of one of the multiplier is changed to double?

Answer

Java does not support target type casting.

private static void multiply() {

    int firstValue = Integer.MAX_VALUE;
    int secondValue = 2;
    double one = 1.0;
    double result = one * firstValue * secondValue;

    System.out.println("Result is: " + result);
}

Target Type casting means casting the value of result to the type of the variable it has to be assigned to.
So it does not know that the result has to be assigned to a double variable. In this case, int is the biggest data type, so the expression is calculated in int data type.
if you multiply it with double one, the expression is calculated in double type and the answer is correct.

Comments