In this Java article we want to learn about Java Method Signature, In Java method signature is a unique identifier that distinguishes one method from another. it consists of the method name, its parameter list and its return type.
Now let’s talk about Java method signature.
Method Name
Method name is the identifier used to call the method. it is typically written in camelCase and should be descriptive name that accurately reflects what the method does.
Parameter List
Parameter list is a comma separated list of parameters that the method takes as input. each parameter includes its data type, followed by its name. if the method does not take any parameters, than parameter list is empty. for example this method signature takes two parameters of type int and String.
1 |
public void printInfo(int id, String name) |
Return Type
return type specifies type of value that the method returns when it is called. if the method does not return anything, return type is void. for example this method signature returns a value of type int.
1 |
public int calculateSum(int num1, int num2) |
These are some examples of Java method signatures.
1 2 3 4 5 |
public void sendMessage(String message) public int calculateAverage(int[] nums) public String[] getNames(String firstName, String lastName) public void printDetails(String name, int age, String address) public boolean isEven(int num) |
Method Overloading
In Java method overloading allows developers to define multiple methods with the same name, but with different parameter lists. this is possible because the method signature includes both the method name and its parameter list. for example we can have two methods with the same name printDetails(), but with different parameter lists:
1 2 |
public void printDetails(String name, int age, String address) public void printDetails(String name, String occupation) |
In the above example two methods have the same name, but different parameter lists. this allows us to use the same method name for related methods and makes the code more readable and maintainable.
This is practical example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Main { public static int calculateSum(int num1, int num2) { int sum = num1 + num2; return sum; } public static void main(String[] args) { System.out.println("Sum is : " + calculateSum(4,7)); } } |
In this examplem we have a method named calculateSum that takes two integer parameters num1 and num2. this method returns an integer value, which is the sum of num1 and num2.
This will be the result