Java Methods – Learn How to Declare, Define, and Call Methods in Java
We know that a program or a code is a set of instructions given to the computer. These instructions begin with some action and therefore, are also called executable instructions. In Java, the programs (executable instructions) are specified through methods or functions.
A method is defined as a sequence of some declaration and execution statements. These statements gather together to perform a specific task.This article will guide you to learn how to declare, define, and call a Java method in classes with syntax and examples.
Let us begin with the discussion of methods or functions in Java. But first, shouldn’t we know why do we use or need methods in Java? So let’s begin with the need for using methods in a Java program:
Why Java Methods?
There are three reasons why we use Java Methods they are as follows:
1. To cope with complexity:
When programs become more and more complex that is, when they gain in size, they become chaotic to handle.
One of the most powerful techniques to reduce this complexity is “Divide and Conquer” which is to take a complex task and divide it into smaller and easily understandable tasks. In Java, we accomplish this technique with the help of methods.
2. To hide low-level details:
Another essential use of methods is to create “black boxes”. At the level of using a method, we need not concern ourselves with how the method’s task is performed. We are actually treating a method as a black box because we accept the result without concern for its details.
This is illustrated in the below figure:
3. To Reuse code:
Once a task is packaged in a method, that method is available for accessing anywhere from the program. The method can be reused that is we can call it more than once in a program and also from other programs.
The practice of reusing is sometimes called “Write once, use many”.
The following diagram illustrates the reuse of method:
After knowing the need for functions, let us learn how to write/define methods in Java.
Methods in Java
In Java, a function or a method must be defined before it is used anywhere in the program. The general form of a function/method is given below:
[access-specifier] [modifier] return-type function-name (parameter list) { body of the function/method; }
We will discuss each of the elements in detail:
1. Access specifier
Access specifier is used to determining the type of access to the method. We have already discussed the access specifiers in our article of Java Access Specifiers. It can be either public or protected or private or default. It is optional to use an access specifier while defining a method.
2. Modifier
It can be static, final, synchronized, transient, volatile. A static method means it is called through an instance or object of a class but rather through the class itself. A final method means that the functionality defined inside this method can never be changed. Using a modifier is not compulsory.
3. Return-Type
It specifies the type of value that the return statement of the function returns. It may be any valid Java data type. If no value is being returned, we use the return type as void.
4. Function-name
The name of the function should be a valid Java identifier. The naming conventions generally followed for method names are:
- It should be meaningful
- It should begin with a lowercase letter. For names having multiple names, we use the camelCase naming convention.
For example:
printReportCard
getMarks
- The method name should generally begin with a verb followed by one or more nouns.
For example:
readData
findFile
calculateInterestAmount
5. Parameter list
The parameter list is a comma-separated list of variables of a function referred to as arguments or parameters. A function may be without any parameters and in this case, the parameter list is empty.
6. Method Body
The body of the Java method should be enclosed within curly braces{}. All the code for a method is written in its body within braces. All the operations and tasks are performed inside a Java method.
Following diagram is an example of declaring a method:
Here are some examples of functions:
public static int maxNumber( int a, int b) { //method body } void printStars() { System.out.println( “ * * * ” ); }
Code Snippet to write a method which returns a minimum of two numbers:
public static int minFunction(int num1, int num2) { int min; if (n1 > n2) min = n2; else min = n1; return min; }
Function Prototype and Signature
The first line of the function definition is the prototype of the function. A function prototype provides a description of function to the compiler by giving details such as the number and type of parameters and return type of the function.
The prototypes of the above-defined functions are:
public static int maxNumber( int a, int b)
void printStars()
public static int minFunction(int num1, int num2)
A function signature basically refers to the number and types of arguments. It is a part of the function prototype. The function signature of the above-defined functions are:
( int a, int b) (int num1, int num2)
Java Methods live in classes
The methods live inside classes. In order to exist within a Java program, a method has to exist inside a class. A Java program can have many classes and each class can have several methods.
And, one class in every program contains a main() method. The main() method is crucial as it tells the program where to start. It is a general rule to have one main() method inside one class only.
Calling a Method/Function in Java
To access or to use a method, we need to call it. A function is called (or invoked, or executed) by providing the function name, followed by the parameters being enclosed within parentheses.
When the program invokes any method, the program control automatically transfers to the function, the statements in the function body are executed, and then the control again returns to the calling code in any of the 3 situations:
- It completes all the statements in the method.
- It reaches a return statement of the method.
- If the method throws an exception.
Code to illustrate method declaration and accessing to them:
package com.techvidvan.methods; public class MethodDemo { //Program to find cube of a number using a method/function //Defining a function public static double getCube(double num) { double result = num * num * num; return result; } public static void main(String args[]) { double number = 7.5, cube =0; // creating an instance of MethodDemo class MethodDemo demo = new MethodDemo(); // calling getCube method using instance created in the above step cube = demo.getCube(number); //Control gets transferred to function definition System.out.println("The cube of " +number + " is: " +cube); } }
Output:
The void Keyword of a Method/Function
We have already used the void keyword as the return type in defining a method or a function. The void data type specifies an empty set of values and it is used to create a method that does not return any value.
A function with no return type can be declared as follows:
void function-name(parameter list);
In the following example, we are defining a void method findGrade(). This method is a void method and does not return any value.
While calling a void method, we cannot use the method in an assignment statement and expressions. So we must use a simple statement like this:
voidMethodName(parameters if any);
Code to illustrate void methods:
package com.techvidvan.methods; public class VoidMethodDemo { public static void findGrade(double marks) { if (marks >= 90) { System.out.println("Grade: A"); } else if (marks >= 80) { System.out.println("Grade: B"); } else { System.out.println("Grade: C"); } } public static void main(String[] args) { //Calling a void method findGrade(85); findGrade(98); findGrade(45); } }
Output:
Grade: A
Grade: C
Note: Only functions returning a value can be used in expressions and assignment statements.
Actual and Formal Parameters
After the discussion we have had so far, you have seen that there are parameters in the function definition and in the function call statement.
The parameters that appear in the function definition are called formal parameters. nd, the parameters that appear in the function call statement are called actual parameters.
Code to explain actual and formal parameters:
package com.techvidvan.methods; public class MethodDemo { //function definition public int getArea(int x, int y) //x and y are formal parameters { return x * y; } public static void main(String args[]) { int length = 10, width = 5, area =0 ; MethodDemo demo = new MethodDemo(); //Calling a function area = demo.getArea(length, width); //length and width are actual parameters System.out.println("The Area is: " +area); } }
Output:
Arguments to Functions/Methods in Java
When you pass arguments to functions, you can pass any value of a legal Java data type. That is, arguments to functions can be:
- Primitive data types that is, char, byte, short, int, long, float, double, boolean.
- Reference data types that is, objects or arrays.
Call by Value and Call by Reference
We can invoke or call a function in two manners: Call by Value and Call by Reference. Basically, these two ways of invoking functions are also known as Pass by Value and Pass by Reference, because they depict the way of passing arguments to functions.
In the following section, we will explore these two ways of passing arguments:
1. Pass By Value(Call by Value)
In the call by value method, the value of actual parameters gets copied into the formal parameters, that is, the function creates its own copy of argument values and then uses them. To understand this concept, let us take an example:
To test your grammar, your teacher purposely writes grammatically incorrect passage on her sheet and gives it to you for correction. So you copy down the given passage on your sheet and make corrections there.
This is an example of the call by value method. The passage given by the teacher is an actual parameter and you copy the passage on your sheet which is a formal parameter. Whatever changes take place are not reflected back to original values because the value of the original is copied onto another.
Thus, in the call by value, the changes are not reflected back to the original values.
Code to illustrate the Call by Value method of function invoking:
package com.techvidvan.methods public class CallByValue { public static int change( int a) { a = 20; System.out.println("Inside the method change(), value is now changed to " +a); return a; } public static void main(String[] args) { int original = 10; System.out.println("The original value is: " + original); change(original); System.out.println("The value after execution of function change() is: " + original); } }
Output:
Inside the method change(), value is now changed to 20
The value after execution of function change() is: 10
2. Pass By Reference(Call by Reference)
In the call by reference method, the called function creates a new set of variables and copies the value of arguments into them. Instead of passing a value to the function, we pass a reference to the original variable. The reference stores a memory location of a variable.
In the call by reference, the called method does not create its own copy of original values rather it refers to the original values, by different names (references). To understand this concept, let us take an example:
Your teacher gives the sheet of incorrect passage to you for correction and allows you to work upon the same sheet, then whatever changes you make, will be there on the original.
Thus, in the call by reference method, the changes are reflected back to the original values.
Note: In Java, all primitive types are passed by value and all reference types (objects, arrays) are passed by reference.
Code to illustrate the Call by Reference method of function invoking:
package com.techvidvan.methods; public class CallByReference { public static int original = 7; public static void change( CallByReference obj) { obj.original = 20; System.out.println("The Value inside change method: " +obj.original); } public static void main(String[] args) { System.out.println("The initial value is: " + original); //Creating a object or a reference CallByReference object = new CallByReference(); //Passing a reference to the method change(object); System.out.println("The value after execution of function change() is:" + original); } }
Output:
The value inside change method: 20
The value after execution of function change() is:20
Method Overloading in Java
When there are two or more than two methods in a class that have the same name but different parameters, it is known as method overloading. Java allows a function to have the same name if it can distinguish them by their number and type of arguments.
For example, the following functions are different in Java:
float divide(int a, int b){...}
float divide( float x, float y){...}
float divide (float a, int b) {...}
That is, the function divide() taking two int arguments is different form divide() taking two float arguments, and also from divide() taking both int and float arguments.
This is called function overloading.
Let us take an example discussed earlier for finding the minimum numbers of integer types. Suppose we want to find the minimum number of double types. Then, we can use the concept of method overloading. We will create two or more methods with the same name but different parameters.
Code to illustrate Method/function overloading:
package com.techvidvan.methods; public class MethodOverloading { public static void main(String[] args) { int intVar1 = 15; int intVar2 = 7; double doubleVar1 = 14.5; double doubleVar2 = 18.3; int result1 = minFunction(intVar1, intVar2); // same function name with different parameters double result2 = minFunction(doubleVar1, doubleVar2); System.out.println("Minimum Value of integer types = " + result1); System.out.println("Minimum Value of double types = " + result2); } // for integer public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } // for double public static double minFunction(double n1, double n2) { double min; if (n1 > n2) min = n2; else min = n1; return min; } }
Output:
Minimum Value of double types = 14.5
Note: Function overloading not only implements polymorphism but also reduces the number of comparisons in a program and thereby makes the program run faster.
Memory Allocation for Method Calls
A stack is used to implement the method calls. A stack frame is created within the stack area whenever we call or invoke a method.
After that, the local variables, the arguments passed to the method and value which is returned by this method, all are stored in this stack frame. This allocated stack frame gets deleted when the called method gets executed.
Summary
We can perform any task or operation with the help of methods. Methods are useful in reusing the code and reducing the complexity of the programs.
Coming to the end of this article, we have learned how to declare, define, and call/access Methods in Java and also in how many ways we can pass arguments to a Java Method. We also introduced the concept of method overloading.
This article will surely help you to understand the methods in Java very easily and properly.
Thank you for reading our article. If you have any queries or suggestions related to Java Methods, let us know by leaving a comment.