Passing byte arguments to overloaded method

For finding the correct overload, the order is:

  1. by number of parameters
  2. boxing/unboxing
  3. variadic parameters

So

  • If b where a Byte the result would be Byte, Byte.
  • If passed would have been new byte[] { b, b }the result would be byte, byte.
  • If passed two byte b, a widening from byte to int to long is possible and the result is long, long.
  • When the long, long overload is removed, Byte, Byte results.

Please have a read of JLS chapter on conversions.

What is happening in your case is that during runtime, JVM chooses to perform a widening conversion byte -> long as this is conversion is safer because it is guaranteed that it does not cause RuntimeException.

Converting from byte to Byte also called boxing can result in OutOfMemoryError as the JVM has to allocate new objects onto the heap:

A boxing conversion may result in an OutOfMemoryError if a new instance of one of the wrapper classes (Boolean, Byte, Character, Short, Integer, Long, Float, or Double) needs to be allocated and insufficient storage is available.

Because of that, the safer byte -> long widening conversion is preferred.


So, if you go through the Java language specification for determining method signature at compile time it will be clear :

  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.

  2. 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.

  3. The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.

So, from the above steps, it is clear that in your case at first phase Java compiler will find a matching method which does doCalc(long a,long b). Your method doCalc(Byte s1, Byte s2) needs an autoboxing during the call so it will get less preference.

Tags:

Java