Java Methods
Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.
Example: Java program to demonstrate how to create and use a method.
// Creating a method
// that prints a message
public class Geeks
{
// Method to print message
public void printMessage() {
System.out.println("Hello, Geeks!");
}
public static void main(String[] args) {
// Create an instance of the Method class
Geeks obj = new Geeks();
// Calling the method
obj.printMessage();
}
}
Output
Hello, Geeks!
Explanation: In this example, printMessage() is a simple method that prints a message. It has no parameters and does not return anything. Here, first we create a method which prints Hello, Geeks!.
Syntax of a Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Key Components of a Method Declaration
- Modifier: It specifies the method's access level (e.g., public, private, protected, or default).
- Return Type: The type of value returned, or void if no value is returned.
- Method Name: It follows Java naming conventions; it should start with a lowercase verb and use camel case for multiple words.
- Parameters: A list of input values (optional). Empty parentheses are used if no parameters are needed.
- Exception List: The exceptions the method might throw (optional).
- Method Body: It contains the logic to be executed (optional in the case of abstract methods).

Types of Methods in Java
1. Predefined Method
Predefined methods are the method that is already defined in the Java class libraries. It is also known as the standard library method or built-in method. for example random() method which is present in the Math class and we can call it using the ClassName.methodName() as shown in the below example.
Example:
Math.random() // returns random value
Math.PI() // return pi value
2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.
Example:
sayHello // user define method created above in the article
Greet()
setName()
Different Ways to Create Java Method
There are two ways to create a method in Java:
1. Instance Method: Access the instance data using the object name. Declared inside a class.
Example:
// Instance Method
void method_name() {
// instance method body
}
2. Static Method: Access the static data using class name. Declared inside class with static keyword.
Example:
// Static Method
static void method_name() {
// static method body
}
Method Signature
It consists of the method name and a parameter list.
- Number of parameters
- Type of the parameters
- Order of the parameters
Note: The return type and exceptions are not considered as part of it.
Method Signature of the above function:
max(int x, int y) Number of parameters is 2, Type of parameter is int.
Naming a Method
In Java language method name is typically a single word that should be a verb in lowercase or a multi-word, that begins with a verb in lowercase followed by an adjective, noun. After the first word, the first letter of each word should be capitalized.
Rules to Name a Method:
- While defining a method, remember that the method name must be a verb and start with a lowercase letter.
- If the method name has more than two words, the first name must be a verb followed by an adjective or noun.
- In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example, findSum, computeMax, setX, and getX.
Generally, a method has a unique name within the class in which it is defined but sometimes a method might have the same name as other method names within the same class as method overloading is allowed in Java.
Method Calling
Method calling allows to reuse code and organize our program effectively. The method needs to be called for use its functionality. There can be three situations when a method is called:
A method returns to the code that invoked it when:
- It completes all the statements in the method.
- It reaches a return statement.
- Throws an exception.
Example 1: Method calling using object of a class.
// Java program demonstrates how to call a method
class Add {
int s = 0;
// Method
public int addTwoInt(int a, int b) {
// Perfrom sum of two numbers given as argument
s = a + b;
// Return the sum of two numbers
return s;
}
}
class Geeks
{
public static void main(String[] args) {
// Creating an object of Add class
Add a = new Add();
// Calling method using object and storing the return
// Value in res variable of int type
int res = a.addTwoInt(1, 2);
// Printing the output
System.out.println("Sum: " + res);
}
}
Output
Sum: 3
Example 2: Calling Methods in Different Ways
// Java Program to Illustrate Method Calling
import java.io.*;
// Helper class
class Test {
public static int i = 0;
// Constructor to count objects
Test() {
i++;
}
// Static method to get the
// number of objects created
public static int get() {
return i;
}
// Instance method m1 calling
// another method m2
public int m1() {
System.out.println("Inside the method m1");
this.m2(); // Calling m2 method
return 1;
}
// Method m2 that prints a message
public void m2() {
System.out.println("In method m2");
}
}
// Main class
class Geeks
{
// Main driver method
public static void main(String[] args) {
// Creating object of Test class
Test obj = new Test();
// Calling m1 method using the class object
int i = obj.m1();
System.out.println("Control returned after m1: " + i);
// Calling the get method directly using the class name
int o = Test.get();
// Printing the value
System.out.println("No of instances created: " + o);
}
}
Output
Inside the method m1 In method m2 Control returned after m1: 1 No of instances created: 1
The control flow of the above program is as follows:

Passing Parameters to a Method
There are some cases when we don’t know the number of parameters to be passed or an unexpected case to use more parameters than declared number of parameters. In such cases we can use
- Passing Array as an Argument
- Passing Variable-arguments as an Argument
- Method Overloading.
Memory Allocation for Methods Calls
Methods calls are implemented through a stack. Whenever a method is called a stack frame is created within the stack area and after that, the arguments passed to and the local variables and value to be returned by this called method are stored in this stack frame and when execution of the called method is finished, the allocated stack frame would be deleted. There is a stack pointer register that tracks the top of the stack which is adjusted accordingly.
Example: Accessor and Mutator Methods
public class Geeks
{
private int num;
private String n;
// Accessor (getter) methods
public int getNumber()
{
return num;
}
public String getName()
{
return n;
}
// Mutator (setter) methods
public void setNumber(int num)
{
this.num = num;
}
public void setName(String n)
{
this.n = n;
}
// Other methods
public void printDetails() {
System.out.println("Number: " + num);
System.out.println("Name: " + n);
}
// Main method to run the code
public static void main(String[] args) {
Geeks g = new Geeks();
g.setNumber(123);
g.setName("GFG Write");
g.printDetails();
}
}
Output
Number: 123 Name: GFG Write
Explanation: In the above example, the Geeks class contains private fields num and n, with getter and setter method to access and modify their values. The printDetails() method prints the values of num and n to the console. In the main method, the setNumber, setName, and printDetails methods are called to set and display the object's details.
Advantages of Methods
- Reusability: Methods allow us to write code once and use it many times.
- Abstraction: Methods allow us to abstract away complex logic and provide a simple interface for others to use.
- Encapsulation: Allow to encapsulate complex logic and data
- Modularity: Methods allow us to break up your code into smaller, more manageable units, improving the modularity of your code.
- Customization: Easy to customize for specific tasks.
- Improved performance: By organizing your code into well-structured methods, you can improve performance by reducing the amount of code.