Methods in Java
Methods in Java are the building block of a Java application. In Java, a method is a set of code used to write the logic of the applications which perform some specific task or operation.
When a method is called, it returns the value to the caller. It can also perform a task without returning any value. It can be called from anywhere. Each method has a single entry point and a single exit.
Why do we use methods in Java?
The purpose of using methods in the Java program is to write the logic of the applications. Let’s take an example program to understand the concept of using method in java programming.
Program source code 1: In this example program, we are performing the addition of two numbers.
From the above program, it is clear that methods are used to write the business logic of the application or program.
Method declaration in Java with Example
The methods must be declared inside the class. In general, methods have six fundamental parts such as modifiers, method name, return type, parameter list, exception list, and body.
The basic syntax to declare the method is as follows:
method_modifier return_type method_name(Parameter_list) throws Exceptions
// Method body
Let’s discuss some important points about the syntax of method.
1. The method modifier defines the access type of a method but it is optional to use. It may be declared as static, final, abstract, synchronized, or one of the access specifiers private, default, protected, and public. The public is the least restrictive access specifiers and private is the most.
2. If the method is abstract, the implementation is omitted and the method body is replaced with a single semicolon.
3. The return type defines the type of data that comes back from the method after calling it.
Method Signature in Java
The method name with the parameter list (number of parameters, type of parameters, and order of parameters ) is called method signature in java.
Examples of methods signature are:
add(int a, int b): Number of parameters is 2, Type of parameter is int.
m1(String name): Number of parameter is 1, Type of parameter is String.
sub(): No parameter.
Parameter list: The parameter list is a comma-separated list of zero or more parameter declaration. The basic form to declare the parameter list is:
parameter-modifier data-type parameter-name
The parameter-modifier may be final. If the parameter is final, it cannot be modified inside the method. The data-type may be int, float, char, double, etc. Each parameter-name must be a distinct name.
If there is more than one parameter, they are separated by commas. If there are no parameters, you include an empty pair of parentheses ().
The method parameter list makes it possible to pass the value to the method. It is declared inside the parentheses after the method name and the scope of the parameter list is inside method body but these are optional. The method may also contain zero parameters.
Method body: The method body is a block-statement which contain statements as well as the declaration of the local variables and local classes. The method body may also contain return statements.
If the return type is void, the method can perform a task without returning any value. Such a method is called void method. There will be no return statement inside the method body.
If the return type is non-void but a data-type like int, float, double, etc, the method will return a value. It will not be possible for execution to reach the end of the method body without executing a return statement.
Key points about Method Signature:
1. The return type and exceptions are not part of the method signature.
2. The method name should be functionality name related to logic.
3. The exceptions may be thrown by the methods. In this case, you can specify the exceptions.
Here are some examples of different types of method declaration in java.
1. public void add(int a, int b); // Here, add is the functionality/method name. It will execute whenever we will pass input values of a and b.
Once the functionality is completed, void represents don’t return any value. The public is access modifiers which represent that this method can be accessed from anywhere.
2. private int m2(); // m2 is functionality/method name with no argument. Once the functionality is completed, it must return an integer value. The private access modifier represents that it can be accessed only within the class.
3. protected int sub(int a) throws Exception. We will discuss more detail examples of the programs.
Types of methods in Java
Generally, there are two basic types of methods in Java but programmers can develop any kind of method depending on the scenario.
1. Predefined methods
2. User-defined methods (Programmer-defined methods)
Predefined methods in Java with Example Program
Predefined methods are those methods that are already defined in the Java API (Application Programming Interface) to use in an application. Java Programming language contains predefined classes that are organized in different predefined packages.
Within these predefined classes, there are located predefined methods.
In fact, Java has over 160 predefined packages that contain more than 3000 predefined classes.
These classes have many more thousands of individual predefined methods. All are available to the programmers via Java API.
1. print() is a predefined method present in the package java.io.PrintSteam. The print(“….”) prints the string inside the quotation marks.
2. sqrt() is a method of Math class which is present in package java.lang. It calculates the square root of a number. Let’ take an example program based on java predefined methods.
User-defined methods in Java with Example Program
User-defined methods are those methods which are defined inside a class to perform special task or function in an application. Such methods are called user-defined methods in java. It is also known as programmer-defined methods.
1. Instance method:
An instance method is used to implement behaviors of each object/instance of the class. Since instance methods represent behaviors of the objects. Therefore, they are linked with an object. An instance method is also known as non-static method.
So, without an object of the class, the methods cannot exist to perform their desired behaviors or task. It is allocated in the heap memory during the object creation.
Example of an instance method declaration:
// This area is called an instanced area/ Non-static area.
// logic here.
2. Static method:
When you declare any method with a static modifier, it is called static method. A static method is linked with class. Therefore, it is also known as a class method. It is used to implement the behavior of the class itself. Static methods load into the memory during class loading and before object creation.
Example of a static method declaration:
static void m2()
// This area is called a static area.
// logic here.
1. An instance method can refer to static variables (class variables) as well as instance variables of the class.
2. A static method can refer to only static variables.
How to Call Method in Java
Calling Instance method in Java:
There are two steps to call an instance method in java.
1. First, create an object of a class before calling an instance method of that class.
2. Second, call the method with a reference variable using the dot operator.
The syntax to call an instance method is as follows:
You can write the following code to call msg() instance method of Test class.
// Create an object of Test class and stores its reference in ‘t’ reference variable.
Test t = new Test();
// Call msg() by using reference variable “t”.
Calling Static method in Java:
To call a static method, we use dot operator with the class name.
The following code calls m1() static method of Test class.
1. Instance method uses dynamic binding (late binding).
2. Class method uses static binding (early binding).
Now just remember the below practical concept as shown in the following figure. You can make calling concept easy.
1. If you call instance members (variables or methods) from instance area within an instance area (i.e, same area), you don’t need to use object reference variable for calling instance variables or methods. You call it directly.
2. If you call instance variables or methods from the instance area within the static area (i.e, different area), you cannot call directly them. You will have to use object reference variables for calling them.
3. If you call static members (variables or methods) from the static area or instance area, we don’t need to use the class name for calling the static members. You can invoke directly.
4. When you want to call static members from the outside the class, static members can be accessed by using the class name only.
5. When a method is called in the program, the control of execution gets transferred to the called method.
How to call Instance method in Java from main
To call an instance method from the main method is very simple. Just create an object of the class and call the method using the reference variable. Let’s understand a simple example program to call an instance method from main in java.
Program source code 4:
How to call Static method from main in Java
Using the class name, you can directly call a static method from the main method. See in the example program.
Program source code 5:
From the above program, One question arises which is asked by the interviewer in the interview.
Why cannot Static method directly access non-static members?
We cannot directly access non-static members from a static method. That is, we cannot directly call instance members within a static area because there is a logical concept behind such restriction.
Since static members such as static variables, methods, or blocks are linked with the class and they get memory only once when the class is loaded but non-static members like instance variables, method, or block get memory after the object creation of the class.
Therefore, If we call any non-static members from the static area, it means that when the class is loaded in the memory, the static members also loaded and it will look for non-static members which are not in existence because we have not created an instance till now.
Hence there is ambiguity. That’s why we cannot call the non-static member from the static area. A non-static method can access static members in Java. we will discuss in the static tutorial.
Since static method cannot access directly the non-static members but if we create the object of the class within the static method, In this case, we can access non-static members within the static method.
Program source code 7:
Let’s understand the flow of execution diagram of this program as shown in the below figure.
As you can see in the above figure for program 7, we are calling m1() method but m1() method is calling m2(). So, the control of execution will go to m2() but m2() is calling static m3() method. After completing of m3(), once again the control of execution goes to m2().
After completion of m2(), the control of execution again goes to m1(). After that, static m4() method is called and printing the message on the console. Now the control of execution goes to class Addition of program source code 2 for calling the static method.
Hope that this tutorial has covered almost all the important topics related to the methods in Java with example programs. I hope that you will have understood this topic and enjoyed programming.
Thanks for reading!!!
⏪ PrevNext ⏩