Java Tutorial 0/145 lessons ~6 min read Lesson 17

    Methods

    java methods parameters arguments return type void overloading pass by value recursion call stack static modular programming

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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
    • void Methods
    • 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:

    java
    public static void greet() {
    System.out.println("Welcome to Java!");
    }

    Calling the method:

    java
    greet();

    Output:

    Welcome to Java!

    Why Do We Need Methods?

    Without methods:

    java
    System.out.println("Calculating Salary...");
    System.out.println("Salary = 50000");
    System.out.println("Calculating Salary...");
    System.out.println("Salary = 50000");

    With methods:

    java
    calculateSalary();
    calculateSalary();

    Benefits:

    • Code Reusability
    • Easy Maintenance
    • Better Readability
    • Modular Design
    • Easier Testing
    • Reduced Duplication

    Method Syntax

    java
    accessModifier returnType methodName(parameters) {
    // Method Body
    }

    Example:

    java
    public static void displayMessage() {
    System.out.println("Hello Java");
    }

    Parts of a Method

    java
    public static int add(int a, int b) {
    return a + b;
    }

    Components:

    • public → Access Modifier
    • static → Static Keyword
    • int → Return Type
    • add → Method Name
    • (int a, int b) → Parameters
    • return → Returns Value

    Calling a Method

    java
    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:

    java
    static void welcome(String name) {
    System.out.println("Welcome " + name);
    }

    Calling:

    java
    welcome("Jagannath");
    welcome("Radha");

    Output:

    Welcome Jagannath
    Welcome Radha

    Arguments vs Parameters

    java
    static void add(int a, int b)

    Here:

    • a and b → Parameters

    Calling:

    java
    add(10, 20);

    Here:

    • 10 and 20 → Arguments

    Return Type

    Methods can return values.

    java
    static int square(int number) {
    return number * number;
    }

    Calling:

    java
    int result = square(5);
    System.out.println(result);

    Output:

    25

    The void Return Type

    A void method performs an action but returns no value.

    java
    static void printLine() {
    System.out.println("----------------");
    }

    Multiple Parameters

    java
    static double calculateArea(double length, double width) {
    return length * width;
    }

    Calling:

    java
    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:

    java
    static int add(int a, int b) {
    return a + b;
    }
    static double add(double a, double b) {
    return a + b;
    }

    Calling:

    java
    System.out.println(add(5, 6));
    System.out.println(add(4.5, 2.3));

    Output:

    11
    6.8

    Pass by Value

    Java always passes arguments by value.

    Example:

    java
    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.

    java
    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:

    java
    static int factorial(int n) {
    if (n == 1)
    return 1;
    return n * factorial(n - 1);
    }

    Calling:

    java
    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

    java
    static double calculateInterest(double amount, double rate) {
    return amount * rate / 100;
    }

    Calling:

    java
    double interest = calculateInterest(50000, 7.5);
    System.out.println(interest);

    Real-World Example: E-Commerce Discount

    java
    static double applyDiscount(double price) {
    return price * 0.90;
    }

    Best Practices

    Use Meaningful Method Names

    Good:

    java
    calculateSalary()

    Bad:

    java
    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:

    java
    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

    java
    int add(int a, int b) {
    }

    This results in a compilation error because the method declares an int return type.

    Returning the Wrong Type

    java
    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:

    1. Creates a method to print a welcome message.
    2. Creates a method to add two numbers.
    3. Creates a method to calculate the area of a rectangle.
    4. Demonstrates method overloading using different parameter types.
    5. Creates a recursive method to calculate factorial.
    6. Demonstrates pass-by-value with primitive variables.
    7. 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.
    • void methods 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.

    Ready to mark this lesson complete?Track your journey across the entire course.