Java Methods


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. 

What is the purpose/use of the methods in Java?


The purpose of using methods in the Java program is to write the logic of the applications.
Let's see a simple example to understand the concept.
Program source code 1: In this example program, we are performing the addition of two numbers.
    class Addition{ // Declare two instance variables. int a=10; int b=20; System.out.println(a+b);// It is invalid syntax because inside the class, we cannot write directly the business logic of the application. Therefore, we declare the method inside the class and write the logic inside the methods. // Declaration of an instance method. void add(){ // Write logic of adding two number and print it on the console. System.out.println(a+b); }
From the above program, it is clear that methods are used to write business logic of the application or program.

Method declaration in Java


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 form to declare the method is given below.
method_modifier   return_type   method_name(Parameter_list) throws Exceptions {
      // Method body 

   }
Let's discuss some important points about the declaration of a 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 the method signature. 
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 the 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 a void method. There will be no return statement inside the method body.
If the return type is non-void but a data-type like an 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: 
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 the method declarations.
1. public void add(int a, int b);  // Here, add is the functionality name. It will execute whenever we will pass the input values of a and b. Once the functionality is completed, void represents don't return any value. The public is the access modifiers which represents that this method can be accessed from anywhere.
2. private int m2(); // m2 is the functionality 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 kinds 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)
Types of methods in Java

Predefined methods in Java


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.
For example,
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' see a simple example program.
Program source code 2:

    package predefinedMethods; public class SquareRoot { public static void main(String[] args) { System.out.println("Square root of 16: " +Math.sqrt(16)); } }
When you run the program, the output will be:
    Output: Square root of 16: 4.0
3. max() returns the greater of two values.
Program source code 3:
    package predefinedMethods; public class MaxValue { public static void main(String[] args) { int num1=20, num2=50, maxValue; maxValue=Math.max(num1,num2); System.out.println("Max value: " +maxValue); } }
    Output: Max value: 50

User-defined methods in Java


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.
We can declare two types of user-defined methods in an application.
1. Instance method: An instance method is used to implement behaviors of each object (also called instance) of the class. Since instance methods represent behaviors of the objects. Therefore, they are linked with an object. 
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:
     void m1(){
      // 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 the 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.
     }
Key points: 
1. An instance method (non-static 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


Executing the code inside the body of a method is called calling a method (or invoking a method). Instance method and static method are called differently.
Calling an Instance method: 
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:
 Syntax:
      instance_reference.instance_method_name(actual parameters); 
For example:
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 the msg() using 't' reference variable.
     t.msg();
Calling a Static method: 
 To call a static method, you use the dot operator with the class name.
For example:
The following code calls the m1() static method of Test class.
   Test.m1();
Key points: 
1. Instance method uses dynamic binding (late binding).
2. Class method uses static binding (early binding).    
Now just remember the below practical concept shown in the figure. You can make calling concept easy. 
Methods in Java,Types of methods in Java.
As shown in the above figure, there are two types of area in Java. First is instance area and second is the static area. 
Key points:
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 the 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 the main in java.
Program source code 4:
    package methodProgram; public class Addition { // Instance area/Non-static area. // Declaration of instance variables. int a=10; int b=20; // Declaration of instance method. void add(){ // Instance area/Non-static area. // Within instance area, we can directly call the instance variables from instance area(Same area) without using object reference variable. System.out.println("First number a = " +a); System.out.println("Second number b = " +b); // logic of addition. int x=a+b; System.out.println("Addition of two numbers x = " +x); // directly called. } public static void main(String[] args) { // Static area. // Create an object of the class. Addition ad=new Addition(); // Since we are calling an instance method from instance area within the static area. So Object reference variable will be used. ad.add(); } }
    Output: First number a = 10 Second number b = 20 Addition of two numbers x = 30

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:
    package methodProgram; public class Multiplication { int a=20; // Instance variable. // Declare static variables. static int c=40; static int d=50; void m1(){ // We can call directly static variables from instance area (Same area) without using class name. System.out.println("Third number c = " +c); System.out.println("Fourth number c = " +d); } static void multiply(){ // Static area. // We cannot call directly instance members/Non-static members in the static area. // System.out.println(x); // Invalid syntax. int mNum=c*d; System.out.println("Multiplication: " +mNum); } public static void main(String[] args) { // Call static method using class name. Multiplication.multiply(); } }
    Output: Multiplication: 2000
From the above program, One question arises which is asked by the interviewer in the interview.

Why cannot a static method directly access non-static members?


We cannot directly access non-static members from a static method. i.e, 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, the static members also loaded and it will look for the non-static members which are not in existence because we have not created an instance till now. Hence there is the 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 a 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.
Let's see a practical example program to understand the concept. 
Program source code 6:
    package methodProgram; public class Subtraction { int a=40; int b=50; void sub(){ int y=a-b; System.out.println("Subtraction of two number y = " +y); } static void subtract(){ // creating the object of the class within a static area to call the instance members. Subtraction st=new Subtraction(); st.sub(); } public static void main(String[] args) { subtract(); } }
    Output: Subtraction of two number y = -10
Program source code 7:
    package callingMethodExample; public class Test { void m1(){ m2(); // Instance method calling. System.out.println("m1 is calling"); } void m2(){ m3();// Static method calling. System.out.println("m2 is calling"); } static void m3(){ System.out.println("m3 is calling"); } static void m4(){ System.out.println("m4 is calling"); } public static void main(String[] args) { Test t=new Test(); t.m1(); m4(); Addition.sum();// here we are calling static method using the class name from outside the class Addition of program source code 2 } }
    Output: m3 is calling m2 is calling m1 is calling m4 is calling Fourth number d = 50
Let's understand the flow of execution diagram of this program as shown in the below figure.
Java Methods
As you can see the above image 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. 

Final words
Hope that this tutorial has covered almost all the important topics related to the methods in Java. All the practical example programs are very important to understand the concepts of methods. We hope that you will have enjoyed this tutorial.
Thanks for reading!
Next ➤ Main method