We have 2 overloaded methods, one has Integer and another has String as parameter. You are calling method with null. Which method will be called

Question:

You have 2 overloaded methods, doSomething, in below code. One takes Integer as parameter whereas another takes String. If you call it with null, which method will be called? What should be output of below code?

public class OverloadDemo {
 public void doSomething(String str){
  System.out.println("do something with String");
 }
 
 public void doSomething(Integer str){
  System.out.println("do something with Integer");
 }
 
 public static void main(String[] args) {
  OverloadDemo overloadDemo = new OverloadDemo();
  overloadDemo.doSomething(null);
 }
}

Answer:

Compilation error - The method doSomething(String) is ambiguous for the type OverloadDemo

Comments

  1. We can have solution for this problem is as follows:

    Solution1 : If we want to call method with Integer argument:

    public class OverloadDemo {
    public void doSomething(String str){
    System.out.println("do something with String");
    }

    public void doSomething(Integer str){
    System.out.println("do something with Integer");
    }

    public static void main(String[] args) {
    OverloadDemo overloadDemo = new OverloadDemo();
    Integer a = null;
    overloadDemo.doSomething(a);
    }
    }

    OR

    Solution2 : If we want to call method with String argument:

    public class OverloadDemo {
    public void doSomething(String str){
    System.out.println("do something with String");
    }

    public void doSomething(Integer str){
    System.out.println("do something with Integer");
    }

    public static void main(String[] args) {
    OverloadDemo overloadDemo = new OverloadDemo();
    String a = null;
    overloadDemo.doSomething(a);
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Data types and Literals in Java

How to define Auxiliary Constructor in case class in Scala

equals() method of Object class in Java