Architecture & DesignA Deeper Look at Java Methods

A Deeper Look at Java Methods

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

A Java application generally consists of a large set of instructions. It is practically unmanageable if it is written as a single piece of code strewn across the program. Java methods provide a way to construct a large program assembled from small pieces of code called modules. Java methods emphasize the divide and conquer principle facilitating design, implementation, operation, and maintenance of a large program. Java methods exist along with Java objects, but there is an exception with static methods. The method designated as static is independent of the Java object and can be invoked without creating one. This article shall explore the intricacies of methods and how things actually work in Java.

Program Modules

When we talk of program modules, a Java program is a combination of methods, classes, and packages. The API library that comes with Java is nothing but a predefined set of these modules. Related methods are grouped into a class and, similarly related classes are grouped into a package. Methods are also called functions or procedures that represent a set of tasks into self-contained units. The design of a method must be well defined to perform a single unit of task because, apart from modularizing a program, it also leverages code reusability, an important principle of software engineering. A cohesive module is not only easy to test and debug, but also easy to maintain in the long run.

A method is invoked by a call and returns back to the caller upon completion of a task. Analogically, a method can be thought of as an employee who specializes in a particular task and who is summoned by the boss to execute a task. The boss may or may not provide some data based on which execution may be performed. However, the employee must report back to the boss with or without some information, depending on the speciality of the agent. The boss can employ several employee each specializing a particular task. Sometimes, one employee may need the help of another employee. In such a case, they can invoke a call to utilize each other’s functionality.

Deep1
Figure 1: An authority chart

Method Signature

As should be obvious, like the employee, each method must be distinct by its signature. A signature of a method is represented by its name, number, and type of parameters it takes. For example, a method declared as:

int max(int a, int b)

is distinct from a method declared as:

int max(int a, int b, int c)

or:

double max(double[] arr)

Although the method name, max, is same in all three cases, it is the number and type of the parameter that distinguishes one from another.

Note: Methods having the same name but different types/numbers of parameters are called method overloading. In the preceding example, the max method is a rudimentary illustration of this concept as well.

A function also will have a return type denoted by primitive data types such as int and double used in the previous functions. The return type can also be a class object. The return types denote that the method will return a value of the mentioned type to the caller.

static Methods

Methods declared as static are an exception to the generic rule of methods. As we know, methods execute in response to a method call on specific objects. static methods are independent of the object and do not require an object to call them. They are called class methods, meaning, they are attached to the class in which it is declared as a whole. Generally, classes that require a method to perform a common function declare it as static. For example, there are numerous static methods declared in the java.lang.Math class, such as abs, to find the absolute value of the argument passed, the max method to get the greater of two values, and so forth.

public class MyClass{

   public int findMax(int a, int b){
      // ...
   }

   public static int findMin(int a, int b){
      // ...
   }
}

Invoking findMax requires creating a MyClass object first.

MyClass mc=new MyClass();

and then we can call

int result=mc.findMax(10,20);

the findMin method, on the other hand, is a static method. As a result, we can invoke it simply by its class name, as follows:

int result=MyClass.findMin(10,20);

Why Is the main Method Declared static?

Perhaps the finest example is the declaration of main as a static method. The reason is this: When JVM is called by the java command, it attempts to invoke the main method by the class name. If, however, main is not declared as static, JVM needs to create an object of the class to make a call. For example, to execute the following program:

public class MyClass{

   public static void main(String[] args){
      // ...
   }
}

we provide the class name as an argument to the java command with, say, arguments as:

$ java MyClass "Hello" "World"

The JVM loads the class identified by the class name (MyClass) and uses it to invoke the main method. The list of command line arguments (“Hello” and “World”) is passed to the main method  by the JVM. A Java program usually consists of several classes. Every class can contain a main method of its own. JVM calls the main method of the class used to execute the application. This is an important concept because a programmer takes this as an advantage to test each class individually by writing a main method specific to that class.

Method Call

A method can be invoked in three ways, such as the following:

  • By method name, such as a sort method calling the swapmethod
    void sort(int[] arr){
       // ...
       swap(arr[], i,j);
       // ...
    }
    
  • By reference to an object
    MyClass mc=new MyClass();
    int result=mc.findMax(10, 20);
    
  • By class name (staticmethod)
    int result=MyClass.findMin(10,20);

However, a static method can manipulate only the static fields and static methods of the same class directly. Non-static methods must be called by object reference within the static method body. Java imposes this restriction because the static method exists without the existence of the class instance. As a result, a call to a non-static method directly by the static method is an uncalled-for situation.

When the program invokes a method, before passing the control to the called method, the return address is pushed into the program execution stack (a stack is a data structure that works in a LIFO, or last-in-first-out, manner). If a series of calls is in order, each address is pushed into the stack so that each pop would result in its immediate caller’s address and the program control flow can proceed from it.

The program execution stack also contains memory for storing local variables used by each method call. This location is called the activation frame of the method. On method call, the activation frame of the method is also pushed into the stack. When the method returns back to the caller, the activation frame is popped off the stack. As a result, local variables are no longer accessible to the program. If the variable is a local reference to an object within a method, it is marked for garbage collection by the JVM. Because each method call uses memory, an unlimited series of method calls may result in an error called a stack overflow.

Once the closing braces of a method or a return statement is encountered, Java pops the caller address from the stack and returns the control back to the caller.

Note: A program is a sequential flow of instructions with an occasional jump from one method to another, yet adheres to the same sequence.

Conclusion

This a brief and terse story of Java methods, though there is more to it than meets the eye. For example, there are overloaded and overridden methods, final methods, access modifiers associated with the methods, and so on. These are all important traits associated with Java methods that can be better understood in relation to inheritance, a paradigm of object-oriented programming. Also, there are default methods that can be better understood in relation to interfaces, and the like. This article is an attempt to provide a glimpse into the rabbit hole of Java methods. Perhaps this would whet inquisitiveness and give a reason to search for more details and learn more.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories