Casting Java long and double sum gives always same result

Viewed 139

Please check this below Java Code:

public class Test{

  public static void main(String []args){
    long start = 1572544800000L;
    long end = 1635703200000L;
    int d = 10;
    int val = (int)(start + d + end + 0.0);
    // value 2147483647
    System.out.println("value: " + val); 
  }
}

Here if i change the value of d the output is always same 2147483647. which is Int max value. And if i change 0.0 to 0 the output is as expected.

Anyone can explain this behavior in Java

Thanks

2 Answers

The value of start + d + end is too large to be represented by an int, but it is not too large to be represented by a long or double.

By using + 0.0, you are making the type of the whole expression of start + d + end + 0.0 to be double. So overall you are casting a double to an int.

What happens when you convert a double that is too large to an int? The Java Language Specification 5.1.3 tells you the answer:

The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

If you use 0, however, the type of the expression start + d + end + 0 is still long, so you are converting a long to int, which is a different conversions. It happens like this:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

2147483647 = Integer.MAX_VALUE

try

double val = (double)(start + d + end + 0.0);

or,

long val = (long)(start + d + end + 0.0);
Related