5

In Double object documentation it only have two constructors, one taking a double value and one taking a string value. However, I just found that if we initialize it with other Number type objects it will also work. For example the following code will work:

Integer i = Integer.valueOf(10);
Double d1 = new Double(i);
Long l = Long.valueOf(100);
Double d2 = new Double(l);

So I'm wondering what's behind that? Autoboxing/unboxing would do the conversion between Double/double, Long/long and Integer/int, but I don't see why the constructor of Double will take other data types.

sabcyang
  • 53
  • 4
  • 1
    Because `int` to `double` and `long` to `double` are silent widening conversions. – shmosel Jun 22 '18 at 18:00
  • So what happened there is at compile time it's converted to new Double(i.intValue()) with unboxing and then at run time the int value is converted to double with the widening conversion? And the compiler is smart enough to know to convert Integer to int when the value required is double? – sabcyang Jun 22 '18 at 18:11

1 Answers1

4
Long l = Long.valueOf(100);
Double d2 = new Double(l);

The above code doesn't make a Double(Long) call, it makes the available Double(long) call, with the parameter being unboxed from Long to long. This only works because long is compatible with double.

So:

However, I just found that if we initialize it with other Number type objects it will also work.

No, you're still calling the same constructor that takes double as parameter.

As a side note, when you have a Number object at hand, rather call its doubleValue() method to get the primitive, instead of creating another object by constructing it using new Double(long)

ernest_k
  • 44,416
  • 5
  • 53
  • 99