Understanding The Java Methods

Understanding The Java Methods
Understanding The Java Methods


Consider a situation where you are writing a Java program for calculating the percentage of every student in the Computer Science Department of your university. There are approximately 100 students and for the sake of simplicity, let’s consider that you only need to sum the marks of five subjects for each of the 100 students.

So, in a nutshell, you are required to display the percentage of each student by their marks. Sounds quite simple right?

All you need to do is sum up the marks obtained in each subject and then divide by the total marks for a single student. Now for 100 students, this task needs to be repeated, which means executing the same logic 100 times!

Here Java Method comes to the rescue. Using functions in the above example will allow us to write the logic for percentage calculation once and use it 100 times.

A method is a group of statements or a block of code that performs some specific operations on data passed to it and may or may not return a result.

Methods provide “Write Once, use many times” functionality. Structuring your code using methods provides better readability and helps in the reusability of code. There is no need to retype the same code over and over again.

A method is executed only when it is explicitly called upon, bypassing specific parameters as arguments. 

How is a method declared?

The method declaration is composed of the following main parts:-

  • Modifier: This defines the access type of the method. There are four types of access specifiers in Java: public, protected, private, and default.
  • The return type: The data type of the value being returned by the method. It may be int, String, double, or maybe void. In the case of void methods, the method executes completely, and nothing is returned.
  • Name of Method: The name of the method being referred to. In general, well descriptive and short method names are preferred.
  • Parameter List: This is the comma-separated list of the input parameters being given to the function. If there are no parameters to be passed, empty parentheses will be used along with the method name
  • Method Body: The block of code or the group of statements that must be executed inside the method.

Let’s try to understand the various elements of method declaration using an example as illustrated below:

The starting point of the Java program i.e. public static void main(String[]args) is too a method and the most crucial one. Let’s try to break down the most important method of Java programming Language

blog banner 1
  • public: It’s an access modifier. Since it is public, that means it is globally accessible. It is made public so that Java Virtual Machine can invoke it from outside the class. Making it private will result in an error.
  • static: It’s a Java keyword that makes it a class-related method. The main method is intentionally made static so that it can be invoked without instantiating the class.
  • void: It is also a keyword and is used to specify that the main method will not return anything to the user.
  • main: This is the name of the method. The JVM looks for the main method as the starting point of the Java program
  • String[] args: This is the argument being passed to the main method and stores the Java command line arguments.
public class JavaMethod 
    public static void main(String[] args) 
        System.out.println("Java Method");

Every method has a Method Signature associated with it. Method signature includes the method name and the parameters list.

Naming Conventions for Java Methods

  • The name of the Java method must be a verb and always start with a lowercase letter.
  • In the case of method names with multiple words, the first name must be a verb followed by an adjective or noun. The first letter of each word except for the first word must be uppercase.

Now you know how to create a method and the various terminologies associated with the creation of a method. But how to use that method? For using a method, it needs to be invoked, i.e., called from somewhere within the main method, inside another method, etc.

Calling a Method

Every java program is executed sequentially, i.e., one instruction is executed only after the previous one has completed its execution. Whenever the method is called, the control gets transferred to the method. The control is returned to the main method or to the caller when:

  • An exception is raised
  • All the statements inside the method have been successfully executed
  • A return statement is encountered in the method.

The example below illustrates how to define a method that may or may not return a value and call it within the main function.

public class JavaMethod
    // This function will return a value that is
    // maximum of the two given values
    public static int findMax(int a, int b)
        if(a > b)
            return a;
        return b;
    // This method calculates the grade of
    // student based on the marks. The method will not return 
    // anything and will execute till completion
    public static void findGrade(int marks)
        if(marks > 30 && marks < 50)
        else if(marks > 50 && marks < 70)
        else if(marks > 70 && marks < 85)
    public static void main(String[] args) 
        System.out.println("Studying about Java Method");
        int first = 99;
        int second = 45;
        // calling a method that returns something
        int res = findMax(first, second);
        // Calling a method that does not returns something

Note that the methods that do not return any value are called void methods. In the example above, findGrade() is a void method.

Types of Methods

There are two types of methods in the Java programming language.

  • Predefined Methods: The methods that are already defined in Java class libraries are called predefined methods.These methods can be used directly by calling them and by adding the necessary package imports. Note that whenever a predefined method is called, a series of code runs behind the scenes to execute that method

Examples: print() method defined in java.io.printStream class
max() method defined in java.util.Math class

The necessary condition for using an in-built method is to import the required Packages as shown in the below examples.

import java.lang.Math;
import java.lang.String;
import java.util.Arrays;
public class JavaMethod
    public static void main(String[] args) 
       // Number Methods
       System.out.println(Math.pow(5, 4));
       // String Methods
       String name = "Java Methods";
       int len = name.length();
       // Array methods
       int[] arr = {10, 20, 30, 40, 50, 60};
       System.out.println(Arrays.binarySearch(arr, 67));
       int[] arr1 = {10, 15, 45};
       System.out.println(Arrays.compare(arr, arr1));
  • User-defined Methods – The methods that are created by the programmer to provide code reusability are called user-defined methods

Examples: findGrade() method implemented above.

Let’s look at an example of User-defined methods wherein in one method primitive data types(int, float, string, etc)  will be passed as parameters, and in other an object data type(arrays, LinkedList, etc)  will be passed as a parameter.

public class TypesOfMethod{
   // Passing primitive data as a parameter
    public static int areaSquare(int side)
        int area = side * side;
        return area;
   // Passing object data as parameter
    public static int arraySum(int[] arr, int size)
        int sum = 0;
        for(int i = 0; i < size; i++)
            sum = sum + arr[i];
        return sum;
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 5, 6};
        System.out.println(arraySum(arr, arr.length));

Methods can also be classified into the following types:

  • Static Method: Methods belonging to a class and not an instance of the class. There is no need for object creation while accessing the static methods.
  • Instance Method: It’s a non-static method that belongs to the class and its instance. It’s necessary to create an object to access the instance method.

The below program illustrates the difference between static and instance methods.

public class TypesOfMethod{
    // Instance Method
    public void display()
        System.out.println("I am an instance Method");
    // Static Method
    public static void showMessage()
        System.out.println("I am static method");
    public static void main(String[] args) {
  • Factory Method: Methods that return an object to the class where it belongs. All static methods are factory methods.
  • Abstract Method: Methods that do not have any code are called abstract methods. The method body is declared later in the program.

An abstract method can only be declared inside an abstract class

Note: Static methods can only access static data members and static methods of the same or another class.Whereas an instance method can access both static and instance methods and data members.

Method Overloading

It’s possible to have multiple methods with the same name in the same class but different parameters (maybe different number of parameters or maybe different data types of parameters) and different functionalities. This is called method overloading.

When more than one method of the same name is created in a class, this method is called an overloaded method.

public class TypesOfMethod 
    public static void cube()
        System.out.println("No parameter method is called");
    public static void cube(int num)
        System.out.println("Method with integer argument is called");
        int cube_value = num * num  *num;
    public static void cube(double num)
        System.out.println("Method with double argument is called");
        double cube_value = num *num * num;
    public static void main(String[] args) 
        cube();  // No parameter method called
        cube(7); // Integer parameter method called
        cube(6.0); // double parameter method called

This will produce the following result:

No parameter method is called
Method with integer argument is called
The method with double argument is called

In the above example, we do not explicitly specify the integer method, float method, or no argument method. The Java compiler itself is capable of performing the appropriate method call for an object based on the data type of the argument/parameter passed to it. 

Memory Allocation for Method Calls

Whenever a java program is compiled, the JVM first looks for the main() method. Inside the main method, instructions are executed sequentially. There may be one or more than one method called inside the main method.

The Java Virtual Machine(JVM)  divides the memory into stacks and heaps. The stack memory may grow and shrink as and when required. Any variable defined in the stack lasts as long as the scope of the method exists. To keep track of the method calls, they are implemented using a Stack. 

Whenever a method is called, a new stack frame is created. Within the stack frame, all the variables and the arguments passed to it are stored. The stack frame would be deleted as and when the execution of the method is done.

(Diagram showing how new stack frames are created below the existing stack frames)

Frequently Asked Questions

What are the methods in Java?

A method in Java is a block of code or a group of statements that performs a specific operation and is executed only when it is being explicitly called. The method may or may not return a value and may or may not have parameters passed to it as arguments.

public static void display()
System.out. println(“Java Methods”);

The above method, when called inside the main method, will print Java Methods as Output.

How can we call a method in Java?

A method needs to be called to leverage its functionality as and when required. There are different ways of calling a method depending on whether it returns a value or not.

How many main methods are there in Java?

There is only one main method, written as public static void main(String[] args), from which the execution of the program begins in a class.

However, there can be more than one method with the name main in case of method overloading bypassing no arguments or a different set of arguments. The below program will compile successfully.

public class Practice {
public static void main(String[] args) {
System.out.println(“The main method with the String[] args argument passed”);
public static void main() { System.out.println("The main method with no arguments passed"); }

What are String [] args in Java?

String[] args in Java is used for storing command line arguments, and it’s an array of type java.lang.String class.

Key Takeaways

This article aimed to explain the Java Method and the different types of methods in the Java programming language. With this done, you can now figure out more details regarding the Java Methods, how using different access modifiers change the program and some exciting concepts about Java programming on CodeStudio.

Don’t forget to upgrade yourself using various problems available on CodeStudio and read about the interview experiences of scholars placed in top product-based companies.

By Manvi Chaddha