Methods in Java: Types, Method Signature, Example

Methods in Java are the building blocks 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 tasks or operations. In simple words, a method is a set of statements which are grouped together to perform a specific task.

In Java programming, a method is executed when it is called from another method. The main() method is the first method that is executed by JVM (Java Virtual Machine) in Java program.

If we want to want to execute any other method, we should call it from the main() method. When a method is called, it returns a value to the calling method. It can also perform a task without returning any value to the calling method.

We can call a method from anywhere in Java program. Each method has a single entry point and a single exit. A method can also call itself. We know this technique as a recursion in Java, which is useful for solving certain complex problems.

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 consider an example program to understand the concept of using methods in Java programming. In this example, we are performing the addition of two numbers.

Example 1:

class Addition 
{ 
// Declare two instance variables. 
   int a = 10; 
   int b = 20; 
   System.out.println(a + b); // It is invalid syntax because we cannot write directly the business logic of the application inside the class. 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); 
   }
public static void main(String[] args)
{
   Addition a = new Addition(); // Object creation.
   a.add(); // Calling method.
 }
}
Output:
       30

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


A method must be declared inside the class. In general, it has six fundamental parts such as modifiers, method name, return type, parameter list, exception list, and body. The general syntax to declare a method in a Java program is as follows:

method_modifier return_type method_name(Parameter_list) throws Exceptions
{
   // Method body 
   // Code to perform the desired task.
      return result; // return statement (optional)
}

Let’s understand 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 Java access modifiers private, default, protected, and public. The public is the least restrictive access modifier and the private is the most. Access modifiers determine the visibility of methods.

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 or value that the method returns when we call it.

4. The return statement allows us to return a value to the caller.

Method Signature in Java


The method name with parameter list (number of parameters, type of parameters, and order of parameters ) is called method signature in Java.
[adinserter block=”5″]
Look at the below some valid methods signature examples:

1. add(int a, int b) // Number of parameters is 2, and type of parameter is int.
2. m1(String name) // Number of parameters is 1, and type of parameter is String.
3. 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:

Syntax:
    parameter_modifier data_type parameter_name

In the above syntax, 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. 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 that contains statements as well as the declaration of the local variables and local classes. The method body may also contain return statement.

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 to caller method. It will not be possible for execution to reach the end of the method body without executing a return statement.


Key Points:

  • The return type and exceptions are not part of the method signature.
  • Method name should be a meaningful name related to logic or functionality.
  • Exceptions may be thrown by the methods. In this case, you can specify the exceptions.

Valid Method Declaration Examples

Here are some valid examples of different types of method declaration in Java.

Example 2:

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.

Example 3:

private int m2() {...}

Here, 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.

Example 4:

protected int sub(int a) throws Exception {...}

In this example, sub is the name of method which has a parameter “a” of type int. The method returns an integer value (int). It can throw an exception named Exception. We declare the method with the protected access modifier. This means that we can access the method within its own class, subclasses, and classes within the same package.

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.

  • Predefined methods
  • User-defined methods (Programmer-defined methods)

Two types of methods in Java: predefined methods and user-defined methods.

Predefined Methods in Java with Example


Predefined methods in Java 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.

Look at some examples below:

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.

Let’s take an example program where we will use sqrt() method of Math class to find out the square root of number 16.

Example 5: 

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 above program, the output will be:

Output: 
       Square root of 16: 4.0

3. max() predefined method returns the greater of two values. Let’s understand it with an example program.

Example 6:

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 with Example


User-defined methods are those methods in Java that are defined inside a class to perform a special task or function in an application. Such methods are called user-defined methods.

A user-defined method is also known as programmer-defined method. We can declare two types of user-defined methods in a program.

  • Instance Method
  • Static Method

Let’s understand both instance and static methods one by one with the help of examples.

Instance Methods in Java


An instance method is used to implement behaviors of each object/instance of the class. Since the instance method represents behaviors of the objects. Therefore, instance method is linked with an object.

An instance method is also known as non-static method. So, without creating 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.

Here is an example of an instance method declaration:

void m1()
{
  // This area is called an instanced area/ Non-static area.
  // logic here.
}

Static Method in Java


When you declare any method with a static modifier, it is called static method in Java. 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.

An example of a static method declaration is as follows:

static void m2()
{
   // This area is called a static area.
   // logic here.
}

Key Points: 

1. An instance method can refer to static variables (class variables) as well as for instance variables of the class.

2. A static method can refer to only static variables.

How to Call Method in Java


Executing code inside the body of a method is called calling a method (or invoking a method) in Java. Instance and static both methods are called differently in a program. Let’s understand one by one.

Calling Instance Method

There are two steps to call an instance method in Java.

  • First, create an object of a class before calling an instance method of that class.
  • Second, call the method with a reference variable using the dot operator.

The general syntax to call an instance method is as follows:

Syntax:
     instance_reference.instance_method_name(actual_parameters); 

Let’s take an example based on it.

Example 7:

package methodProgram;
public class Test
{
// Creating an instance method.	
   void msg() {
	  System.out.println("Instance method");
   }
public static void main(String[] args) {
// Creating an object of class.
   Test t = new Test();

// Call the method using reference variable t.
   t.msg();
  }
}
Output:
       Instance method

Calling Static Method

To call a static method, we use dot operator with the class name. The general syntax to call a static method in Java is as follows:

class_name.method_name(actual_parameters);

Key Points:

  • Instance methods uses dynamic binding (late binding) in Java.
  • Class methods uses static binding (early binding).

Now just remember the below practical concept as shown in the figure. You can make the concept of calling methods easy.

How to call method in Java from instance area and static area.

As shown in the above figure, there are two types of areas in Java. First is instance area and second is static area.

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 them directly.

4. When you want to call static members from 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 take a simple example program in which we will call an instance method from main in Java.

Example 8:

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, we will use object reference variable ad to call it. 
    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 class name, we can directly call a static method from the main method. Let’s take an example program where we will call static method using class name.

Example 9:

package methodProgram; 
public class Multiplication 
{ 
   int a = 20; // Instance variable. 

// Declare static variables. 
   static int c = 40; 
   static int d = 50; 

// Instance method.
   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 method
   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 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.

Static members such as static variables, methods, or blocks are linked with the class. Therefore, they get memory only once when the class is loaded in the memory. 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. Let’s see an example program based on the static method.

Example 10:

package methodProgram; 
public class Subtraction 
{ 
  int a = 40; 
  int b = 50; 

// Declaration of instance method.
  void sub() 
  { 
    int y = a-b; 
    System.out.println("Subtraction of two number y = " +y); 
  } 
// Declaration of static method
  static void subtract() 
  { 
  // creating the object of the class within a static area to call instance members. 
     Subtraction st = new Subtraction(); 
     st.sub(); 
   } 
public static void main(String[] args) 
{ 
   subtract(); // calling static method.
 } 
}
Output: 
      Subtraction of two number y = -10

Example 11:

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 of this program from diagram, as shown in the below figure.

Calling of instance and static methods in Java

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.

Advantages of Methods in Java


Methods are used to perform specific tasks, provide code reusability, and organize code logic within programs. There are several advantages of using methods in a program. They are:

(1) One of the main benefit of using a method is core reusability. Once a method is written, we can use it multiple times across different parts of a program, or even in different programs. This saves time and effort.

(2) Methods help in organizing code logically by breaking complex problems into smaller. This makes the program easier to read and maintain.

(3) They help avoid redundancy by allowing us to reuse code.

(4) A method helps to perform tasks on a variety of data inputs by passing method’s parameter.