Skip to content

Why this code convert value to double instead to float?

I got a question. Why this code prints YYZ10.0 instead of printing XXZ10.0? The first constructor is A(int), then inside statement it returns false, so 9+1f should jump into A(float) constructor but instead it is going to A(double).

public class Main {
    public static void main(String[] args) {
        System.out.print(new A(011).fun()[1]);
    }
}

class A{
    double value;
    public A(int value){
        this(value >> 2 == 1 ? value+1.0 : value+1f);
    }
    public A(float value){
        System.out.print("XX");
        this.value = value;
    }
    public A(double value){
        System.out.print("YY");
        this.value = value;
    }
    public Object[] fun(){
        return new Object[]{new Object(), this};
    }
    public String toString(){
        return "Z"+value;
    }
}

Answer

If there are multiple overloads of a method, Java picks which one to call at compile time, not at run time. In this case, you’re calling the constructor via this. At compile time, Java decides which of the three constructors to call, and you can see that it’s going to have to be the one that accepts a double.

Java has to choose the constructor that accepts a double not just because it can handle both the double and float cases, but also because there is no float case. The ternary expression can only have one type. It’s not double sometimes and float sometimes; it’s always double.

Consider this statement:

____ result = value >> 2 == 1 ? value+1.0 : value+1f;

What type would you put in the blank? There’s no way to write “sometimes double, sometimes float.” It’s going to have to be double.