Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of Method
2.1.
Example
3.
Advantage of Method
3.1.
Reduces Code Repetition
3.2.
Enhances Code Organization
3.3.
Simplifies Debugging & Maintenance
3.4.
Facilitates Code Reusability
3.5.
Improves Readability
3.6.
Enables Modular Testing
4.
Method Declaration
4.1.
Access Modifier
4.2.
Return Type
4.3.
Method Name
4.4.
Parameters
4.5.
Example of a simple method declaration:
5.
Types of Methods in Java
5.1.
Void Methods
5.2.
Returning Methods
5.3.
Parameterized Methods
5.4.
Non-Parameterized Methods
5.5.
Static Methods
5.6.
Non-Static Methods
6.
How to Name a Method?
6.1.
Use Action Words
6.2.
Be Specific
6.3.
Keep It Short & Simple
6.4.
Use CamelCase
6.5.
Avoid Using Numbers
6.6.
Consider the Context
7.
Method Calling
7.1.
Using the Method Name
7.2.
Passing Parameters
7.3.
Storing Return Values
7.4.
Calling Non-Static Methods
7.5.
Calling Static Methods
8.
Example
8.1.
Java
9.
Memory Allocation for Method Calls
9.1.
Stack Memory
9.2.
Stack Frame
9.3.
Method Execution
9.4.
Method Completion
9.5.
Recursion and Stack Overflow
10.
Frequently Asked Questions
10.1.
Can a Java method have more than one return statement?
10.2.
Is it necessary for every Java method to have parameters?
10.3.
Can we call one method inside another method in Java?
11.
Conclusion
Last Updated: Apr 4, 2024
Easy

Methods in Java

Author Pallavi singh
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In Java, a method is a collection of commands that may be invoked by calling its name.It  holds a sequence of steps to accomplish a particular job. When you need to perform that job, you just "call" the method. This approach makes your code neat and organized. 

Methods in Java

In this article we will learn what these methods look like, how they work, and when to use which one. 

Syntax of Method

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
}

 

  • returnType: This part tells you what type of result the method will give back after it finishes. If your method doesn't return anything, you use the word void.
     
  • methodName: This is the name you give your method. It should be something that makes sense for what the method does, like calculateTotal or displayMessage.
     
  • parameters: These are like inputs for your method. You can have none, one, or many. Each parameter has a type and a name.

 

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!".

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Advantage of Method

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.

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.

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.

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

In Java, methods are categorized mainly based on what they return and what they accept as input. For example -: 

Void Methods

These methods do not return any value. They just perform an action. For example, a method that prints a message on the screen might not need to return anything.

Returning Methods

Unlike void methods, these methods return a value after completing their task. The return type can be any data type, like int, String, or even an array. This is useful when you perform a calculation and need the result.

Parameterized Methods

These methods take input values, called parameters, to perform their tasks. The inputs can affect how the method behaves or what it returns. For example, a method to add two numbers would need those numbers as input.

Non-Parameterized Methods

These methods do not require any inputs. They perform their tasks based on the information available to them within the class they belong to.

Static Methods

A static method belongs to the class rather than any instance of the class. You can call it without creating an object of the class. For example, the main method in Java is static.

Non-Static Methods

These are also known as instance methods. They require an object of the class to be created before you can call them. They can access instance data and other instance methods directly.

How to Name a Method?

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

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

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

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);
}
}

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.

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.

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.

Conclusion

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. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Odd or Even Program in Java
Next article
Reference Variable in Java
Live masterclass