0

In this code

    public void display(int x, double y){
        System.out.println("Double");
    }
    public void display(int x, float y){
        System.out.println("Float");
    }
    public static void main(String[] args){
        prog01 p = new prog01();
        p.display(4,5); //First Output
        p.display(4,5.0); // Second Output
    }

The outputs are:

Float
Double

The second output is understandable, but why is 5 being cast to float when it should have given an error?

Ayush Basak
  • 449
  • 1
  • 7
  • 15
  • 2
    Why should it give an error? The value is widen implicitly. – akuzminykh Sep 08 '20 at 03:30
  • @akuzminykh Why didn't it widen to double? – Ayush Basak Sep 08 '20 at 03:32
  • Where does it say it should widen to `double` rather than `float`? What is the basis for your expectation? – user207421 Sep 08 '20 at 03:32
  • @AyushBasak Check out the limits `Integer.MAX_VALUE` and `Float.MAX_VALUE`; a `double` is just not necessary. – akuzminykh Sep 08 '20 at 03:38
  • In fairness, a `double` is needed to _precisely_ represent all values of type `int`. – Louis Wasserman Sep 08 '20 at 04:59
  • [Loss of precision - int -> float or double](https://stackoverflow.com/q/2781086/12323248) – akuzminykh Sep 08 '20 at 05:51
  • @akuzminykh The confusion that I had was why does implicit casting happen in function overloading. I was expecting it to give an error as 5 is an `int` and it can't find a function with the same parameter data types. – Ayush Basak Sep 08 '20 at 06:05
  • @AyushBasak Yes, I know. I've just added a reference about what Louis has mentioned, which I should have mentioned as well. – akuzminykh Sep 08 '20 at 06:12
  • 1
    @AyushBasak To your point: You can imagine the process of finding a method to be like so: 1) The compiler searches for a method that matches exactly those arguments and their types that you are passing. 2) If no method in 1) could be found, the compiler allows widenings for the search. In your case, the compiler finds the method `display(int, double)` because the `5` can be widen to `float`. – akuzminykh Sep 08 '20 at 06:15

1 Answers1

1

Widening Casting (Implicit) happens, byte -> short -> int -> long -> float -> double. Here you pass integer, Since it doesn't have long as a type, the next one is float. That's why it's giving you float

varman
  • 8,704
  • 5
  • 19
  • 53