-2
class Practice {
   public static void aMethod (int val) { System.out.println("int"); }
   public static void aMethod (short val) { System.out.println("short"); }
   public static void aMethod (Object val) { System.out.println("object"); }
   public static void aMethod (String val) { System.out.println("String"); }

   byte b = 9;
   Practice.aMethod(b); // first call My guess:don't know? it is short but why
   Practice.aMethod(9); // second call My guess:int correct 
   Integer i = 9;
   Practice.aMethod(i); // third call My guess: Object correct
   Practice.aMethod("9"); // fourth call My guess: String correct
}

Why does the method called with byte (b) as a parameter calls the method with short?

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
valer
  • 119
  • 3
  • 5
    Narrowest applicable type. `short` is closer to `byte` than `int`. – Louis Wasserman Oct 09 '17 at 18:47
  • Why would the compiler use an int for the parameter when it perfectly fits into a short? Just saves memory – Tyler Oct 09 '17 at 18:47
  • Yes i thought that too, that the reason would be from which type is closer, but i wasn't sure thanks @LouisWasserman. Damn and already -2 points oh well. – valer Oct 09 '17 at 18:59

1 Answers1

1

Java automatically chooses the best applicable method for your type.

In this case you are providing a byte, which is the smallest possible data type. The conversion for all data types would look like:

  • int - Possible, direct conversion from byte to int
  • short - Possible, direct conversion from byte to short
  • String - Not possible, byte is no String (usage of parsing-methods is needed)
  • Object - Possible, conversion from byte to Byte to Object

Java now automatically chooses the conversion to the narrowest type.

The conversion to Object goes in favor of int and short since it introduces a whole object, a huge overhead.

Finally short is chosen instead of int since it is smaller. A byte fits inside a short, which itself fits inside an int.

  • byte - from -2^(7) to 2^(7)-1
  • short - from -2^(15) to 2^(16)-1
  • int - from -2^(31) to 2^(31)-1

Ranges of data-types

(The difference is larger but then you wouldn't see anything in the image)

Zabuzard
  • 25,064
  • 8
  • 58
  • 82