Ad Infinitum - 3 months ago 17

Java Question

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.

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.