Syntax of Method in Java
In Java, the way we write methods follows a specific pattern, called syntax. This is like a recipe that tells Java exactly what you want your method to do and how to do it. Here's a basic outline:
returnType methodName(parameters) {
// Code to execute
}
Example
void greet() {
System.out.println("Hello, world!");
}
This method, greet, doesn't take any inputs (parameters) and doesn't return anything (void). When called, it simply prints out "Hello, world!".
Java Method Declaration
Declaring a method in Java is like telling the program that you have a set of instructions to perform a specific task. When you declare a method, you specify what it will do and what it needs to do its job. Here are the main parts of a method declaration:
- Access Modifier: This part tells who can use the method. For example, public means anyone can access it, while private means only code inside the same class can use it.
- Public: Methods or variables declared as public can be accessed from any class, package, or subclass, providing the widest scope of visibility.
- Private: Methods or variables declared as private are accessible only within the same class, ensuring encapsulation and restricting external access.
- Protected: Members with the protected modifier are accessible within the same package and by subclasses, even if they are in different packages.
- Default: If no access modifier is specified, the member has package-private access, meaning it is accessible only within the same package.
- Return Type: This tells what type of value the method will give back after it finishes. If the method doesn't return anything, you use void.
- Method Name: This is what you call the method. It should describe what the method does, like calculateAge or readFile.
- Method Body: The method body is the block of code within curly braces {} that defines the specific actions or logic to be executed when the method is called.
- Parameters: These are the inputs the method needs to work. You list them inside the parentheses after the method name. Each parameter has a type and a name. If the method doesn't need any inputs, you just use empty parentheses.
Example of a simple method declaration:
public int addNumbers(int number1, int number2) {
return number1 + number2;
}
In this example, public is the access modifier, int is the return type because the method returns an integer, addNumbers is the method name, and int number1, int number2 are the parameters the method needs to perform its task.
Types of Methods in Java
Types of Methods in Java
There are two types of methods in Java:
- Predefined Method
- User-defined Method
Predefined Method
Predefined methods are built-in methods provided by the Java library. These methods simplify common tasks like string manipulation, mathematical calculations, or input/output operations. Examples include Math.sqrt() and System.out.println().
Example:
Java
public class PredefinedMethodExample {
public static void main(String[] args) {
double result = Math.sqrt(16); // Predefined method from the Math class
System.out.println("Square root of 16 is: " + result);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Square root of 16 is: 4.0
User-defined Method
User-defined methods are written by developers to perform specific tasks. These methods help improve code reuse and modularity. Developers define the method's logic and parameters based on their needs.
Example:
Java
public class UserDefinedMethodExample {
public static void main(String[] args) {
greet("Alice"); // Calling a user-defined method
}
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Hello, Alice!
How to Name a Method in Java?
- Use Action Words: Start with a verb that describes what the method does, like calculate, read, print, or get. This makes it clear that the method performs an action.
- Be Specific: The name should give a clear idea of what the method does. For example, calculateTotalPrice is better than just calculate because it tells you exactly what the calculation is for.
- Keep It Short & Simple: While being specific, also try to keep the name concise. Long names can be hard to read and remember. Aim for a balance between clarity and brevity.
- Use CamelCase: In Java, the convention is to start method names with a lowercase letter and then capitalize the first letter of each subsequent word, with no spaces. For example, findMaximumValue.
- Avoid Using Numbers: Names like method1 or process2 don't tell you anything about what the method does. It's better to use descriptive names.
- Consider the Context: Think about the parameters the method takes and what it returns. This can sometimes help in naming the method. For example, if a method takes a username and returns a greeting message, createGreetingForUser might be a good name.
Method Calling in Java
Calling a method in Java means telling the program to execute the set of instructions defined in that method. When you call a method, the program pauses its current task, performs the method's instructions, and then returns to where it left off. Here's how to call a method:
- Using the Method Name: If you're calling a method from within the same class and the method doesn't require any input, you simply use its name followed by parentheses. For example, methodName();.
- Passing Parameters: If the method requires inputs, you need to provide values for those parameters within the parentheses. For example, if you have a method addNumbers(int a, int b), you would call it by writing addNumbers(5, 3);, where 5 and 3 are the inputs.
- Storing Return Values: If the method returns a value, you can store it in a variable. For instance, if addNumbers returns an integer, you could call it like this: int sum = addNumbers(5, 3);. Now, sum holds the result of the method.
- Calling Non-Static Methods: To call non-static (instance) methods, you first need an object of the class. Suppose you have a class Calculator with a method subtractNumbers. You'd first create an object like Calculator calc = new Calculator(); and then call the method like calc.subtractNumbers(10, 5);.
- Calling Static Methods: Static methods belong to the class, not to any object. So, you can call them directly using the class name. For example, if addNumbers is static, you call it like ClassName.addNumbers(5, 3);.
Remember, the key to calling methods is understanding whether they need inputs, return a value, and whether they are static or non-static.
Example of methods in Java
Example 1: Adds two numbers
We'll create a simple method that adds two numbers and then show how to call this method from the main method.
First, we declare our method addNumbers, which takes two integer parameters and returns their sum:
Java
public class Calculator {
// Method to add two numbers
public int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // Returning the sum of the two numbers
}
public static void main(String[] args) {
Calculator myCalculator = new Calculator(); // Creating an object of the Calculator class
// Calling the addNumbers method and storing the returned value in a variable
int result = myCalculator.addNumbers(10, 5);
// Printing the result to the console
System.out.println("The sum of 10 and 5 is: " + result);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
The sum of 10 and 5 is: 15
In this example:
We've defined a method named addNumbers inside the Calculator class. This method takes two integers (num1 and num2) as input parameters.
Inside the method, we add num1 and num2 and store their sum in a local variable named sum.
- The method then returns sum to wherever it was called from, using the return statement.
- In the main method, we create an instance of the Calculator class named myCalculator.
- We then call the addNumbers method on myCalculator, passing 10 and 5 as arguments. The method returns the sum of these numbers, which we store in the result variable.
- Finally, we print out the result, which in this case will be 15, because 10 + 5 = 15.
Example 2: Adding Negative Numbers
Java
public class Calculator {
// Method to add two numbers
public int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // Returning the sum of the two numbers
}
public static void main(String[] args) {
Calculator myCalculator = new Calculator(); // Creating an object of the Calculator class
// Calling the addNumbers method with negative numbers
int result = myCalculator.addNumbers(-10, -5);
// Printing the result to the console
System.out.println("The sum of -10 and -5 is: " + result);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
The sum of -10 and -5 is: -15
Example 3: Adding a Positive and Negative Number
Java
public class Calculator {
// Method to add two numbers
public int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // Returning the sum of the two numbers
}
public static void main(String[] args) {
Calculator myCalculator = new Calculator(); // Creating an object of the Calculator class
// Calling the addNumbers method with a positive and a negative number
int result = myCalculator.addNumbers(20, -8);
// Printing the result to the console
System.out.println("The sum of 20 and -8 is: " + result);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
The sum of 20 and -8 is: 12
Memory Allocation for Method Calls
When you call a method in Java, the program needs a place to keep track of the method's operations and the values it uses. This is where memory allocation comes into play. Here's how it works:
- Stack Memory: Java uses a section of memory called the "stack" for method calls. Each time a method is called, a block of space (called a "stack frame") is set aside in the stack for that method.
- Stack Frame: This stack frame holds everything the method needs to run, like its parameter values and local variables. Each method call gets its own stack frame, keeping its operations separate from others.
- Method Execution: As the method runs, it uses its stack frame to keep track of what it's doing. If the method calls another method, a new stack frame is created for that call, placed on top of the current one.
- Method Completion: Once a method finishes running, its stack frame is no longer needed. The frame is removed from the stack, freeing up that space. If the method returned a value, that value is passed back to the place where the method was called.
- Recursion and Stack Overflow: If a method keeps calling itself (a situation known as "recursion"), or if too many methods are called without completing, the stack can run out of space. This situation is called a "stack overflow," and it will cause the program to crash.
Advantage of Method in Java
- Reduces Code Repetition: One of the main benefits of using methods in Java is that they help reduce the repetition of code. Instead of writing the same code multiple times in different places, you can create a method that contains this code & call it wherever needed. This not only saves time but also makes your code more manageable & less prone to errors.
- Enhances Code Organization: Methods act as organizing tools for your code, similar to how chapters organize a book. By grouping related actions into methods, you make your code more structured & easier to navigate. This organization is especially helpful in large projects where keeping track of what each part of the code does can become challenging.
- Simplifies Debugging & Maintenance: When your code is divided into methods, identifying & fixing bugs becomes simpler. You can test individual methods for errors without having to sift through the entire codebase. This compartmentalization also makes updating the code more straightforward, as changes can be made within a specific method without affecting others.
- Facilitates Code Reusability: Methods allow you to reuse code across different parts of the same project or even in entirely different projects. If you've written a method that performs a common task, you can easily call it in any new project that requires the same functionality, thereby avoiding redundancy & saving time.
- Improves Readability: Methods with meaningful names can make your code much easier to read & understand. For someone reviewing your code, a well-named method like calculateTotalScore() immediately conveys what the method does, without the need to delve into its implementation details.
- Enables Modular Testing: With methods, testing becomes a modular affair. You can test each method independently, ensuring that it works as expected before integrating it into the larger application. This approach to testing, known as unit testing, is a cornerstone of reliable software development, leading to more stable & dependable code.
Frequently Asked Questions
Can a Java method have more than one return statement?
Yes, a Java method can have multiple return statements, but only one will be executed based on the conditionals within the method. Once a return statement is executed, the method exits, and no further code within it is run.
Is it necessary for every Java method to have parameters?
No, it's not necessary for every Java method to have parameters. Methods can be declared without parameters if they don't require any external input to perform their task.
Can we call one method inside another method in Java?
Yes, in Java, you can call one method from within another. This is a common practice for breaking down complex tasks into simpler, more manageable pieces.
What is the difference between a method and a function in Java?
In Java, a method is a block of code defined within a class and performs a specific task. A function is a general term used for any callable block of code, but in Java, methods are the only type of functions.
What happens if a method has the same name as the class?
If a method has the same name as the class, it is considered a constructor. Constructors are special methods used to initialize objects and are called automatically when an object of the class is created.
Conclusion
Methods are essential building blocks in Java programming, offering structure, reusability, and clarity to your code. In this article, we learned the concept of methods in Java, starting with what they are and why they're useful. We've covered the syntax for creating methods, the benefits they offer like code reusability and simplification, and how to properly declare and name them. We also discussed the types of methods in Java, how to call them, and how memory is allocated for method calls.