Methods in Java: Types, Method Signature
Methods in Java are the building blocks of a Java application. A method is a block of code used to write the logic of the application, which performs some specific tasks or operations. In simple words, a method is a set of statements grouped together to perform a specific function.
In Java programming, a method is executed when it is called from another method. The main() method is an entry point of a Java application and is the first method executed by JVM (Java Virtual Machine).
If we want to want to execute any other method, we need to call it from the main() method or from another method that eventually gets called by main().. When a method is called, it may return a value to the calling method. However, it can also perform a task without returning any value to the calling method.
We can call a method from anywhere in Java program, provided it is accessible in the current scope. Each method has a single entry point and a single exit point. A method can also call itself. This technique is known as a recursion in Java. Recursion is useful for solving certain complex problems like factorial calculation, tree traversal, and more.
Why do We Use Methods in Java?
The purpose of using methods in a Java program is to write the logic of the application in a structured and reusable way. Let’s consider an example to understand the concept of using methods in Java. In this example, we will perform the addition of two numbers.
Example 1:
class Addition
{
// Declare two instance variables.
int a = 10;
int b = 20;
// System.out.println(a + b);
// This is invalid syntax because you cannot directly write the business logic of the application inside the class.
// Therefore, we will declare an instance method inside the class and write the logic inside the method.
// Declare 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
In the above program, we tried to write the statement System.out.println(a + b); directly inside the class (outside of any method), which is invalid in Java. This is because we cannot write executable statements directly inside a class. They must be placed inside methods or blocks.
To resolve this, we declared an instance method named add() inside the class and wrote the business logic (i.e. addition of two numbers) within that method. Then, we created an object of the class in the main() method and called the add() method using that object.
In this way, it is clear that methods are used to write the business logic of a Java application or program in an organized, reusable, and error-free manner.
Method Declaration in Java
A method must be declared inside a class in Java. In general, a method has six fundamental parts, such as:
- Modifiers
- Method name
- Return type
- Parameter list
- Exception list
- Body.
The general syntax to declare a method in a Java 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)
}
Important Points About Method Syntax
1. Modifier: This defines the access type of a method, but it is optional to use. It may include:
- Access modifiers: private, default (no modifier), protected, or public.
- Non-access modifiers: static, final, abstract, or synchronized.
The public is the least restrictive access modifier and the private is the most. Access modifiers control the visibility of methods.
2. Abstract Methods: If the method is declared as abstract, its implementation is omitted, and the method body is replaced with a semicolon (;). The method must be part of an abstract class or interface.
3. Return Type: The return type specifies the type of data or value that the method will return when it is called. If a method does not return any value, its return type is declared as void.
4. Return Statement: The return statement is used to return a value from the method to the caller. It is optional if the return type is void.
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. Look at the below some valid examples of methods signature:
1. add(int a, int b) // Number of parameters is 2, and type of parameters is int.
2. m1(String name) // Number of parameters is 1, and type of parameters is String.
3. sub(): No parameter.
Parameter list:
The parameter list is a comma-separated list of zero or more parameter declarations. It is written inside the parentheses after the method name. The basic syntax to declare the parameter list is:
parameter_modifier data_type parameter_name
In the above syntax,
- parameter_modifier: It may be final. If the modifier of parameter is final, it cannot be modified inside the method. However, it is optional.
- data_type: The type of the parameter may be int, float, char, double, String, etc.
- parameter_name: Each parameter_name must be a unique name within the method.
If there is more than one parameter, they should be 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 following the method name. The scope of the parameter list is limited to the method only. However, the parameter list is optional. The method may also contain zero or more parameters.
Method body:
The method body is a block of code or statements enclosed within curly braces ({}). It contains statements, local variable declarations, and possibly local classes. It defines the actual logic or behavior of the method. The method body may also contain return statement, depending on the method’s return type.
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 a non-void but a data type like int, float, double, etc., the method must return a value of the specified type to the calling method. In such methods, it is mandatory to include a return statement inside the method body. This 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 in Java.
- A method name should be a meaningful name related to logic or functionality. It clearly describe the purpose or logic of the method.
- Exceptions may be thrown by the methods. In such cases, you can use the throws keyword to specify the exceptions in the method declaration.
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 method name (or functionality name). This method will execute when it is called and provided with values for parameters a and b.
- int a, int b are the parameters of the method. They allow input values to be passed when the method is called.
- void is the return type, which means the method does not return any value after execution.
- public is an access modifier, which means you can access this method from anywhere in the program, as long as the class containing it is accessible.
Example 3:
private int m2() { }
Here,
- m2 is the method name with no arguments (empty parameter-list).
- int is the return type, which means the method must return an integer value when it finishes execution. If it does not return an int, the compiler will show an error.
- private is the access modifier, which means that you can access this method only within the same class in which it is defined.
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).
- This method has been declared with the throws Exception clause, meaning the method may throw an exception of type Exception. The caller must handle it.
- We have declared this 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 create various kinds of methods based on the requirements and logic of the application.
- Predefined methods
- User-defined methods (Programmer-defined methods)
Let’s understand them one by one.
Predefined Methods in Java
Predefined methods in Java are those methods that are already defined in the Java API (Application Programming Interface) to use directly in an application.
Java Programming language contains a large number of predefined classes, which are organized in different predefined packages. These classes contain many predefined methods that help programmers to perform common tasks efficiently.
In fact, Java includes over 160 predefined packages that contain more than 3000 predefined classes. These classes have many more thousands of individual predefined methods. All of these are accessible to the programmers through the Java API.
Examples of Predefined Methods:
1. print() is a predefined method present in the class PrintStream, which is a part of package java.io package. For example, System.out.print(“Hello”) prints the specified string inside the double quotation marks on the console.
2. sqrt() is a method of Math class, which is present in the java.lang package. It is used to calculate the square root of a number.
3. max() is a predefined method, which returns the greater of two values.
Let’ take an example program based on Java predefined methods.
Example 5: Let’s write a Java program to find out the square root of a number 16 using sqrt() method of Math class.
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
Example 6: Java program to find the maximum between two numbers.
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 in Java are those methods that are defined by the user or programmer 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.
In Java, we can declare two main types of user-defined methods:
- Instance methods
- Static methods
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 behavior of an object/instance of the class. Since it is tied to the object of a class, it is also called a non-static method.
You must create an object of the class to invoke an instance method. Without creating an object of the class, the methods cannot exist to perform their desired behaviors or task. Here is an example of an instance method declaration:
void m1()
{
// This area is called an instance area or non-static area.
// Write logic here.
}
Static Methods 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 in Java is as follows:
static void m2()
{
// This area is called a static area.
// Write logic here.
}
Key Points:
- An instance method can refer to static variables (class variables) as well as for instance variables of the class.
- 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:
instance_reference.instance_method_name(actual_parameters);
Let’s take an example based on it.
Example 7:
package methodProgram;
public class Test
{
// Create an instance method.
void msg() {
System.out.println("Instance method");
}
public static void main(String[] args) {
// Create 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 practical concept shown in the figure below. It will help you understand method calling more easily.
As shown in the figure above, there are two types of areas in Java: the instance area and the static area.
1. Calling Instance Members from the Instance Area:
If you call instance members (variables or methods) from within instance area (i.e., same area), you don’t need to use object reference variable for calling instance variables or methods. You can call them directly.
2. Calling Instance Members from the Static Area:
If you call instance variables or methods from the instance area within the static area (i.e. different area), you cannot call them directly. You will have to use object reference variables for calling them.
3. Calling Static Members from Static or Instance Areas:
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. Accessing Static Members from Outside the Class:
When you want to call static members from outside the class, static members can be accessed by using the class name only.
5. Method Call Execution Flow:
When a method is called in a Java 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 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 an 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);
// Write the 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 Can’t a 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 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
Calling Instance and Static Methods from Inside Method
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();
}
}
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 the diagram shown in the below figure.
As you can see in the above figure for example program 11, we are calling m1() method, but m1() method is calling m2(). So, the control of execution will go to m2() method, but m2() is calling static m3() method.
After completing of m3() method, once again the control of execution goes to m2() method to execute the rest of code. After the complete execution of m2() method, the control again goes to m1() method to execute the rest of the code. At last, we have called the static method m4().
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:
- 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.
- Methods help in organizing code logically by breaking complex problems into smaller. This makes the program easier to read and maintain.
- They help avoid redundancy by allowing us to reuse code.
- A method helps to perform tasks on a variety of data inputs by passing method’s parameter.