Java Method overloading

18-Sep-2024

Learn how to create multiple methods with the same name but different parameters in Java



Let's understand the method overloading.

Suppose we need to perform a simple task which is addition of 2 number or 3 number or concat 2 string.

for this we can create 3 method.




public static void addTwoNumber(int a, int b){
// method body
}
public static void addThreeNumber(int a, int b, int c){
// method body
}
public static void concatTwoString(String a, String b){
// method body
}


But this is not a perfect way a to do this similar task. Another best way to do this is method overloading.


With the help of method overloading concept we can create multiple method with the same name but different parameter.




public static void addition(int a, int b){
// method body
}
public static void addition(int a, int b, int c){
// method body
}
public static void addition(String a, String b){
// method body
}


here each method parameter should different from one another. Now we don't need to call three another methods. we can call one method. The specific method will work based on the parameters sent while calling



addition(345,3453); // this will work for the first method
addition(345,3453, 3453); // this will work for the second method
addition("Hello ","World"); // this will work for the third method





Comments