4

I am new learner of Java. I am trying to understand the concept of passing argument in function and function overloading. I found few example on a java web site which where following code is given, my doubt is if null is passed to nh() then how "string" is displayed in output. Here is the code

public class CLI_APP
{
   public static void main(String[] args)
   {
      jh(null);
   }
   public static void jh(String s)
   {
      System.out.print("String");
   }
   public static void jh(Object o)
   {
      System.out.print("Object");
   }
}

In same code if below lines are added

public static void jh(Integer s)
{
   System.out.print("Integer");
}

I got an compilation error of

"Method is ambiguous"

WHY this happen?

user3599755
  • 93
  • 3
  • 11

3 Answers3

5
my doubt is if null is passed to nh() then how "string" is displayed in output

Overloaded methods are matched from bottom to top level of classes. Object class sits at the top level so it will be matched at the last. Having said that, null is first match to the String parameter method and a String can be null so this method is called.

If you also add the following method

public static void jh(Integer s)

to your code then jh(null) call introduces the ambiguity between Integer and String as both can be null.

Lean more here : Java Language Specification: Choosing the Most Specific Method

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

Integer and String both support null , so it generate ambiguity error at compile time, Now, if you use int instead of Integer then it will work because int not support null.

public class testJava {
   public static void main(String[] args)
   {
      jh(null);
   }
   public static void jh(String s)
   {
      System.out.print("String");
   }
   public static void jh(Object o)
   {
      System.out.print("Object");
   }
   public static void jh(int o)
   {
      System.out.print("Object int");
   }
}
bharatpatel
  • 1,203
  • 11
  • 22
0

Java always use the most specific method. In your first example it will print "String" instead of "Object" because String is more specific than Object.

In your second example, java can´t choose if null is better for Integer or String. You should cast your call or use primitives to remove your ambiguity.

This would work:

public static void jh(int s)
{
   System.out.print("Integer");
}

Also this would work:

jh((String) null);
felipecrp
  • 999
  • 10
  • 16