Open In App

Method overloading and null error in Java

Improve
Improve
Like Article
Like
Save
Share
Report

In Java it is very common to overload methods. Below is an interesting Java program. 

Java




public class Test
{
    // Overloaded methods
    public void fun(Integer i)
    {
        System.out.println("fun(Integer ) ");
    }
    public void fun(String name)
    {
        System.out.println("fun(String ) ");
    }
 
    // Driver code
    public static void main(String [] args)
    {
        Test mv = new Test();
 
        // This line causes error
        mv.fun(null);
    }
}


Output :

22: error: reference to fun is ambiguous
        mv.fun(null);
          ^
  both method fun(Integer) in Test and method fun(String) in Test match
1 error

The reason why we get compile time error in the above scenario is, here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn’t happen unless we intentionally pass null value. For example see the below scenario which we follow generally while coding. 

Java




public class Test
{
    // Overloaded methods
    public void fun(Integer i)
    {
        System.out.println("fun(Integer ) ");
    }
    public void fun(String name)
    {
        System.out.println("fun(String ) ");
    }
 
    // Driver code
    public static void main(String [] args)
    {
        Test mv = new Test();
         
        Integer arg = null;
 
        // No compiler error
        mv.fun(arg);
    }
}


Output :

fun(Integer ) 

In the above scenario if the “arg” value is null due to the result of the expression, then the null value is passed to method1. Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that. Note: This problem wouldn’t persist when the overridden method arguments are primitive data type. Because the compiler will select the most suitable method and executes it.



Last Updated : 18 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads