Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is long casted to double in Java?

SSCCE:

public class Test {

    public static void main(String[] args) {
        Long a = new Long(1L);
        new A(a);
    }

    static class A {
        A(int i) {
            System.out.println("int");
        }

        A(double d) {
            System.out.println("double");
        }
    }
}

Output:

double

There will be no compilation error printed, it works fine and calls double-parameter constructor. But why?

like image 700
SeniorJD Avatar asked Feb 06 '26 05:02

SeniorJD


2 Answers

It's down to the rules of type promotion: a long is converted to a double in preference to an int.

A long can always fit into a double, although precision could be lost if the long is larger than the 53rd power of 2. So your compiler picks the double constructor as a better fit than the int one.

(The compiler doesn't make a dynamic check in the sense that 1L does fit into an int).

like image 174
Bathsheba Avatar answered Feb 08 '26 21:02

Bathsheba


Converting long to int is a narrowing primitive conversion because it can lose the overall magnitude of the value. Converting long to double is a widening primitive conversion.

The compiler will automatically generate assignment context conversion for arguments. That includes widening primitive conversion, but not narrowing primitive conversion. Because the method with an int argument would require a narrowing conversion, it is not applicable to the call.

like image 23
Patricia Shanahan Avatar answered Feb 08 '26 20:02

Patricia Shanahan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!