19

I was trying to understand java overloading rules. Everything seems fine except following,

public static void main(String[] args) {
    long aLong = 123L;        
    foo(aLong);
}

private static void foo(double aDouble) {
    System.out.println("Foo aDouble");
}

private static void foo(Long aWrapperLong) {
    System.out.println("Foo Wrapper Long");
}

private static void foo(int anInt) {
    System.out.println("Foo Int");
}

private static void foo(float aFloat) {
    System.out.println("Foo Float");
}

Why does the call resolve to foo(float aFloat). I understand the following from JLS,

This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable There may be more than one such method, in which case the most specific one is chosen.

I have intentionally used Wrapper Long here and not primitive long. Primitive long being 64 bit in size does not end up in foo(double aDouble) but 32 bit float foo(float aFloat).

The question Why does Java implicitly (without cast) convert a `long` to a `float`? further clarifies the answer to this question.

Community
  • 1
  • 1
GauravJ
  • 2,162
  • 1
  • 22
  • 28
  • Very good question, this is especially important because not all values above 16777215 can't be represented in a float without precision loss. For instance 16777217, will be rounded to 1.6777216E7 when converted to a float. – Klaus Groenbaek May 05 '17 at 05:23
  • About the edit : a 64bits long has nothing to do with a 64bits double. See [about mantissa](http://stackoverflow.com/questions/24273994/how-do-you-get-the-mantissa-of-a-float-in-java) to see the difference. – AxelH May 05 '17 at 05:30

4 Answers4

15

This is because of the 'most-specific' rule in JLS #15, which in turn refers to JLS #4.10, which in turn refers to #4.10.1, which states:

The following rules define the direct supertype relation among the primitive types:

  • double >1 float

  • float >1 long

  • long >1 int

  • int >1 char

  • int >1 short

  • short >1 byte

where "S >1 T" means "T is a direct subtype of S", as per JLS #4.10 immediately above this section.

So in this case, in the absence of a direct match on long, and before looking at auto-boxing, the compiler chooses the nearest available supertype, which is float, by the rules above.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483
  • If that was the case, should it not have picked the `int` method ? – Klaus Groenbaek May 05 '17 at 05:22
  • 2
    @KlausGroenbaek No, because the original argument is a `long`, which is where the thing starts. Calling the `int` overload would require a cast. – user207421 May 05 '17 at 05:24
  • 2
    @EJP `where "S >1 T" means "S is a direct subtype of T"`, Is not the other way around? From the link, `T is a direct subtype of S, written T <1 S, if S >1 T.` – GauravJ May 05 '17 at 05:32
  • 1
    "the compiler chooses the nearest available subtype" do you mean nearest available supertype? – Michael May 05 '17 at 13:25
  • @Michael No I don't. It wouldn't choose `int` for example if the actual parameter was `long`. – user207421 May 06 '17 at 01:10
  • @EJP **"S >1 T" means "T is a direct subtype of S"** and **"long >1 int"**. Substituting in you get "int is a direct subtype of long", which becomes "long is a supertype of int". So if the parameter was an int, it would choose the nearest *supertype* which is long. – Michael May 06 '17 at 15:06
7

Quote from JLS:

The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1).

The remainder of the process is split into three phases, to ensure compatibility with versions of the Java programming language prior to Java SE 5.0. The phases are:

  1. The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.

  1. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase. ...

Edit: about choosing float instead of double:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

The first phase of overload resolution will choose two of these four methods

private static void foo(double aDouble) 
private static void foo(float aFloat) 

because first phase doesn't permit boxing/unboxing (Long) and you cannot pass long to method with int parameter without explicit casting. Than the most specific method will be choosen. In this situation float method would be interpreted as most specific than double.

DAle
  • 8,990
  • 2
  • 26
  • 45
  • 2
    But why was `float` chosen over `double`? – user207421 May 05 '17 at 05:06
  • Added to the answer – DAle May 05 '17 at 05:17
  • [JLS 5.1.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.2) says _long to float or double_ so looks like the rules say float is preferred to double for conversion. Edit: source for that rule is [JLS 4.10.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.10.1) – prunge May 05 '17 at 05:21
  • 3
    This would be a better answer if you showed how the language rules were applied in the given situation, instead of just dumping parts of the JLS on us with no explanation. Language standards are usually written in a way to make them mathematically precise, not in a way to be easily understood by a non-compiler-writer. Furthermore, even though I am a former compiler maintainer who is used to language standards, I don't see how the parts you quoted show why `float` is chosen. I suspect there are other important parts of the JLS you didn't quote. – ajb May 05 '17 at 05:21
4

Conversion has precedence rules. It will choose widening over boxing.

So, in this case compiler searches for method which can accept the parameter bigger(closest possible bigger) than long primitive data type as an argument, which is float.

If you remove methods foo(double aDouble) and foo(float aFloat) from your posted example, then compiler will perform boxing and choose foo(Long aWrapperLong)

adi
  • 304
  • 2
  • 11
2

Widening has precedence before autoboxing for overloading. Wrapper classes for primitives (Integer, Long & so on) were not introduced in java since the very beginning and because java supports backward compatibility it should execute code which was written in one java version in the same way in newer versions.