Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How method overloading works here?

Tags:

java

I have two overloaded methods with parameters int and Integer respectively. when I call print method by passing 5, Why is it calling the first print method. How it identifies which method to call?

public class Main {

    public static void main(String[] args) {
        print(5);
    }

    static void print(int a) {
        System.out.println("Calling first print");
    }

    static void print(Integer a) {
        System.out.println("Calling second print");
    }

}
like image 228
Keerthy Keerthy Avatar asked Jan 27 '23 09:01

Keerthy Keerthy


2 Answers

public class Test
{
   static void print( int a )
   {
      System.out.println( "Calling first print" );
   }

   static void print( Integer a )
   {
      System.out.println( "Calling second print" );
   }

   public static void main( String[] args )
   {
      print( 5 );
      print( new Integer(5) );
   }
}

print( 5 ); Will output Calling first print because you are passing 5 which is a premitive.print( new Integer(5) ); Will output Calling second print because you are passing 5 as integer object so method static void print( Integer a ) having higher priority.

like image 127
Sudhir Ojha Avatar answered Feb 02 '23 12:02

Sudhir Ojha


Why does the compiler bind a primitive variable passed as parameter to the method with a primitive declared parameter ?
Because it makes sense and the JLS goes in this way.
That is rather the reverse that would be very surprising : you pass an int and the compiler chooses the method that boxes it to Integer instead of selecting the method that has an exact match : an int parameter.

Similarly, when you invoke print(Integer.valueOf(5)) where Integer.valueOf() returns an Integer and not an int, the method selected by the compiler is the method with the Integer as parameter.

How it identifies which method to call?

In Java, the compiler chooses the most specific method that it founds according to the type declared of the passed parameter. Here it is straight. Things are less obvious as the match is not direct.

15.12.2.5. Choosing the Most Specific Method should interest you.

like image 26
davidxxx Avatar answered Feb 02 '23 10:02

davidxxx