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 Program to demonstrate Method Overloading // Handling Null Argument import java.io.*;
// Driver Class class GFG {
// Method Overloading for Integer
public static void overload1(Integer val) {
// Handling null value
if (val == null ) {
System.out.println( "null value is handled" );
}
// Printing the provided value
System.out.println( "The provided value is " + val);
}
// Method Overloading for String
public static void overload1(String val) {
// Handling null value
if (val == null ) {
System.out.println( "null value is handled" );
}
// Printing the provided value
System.out.println( "The provided value is " + val);
}
// Main method to test method overloading
public static void main(String[] args) {
// Calling overload1 with an Integer argument
overload1( 5 ); // Calls overload1 for Integer
// Calling overload1 with a String argument
overload1( "String" ); // calls overload1 for String
// Here we have provided the constant value, but when
// we take user input and the user gives null value for
// the variable, our program will not break because we
// have checked for null value
}
} |
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 aString
. -
Both methods check if the provided argument is
null
. If it isnull
, it prints a message indicating that thenull
value is handled. If it is notnull
, it prints the provided value. -
In the
main
method, we call theoverload1
method with anInteger
and aString
.