Search code examples
javaprimitive

Why does the method with byte parameter calls the method with short, why not int?


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?


Solution

  • 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)