Method overload (double and float)

Asked

Viewed 283 times

6

Having 2 methods with the same name, but the types are different (double and float), the amount of parameter is the same, which of the methods Java will recognize first and why?

  • Java is not like weakly typed languages (i.e., Javascript), in which you can pass what you want (literally) to a function. You won’t get through one float to a function waiting for a double and vice versa.

1 answer

5


It depends on what value is used in your call. If the value is a float or any other that is automatically converted to float, will be the method you receive float, if the guy from argument of the method call is a double, call the method whose parameter is a double.

There is no such thing which will be called first. Except the question from a wrong premise.

class Classe {
     void metodo(float x) {
        System.out.printf("Float %f\n", x);
    }
     void metodo(double x) {
        System.out.printf("Double %f\n", x);
    }
}
 
class Ideone {
    public static void main(String args[]) {
        Classe classe = new Classe();
        classe.metodo(1);
        classe.metodo(1.0);
        classe.metodo(1.0f);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I was going to ask if, instead of double and float, it was float and Float (wrapper class) as the jvm would understand, but I remembered that, although there is Unboxing between the primitive type and wrapper class, they are different types and will prevail the same premise that you mentioned in the question... Or am I wrong?

  • 1

    You are right, in the background the internal value of the boxed type will be of the primitive type, even if its box is, of course, another type.

  • Yes, ignore the "call first", I meant "which of the methods it calls", my doubt is in reading the value, if when reading 1.0 the java will recognize as float or as double, since the two are of very similar types

Browser other questions tagged

You are not signed in. Login or sign up in order to post.