Methods
java methods parameters arguments return type void overloading pass by value recursion call stack static modular programming
Introduction
So far in this course, you've learned about variables, operators, control flow, loops, and arrays.
As programs grow larger, you'll often find yourself writing the same block of code multiple times. Repeating code makes applications harder to maintain, debug, and extend.
Java solves this problem using Methods.
A method is a reusable block of code that performs a specific task. Instead of rewriting the same logic repeatedly, you write it once and call it whenever needed.
Methods are one of the core principles of modular programming and are heavily used in enterprise applications such as Spring Boot, Microservices, Android, and Java EE.
In this lesson, you'll learn:
- What is a Method?
- Why Methods are Needed
- Method Declaration
- Calling Methods
- Parameters and Arguments
- Return Types
voidMethods- Method Overloading
- Pass by Value
- Variable Scope
- Recursive Methods
- Method Call Stack
- Real-world Examples
- Best Practices
- Common Mistakes
- Hands-on Exercises
- Professional Interview Questions
What is a Method?
A method is a named block of reusable code that performs a specific task.
Think of a method as a machine:
- Input → Parameters
- Processing → Business Logic
- Output → Return Value
Example:
public static void greet() {System.out.println("Welcome to Java!");}
Calling the method:
greet();
Output:
Welcome to Java!
Why Do We Need Methods?
Without methods:
System.out.println("Calculating Salary...");System.out.println("Salary = 50000");System.out.println("Calculating Salary...");System.out.println("Salary = 50000");
With methods:
calculateSalary();calculateSalary();
Benefits:
- Code Reusability
- Easy Maintenance
- Better Readability
- Modular Design
- Easier Testing
- Reduced Duplication
Method Syntax
accessModifier returnType methodName(parameters) {// Method Body}
Example:
public static void displayMessage() {System.out.println("Hello Java");}
Parts of a Method
public static int add(int a, int b) {return a + b;}
Components:
public→ Access Modifierstatic→ Static Keywordint→ Return Typeadd→ Method Name(int a, int b)→ Parametersreturn→ Returns Value
Calling a Method
public class Main {static void greet() {System.out.println("Hello");}public static void main(String[] args) {greet();}}
Output:
Hello
Method Parameters
Parameters receive input values.
Example:
static void welcome(String name) {System.out.println("Welcome " + name);}
Calling:
welcome("Jagannath");welcome("Radha");
Output:
Welcome JagannathWelcome Radha
Arguments vs Parameters
static void add(int a, int b)
Here:
aandb→ Parameters
Calling:
add(10, 20);
Here:
10and20→ Arguments
Return Type
Methods can return values.
static int square(int number) {return number * number;}
Calling:
int result = square(5);System.out.println(result);
Output:
25
The void Return Type
A void method performs an action but returns no value.
static void printLine() {System.out.println("----------------");}
Multiple Parameters
static double calculateArea(double length, double width) {return length * width;}
Calling:
double area = calculateArea(5.5, 3.2);System.out.println(area);
Method Overloading
Java allows multiple methods with the same name but different parameter lists.
Example:
static int add(int a, int b) {return a + b;}static double add(double a, double b) {return a + b;}
Calling:
System.out.println(add(5, 6));System.out.println(add(4.5, 2.3));
Output:
116.8
Pass by Value
Java always passes arguments by value.
Example:
static void changeValue(int number) {number = 100;}public static void main(String[] args) {int value = 50;changeValue(value);System.out.println(value);}
Output:
50
The original variable remains unchanged because Java passes a copy of the value.
Variable Scope
Local variables exist only inside the method where they are declared.
static void demo() {int age = 25;System.out.println(age);}
Trying to access age outside the method results in a compilation error.
Recursive Methods
A recursive method calls itself.
Example:
static int factorial(int n) {if (n == 1)return 1;return n * factorial(n - 1);}
Calling:
System.out.println(factorial(5));
Output:
120
A recursive method must have a base case to avoid infinite recursion.
Method Call Stack
Each method call creates a new frame in the stack memory.
Example:
main()↓calculate()↓display()↓Return↓Back to calculate()↓Back to main()
Understanding the call stack helps in debugging recursive calls and exceptions.
Real-World Example: Banking Application
static double calculateInterest(double amount, double rate) {return amount * rate / 100;}
Calling:
double interest = calculateInterest(50000, 7.5);System.out.println(interest);
Real-World Example: E-Commerce Discount
static double applyDiscount(double price) {return price * 0.90;}
Best Practices
Use Meaningful Method Names
Good:
calculateSalary()
Bad:
doTask()
Keep Methods Small
A method should ideally perform one specific responsibility.
Avoid Code Duplication
Extract repeated logic into reusable methods.
Return Values Instead of Printing
Prefer:
return total;
Instead of printing inside every method, allowing the caller to decide how to use the result.
Document Complex Methods
Use JavaDoc comments for methods with non-trivial logic.
Common Mistakes
Forgetting to Return a Value
int add(int a, int b) {}
This results in a compilation error because the method declares an int return type.
Returning the Wrong Type
return "Hello";
from an int method is invalid.
Infinite Recursion
A recursive method without a base case causes a StackOverflowError.
Using Global Variables Unnecessarily
Prefer passing data as parameters instead of relying on shared mutable state.
Writing Large Methods
Long methods are difficult to understand and maintain.
Hands-on Exercise
Create a Java program that:
- Creates a method to print a welcome message.
- Creates a method to add two numbers.
- Creates a method to calculate the area of a rectangle.
- Demonstrates method overloading using different parameter types.
- Creates a recursive method to calculate factorial.
- Demonstrates pass-by-value with primitive variables.
- Creates a simple calculator using separate methods for addition, subtraction, multiplication, and division.
Summary
Methods are the building blocks of modular Java applications. They improve readability, reduce duplication, and promote code reuse. Understanding parameters, return types, overloading, recursion, and variable scope is essential for writing clean, maintainable, and scalable Java applications.
Key Takeaways
- Methods encapsulate reusable logic.
- Parameters receive inputs; arguments supply values.
voidmethods perform actions without returning a value.- Return types specify the value a method produces.
- Method overloading allows multiple methods with the same name but different parameters.
- Java passes arguments by value.
- Local variables are accessible only within their scope.
- Recursive methods require a base case to terminate.
- Each method call creates a new frame on the call stack.
Professional Interview Questions
1What is the difference between parameters and arguments?
Professional Answer
Parameters are variables defined in a method declaration that receive input values, whereas arguments are the actual values passed when invoking the method. Parameters act as placeholders, while arguments provide real data during execution.
Follow-up Questions
- Can the number of arguments differ from the number of parameters?
- Can parameters have the same name as instance variables?
Interview Tip: Remember: Parameter → Method Definition, Argument → Method Call.
2What is Method Overloading?
Professional Answer
Method overloading allows multiple methods to have the same name but different parameter lists. The compiler determines which method to invoke based on the number, type, and order of the arguments. This is an example of compile-time polymorphism.
Follow-up Questions
- Can methods be overloaded by changing only the return type?
- How does Java resolve overloaded methods?
Interview Tip: Changing only the return type is not sufficient to overload a method.
3Does Java use Pass by Value or Pass by Reference?
Professional Answer
Java always uses pass by value. For primitive types, a copy of the value is passed. For objects, a copy of the reference is passed, meaning the reference itself is copied, not the actual object. As a result, object state can be modified through the copied reference, but the original reference variable cannot be changed to point to a different object.
Follow-up Questions
- Why do object modifications appear to persist after a method call?
- Can a method change the caller's object reference?
Interview Tip: A common interview question is whether Java is pass-by-reference. The correct answer is No—Java is always pass-by-value, including for object references.