How to do Method Overloading for Null Argument?
Last Updated :
21 Feb, 2024
In Java, Method overloading is a process in which we can define a method with the same name but with a different parameter in the same class. This is a feature of OOP (object-oriented programming). It helps increase the readability of the code, as we can use the same name for a function performing the same task but with different parameters or different datatypes.
Overloading for Null Argument
In Java, null is a valid value for the reference type (reference type is the data type that does not store the actual value but stores the address of the value, such as an array or an object). Therefore, they cannot be overloaded because they are a specified value for a reference type, not a particular data type.
- We require different types and numbers of parameters for overloading, not different values; therefore, we cannot perform overloading for a null argument.
- But we can handle the null value inside the overloaded methods by specifying the check for the null value in the methods.
Program to do Method Overloading for Null Argument in Java
In the below program, we have a method named overload1, which performs the printing of values of different types, and for each type, we have handled the null value explicitly.
Java
import java.io.*;
class GFG {
public static void overload1(Integer val) {
if (val == null ) {
System.out.println( "null value is handled" );
}
System.out.println( "The provided value is " + val);
}
public static void overload1(String val) {
if (val == null ) {
System.out.println( "null value is handled" );
}
System.out.println( "The provided value is " + val);
}
public static void main(String[] args) {
overload1( 5 );
overload1( "String" );
}
}
|
Output
The provided value is 5
The provided value is String
Explanation of the above Program:
- We have two
overload1
methods.
- First one accepts an
Integer,
and another one accepts a String
.
- Both methods check if the provided argument is
null
. If it is null
, it prints a message indicating that the null
value is handled. If it is not null
, it prints the provided value.
- In the
main
method, we call the overload1
method with an Integer
and a String
.
Share your thoughts in the comments
Please Login to comment...