• Post Reply Bookmark Topic Watch Topic
  • New Topic

Clarification for Result  RSS feed

 
RaviShankar Guna
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class MainStaticEx {


public static void fun1(String s){
System.out.println("OK");
}

public static void fun1(Object obj){
System.out.println("Test");
}




public static void main(String args[]){

Throwable throwable = new Throwable();

fun1(null);

}

}


The Output is "OK" Why not "Test" Can any one tell please? I faced this in the interview
 
Tyson Lindner
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler goes for the more specific input parameters first if its valid. So since null is a valid input for String it will use that method.
 
Roger Sterling
Ranch Hand
Posts: 426
Eclipse IDE Fedora Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
null is a valid String type and the String function signature is the first one the JRE got to when it looked for a matching signature.
 
Paweł Baczyński
Bartender
Posts: 2085
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roger Sterling wrote:null is a valid String type and the String function signature is the first one the JRE got to when it looked for a matching signature.

I think an important question is why is String found first?

The answer is as JLS says:
JLS wrote:The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!