LearnContact
Lesson 1465 min read

Methods in Java

Learn how to create reusable blocks of code in Java using methods, parameters, return values, method overloading, variable arguments, recursion, scope, and real-world method design.

Introduction

In the previous lesson, you learned how loops repeat blocks of code. However, large programs often contain many different tasks, and placing all code inside the main method quickly makes a program difficult to understand, test, reuse, and maintain.

Methods solve this problem by dividing a program into smaller, reusable blocks of code. Each method can perform one specific task and can be called whenever that task is needed.

Methods are one of the most important building blocks of Java programming. Almost every real-world Java application is organized around methods.

Simple Method
public class Main {

    static void greet() {

        System.out.println(
                "Hello, Java!"
        );

    }

    public static void main(String[] args) {

        greet();

    }
}
Output
Hello, Java!
What You Will Learn
  • What methods are.
  • Why methods are needed.
  • How methods work.
  • The anatomy of a method.
  • How to declare methods.
  • How to call methods.
  • How method execution flow works.
  • How void methods work.
  • How parameters work.
  • The difference between parameters and arguments.
  • How methods return values.
  • How the return statement works.
  • The four common method categories.
  • How static methods work.
  • How instance methods differ from static methods.
  • How built-in Java methods are used.
  • How method overloading works.
  • How Java resolves overloaded methods.
  • How variable arguments work.
  • How method scope works.
  • How local variables work.
  • How parameter scope works.
  • How block scope works.
  • What variable shadowing means.
  • Why Java is pass-by-value.
  • How primitive arguments behave.
  • How reference arguments behave.
  • How arrays are passed to methods.
  • How arrays are returned from methods.
  • How methods call other methods.
  • How the call stack works.
  • What stack frames are.
  • How recursion works.
  • Why recursive methods need a base case.
  • How recursive factorial works.
  • How recursion compares with loops.
  • What causes StackOverflowError.
  • How to design clear methods.
  • How to name methods.
  • What single responsibility means.
  • What pure methods are.
  • What side effects are.
  • How to build validation methods.
  • How to build utility methods.
  • Common method errors.
  • Best practices for writing maintainable methods.

What is a Method?

A method is a named block of code designed to perform a specific task. A method executes only when it is called.

Method Concept
METHOD

┌────────────────────────────┐
│                            │
│  NAME                      │
│                            │
│  INPUTS                    │
│       │                    │
│       ▼                    │
│  PERFORM TASK              │
│       │                    │
│       ▼                    │
│  OPTIONAL RESULT           │
│                            │
└────────────────────────────┘
Example
static void sayHello() {

    System.out.println(
            "Hello!"
    );

}

Why Methods are Needed

Reusability

Write code once and call it whenever the same task is needed.

Modularity

Divide large programs into smaller and manageable parts.

Readability

Well-named methods make programs easier to understand.

Maintainability

Update logic in one method instead of changing duplicated code.

Testing

Small methods are easier to test independently.

Debugging

Problems can be isolated to specific methods.

Without a Method
System.out.println("Welcome!");
System.out.println("----------------");

System.out.println("Dashboard");

System.out.println("Welcome!");
System.out.println("----------------");

System.out.println("Profile");

System.out.println("Welcome!");
System.out.println("----------------");
With a Method
static void showHeader() {

    System.out.println("Welcome!");
    System.out.println("----------------");

}

showHeader();

System.out.println("Dashboard");

showHeader();

System.out.println("Profile");

showHeader();

Real-World Analogy

Think of a coffee machine. You provide inputs, the machine performs a predefined process, and it may produce an output.

Coffee Machine Analogy
INPUTS

Coffee Type
Sugar Level
Cup Size

     │
     ▼

┌──────────────────────┐
│                      │
│    MAKE COFFEE       │
│                      │
│  Grind               │
│  Heat Water          │
│  Brew                │
│  Add Sugar           │
│                      │
└──────────────────────┘

     │
     ▼

OUTPUT

Prepared Coffee

A Java method works similarly. Parameters provide input, the method body performs the task, and the return value provides an optional result.

How Methods Work

Method Process
PROGRAM EXECUTION

        │
        ▼

CALL METHOD

        │
        ▼

PASS ARGUMENTS

        │
        ▼

METHOD RECEIVES PARAMETERS

        │
        ▼

EXECUTE METHOD BODY

        │
        ▼

OPTIONALLY RETURN VALUE

        │
        ▼

CONTINUE FROM CALLING LOCATION

Method Anatomy

Method Anatomy
public static int add(
        int first,
        int second
) {

    int result =
            first + second;

    return result;

}
Method Parts
public

ACCESS MODIFIER


static

NON-ACCESS MODIFIER


int

RETURN TYPE


add

METHOD NAME


(int first, int second)

PARAMETER LIST


{

    METHOD BODY

}


return result;

RETURN STATEMENT

Method Syntax

General Syntax
accessModifier static returnType methodName(
        parameterType parameterName
) {

    // Method body

    return value;

}
Main Method Components
  • Access modifier controls visibility.
  • static determines whether an object is required.
  • Return type describes the result.
  • Method name identifies the method.
  • Parameters receive input.
  • The method body contains executable statements.
  • return sends a result back to the caller.

Declaring a Method

Method Declaration
static void displayMessage() {

    System.out.println(
            "Learning Java Methods"
    );

}

Declaring a method defines what the method is called, what inputs it accepts, what type of result it returns, and what work it performs.

Calling a Method

A method call tells Java to execute the method.

Method Call
displayMessage();
Complete Example
public class Main {

    static void displayMessage() {

        System.out.println(
                "Learning Java Methods"
        );

    }

    public static void main(String[] args) {

        displayMessage();

    }
}

Method Execution Flow

Execution Flow Example
public class Main {

    static void greet() {

        System.out.println(
                "Inside greet"
        );

    }

    public static void main(String[] args) {

        System.out.println(
                "Before method"
        );

        greet();

        System.out.println(
                "After method"
        );

    }
}
Execution Flow
main STARTS

     │
     ▼

PRINT "Before method"

     │
     ▼

CALL greet()

     │
     ▼

ENTER greet()

     │
     ▼

PRINT "Inside greet"

     │
     ▼

greet() ENDS

     │
     ▼

RETURN TO main

     │
     ▼

PRINT "After method"

     │
     ▼

main ENDS
Output
Before method
Inside greet
After method

void Methods

A void method performs a task but does not return a value to the caller.

void Method
static void showMessage() {

    System.out.println(
            "No value is returned"
    );

}

Basic void Method

Print Separator
static void printSeparator() {

    System.out.println(
            "--------------------"
    );

}
Use Method
printSeparator();

System.out.println(
        "Java Course"
);

printSeparator();

Calling a Method Multiple Times

Multiple Calls
public class Main {

    static void greet() {

        System.out.println(
                "Welcome!"
        );

    }

    public static void main(String[] args) {

        greet();
        greet();
        greet();

    }
}
Output
Welcome!
Welcome!
Welcome!

Methods with Parameters

Parameters allow a method to receive data from the caller. They make methods flexible because the same method can work with different values.

Method with Parameter
static void greet(String name) {

    System.out.println(
            "Hello, " + name
    );

}

Parameters vs Arguments

Parameter and Argument
static void greet(String name) {

    System.out.println(
            "Hello, " + name
    );

}

greet("Aarav");
Difference
PARAMETER

String name

Variable declared in method definition


ARGUMENT

"Aarav"

Actual value supplied during method call

Single Parameter

Single Parameter
static void printSquare(int number) {

    System.out.println(
            number * number
    );

}

printSquare(5);
printSquare(10);
Output
25
100

Multiple Parameters

Multiple Parameters
static void displayUser(
        String name,
        int age
) {

    System.out.println(
            "Name: " + name
    );

    System.out.println(
            "Age: " + age
    );

}

displayUser("Aarav", 25);

Parameter Types

Different Parameter Types
static void showProduct(
        String name,
        double price,
        int quantity,
        boolean available
) {

    System.out.println(
            "Product: " + name
    );

    System.out.println(
            "Price: " + price
    );

    System.out.println(
            "Quantity: " + quantity
    );

    System.out.println(
            "Available: " + available
    );

}

Argument Order

Arguments must match the parameter list in number, compatible type, and order.

Correct Order
static void createUser(
        String name,
        int age
) {

}

createUser("Aarav", 25);
Incorrect Order
// Compilation error

createUser(25, "Aarav");

Methods with Return Values

A method can calculate or create a value and return it to the caller.

Return Value
static int add(
        int first,
        int second
) {

    return first + second;

}

return Statement

The return statement immediately ends the current method and optionally sends a value back to the caller.

Return Result
static int multiply(
        int first,
        int second
) {

    int result =
            first * second;

    return result;

}

Returning int

Return int
static int square(int number) {

    return number * number;

}

int result = square(6);

System.out.println(result);

Returning double

Return double
static double calculateAverage(
        double first,
        double second
) {

    return (first + second) / 2;

}

Returning boolean

Return boolean
static boolean isEven(int number) {

    return number % 2 == 0;

}

System.out.println(
        isEven(10)
);

Returning String

Return String
static String getGrade(int marks) {

    if (marks >= 90) {

        return "A";

    } else if (marks >= 75) {

        return "B";

    } else if (marks >= 60) {

        return "C";

    }

    return "D";

}

Using Returned Values

Store Result
int total = add(10, 20);

System.out.println(total);
Use Directly
System.out.println(
        add(10, 20)
);
Use in Expression
int finalTotal =
        add(10, 20) + 50;
Use as Argument
System.out.println(
        square(add(2, 3))
);

Return Type Rules

Return Type Rules
  • A void method does not return a result value.
  • A non-void method must return a compatible value.
  • Every reachable execution path of a non-void method must return a value.
  • The returned value must be compatible with the declared return type.
  • return immediately ends method execution.
  • Code after an unconditional return is unreachable.
Valid Return
static int getNumber() {

    return 10;

}
Invalid Return Type
static int getNumber() {

    // Compilation error
    return "Ten";

}

Early Return

An early return exits a method before reaching its final statement. It is useful for validation and special cases.

Early Return
static void withdraw(
        double balance,
        double amount
) {

    if (amount <= 0) {

        System.out.println(
                "Invalid amount"
        );

        return;

    }

    if (amount > balance) {

        System.out.println(
                "Insufficient balance"
        );

        return;

    }

    System.out.println(
            "Withdrawal successful"
    );

}

Unreachable Code

Unreachable Statement
static int getNumber() {

    return 10;

    // Compilation error
    // System.out.println("Hello");

}

Method Categories

Four Common Categories
METHODS

├── No Parameters
│   └── No Return Value
│
├── Parameters
│   └── No Return Value
│
├── No Parameters
│   └── Return Value
│
└── Parameters
    └── Return Value

No Parameters, No Return

Category 1
static void greet() {

    System.out.println(
            "Hello!"
    );

}

Parameters, No Return

Category 2
static void greet(String name) {

    System.out.println(
            "Hello, " + name
    );

}

No Parameters, Return Value

Category 3
static int getDefaultAge() {

    return 18;

}

Parameters and Return Value

Category 4
static int add(
        int first,
        int second
) {

    return first + second;

}

Static Methods

A static method belongs to the class itself rather than to a specific object.

Static Method
static void greet() {

    System.out.println(
            "Hello!"
    );

}

Why static is Used

The main method is static. Therefore, methods called directly from main are commonly declared static while learning procedural Java programming.

Static Call from main
public class Main {

    static void greet() {

        System.out.println(
                "Hello!"
        );

    }

    public static void main(String[] args) {

        greet();

    }
}

Calling Static Methods

Direct Call
greet();
Class Name Call
Main.greet();
Preferred Style
  • Inside the same class, a static method may be called directly.
  • From another class, static methods are commonly called using the class name.
  • Using the class name makes ownership clear.

Instance Methods

An instance method belongs to an object and requires an object before it can be called.

Instance Method
public class Main {

    void greet() {

        System.out.println(
                "Hello!"
        );

    }

    public static void main(String[] args) {

        Main object =
                new Main();

        object.greet();

    }
}

Static vs Instance Methods

Comparison
STATIC METHOD

Belongs to class
No object required
Called using class name
Cannot directly use instance members


INSTANCE METHOD

Belongs to object
Object required
Called using object reference
Can directly use instance members

Built-in Methods

Java provides many predefined methods through its standard library.

Built-in Method Examples
String name = "Java";

System.out.println(
        name.length()
);

System.out.println(
        Math.max(10, 20)
);

System.out.println(
        Math.sqrt(81)
);

String Methods

String Methods
String text = "Java Programming";

System.out.println(
        text.length()
);

System.out.println(
        text.toUpperCase()
);

System.out.println(
        text.toLowerCase()
);

System.out.println(
        text.contains("Java")
);

Math Methods

Math Methods
System.out.println(
        Math.max(10, 20)
);

System.out.println(
        Math.min(10, 20)
);

System.out.println(
        Math.sqrt(64)
);

System.out.println(
        Math.pow(2, 5)
);

System.out.println(
        Math.abs(-50)
);

Method Overloading

Method overloading allows multiple methods in the same class to have the same name as long as their parameter lists are different.

Overloaded Methods
static int add(
        int first,
        int second
) {

    return first + second;

}

static double add(
        double first,
        double second
) {

    return first + second;

}

Overloading by Parameter Count

Different Parameter Count
static int add(
        int first,
        int second
) {

    return first + second;

}

static int add(
        int first,
        int second,
        int third
) {

    return first + second + third;

}

Overloading by Parameter Type

Different Parameter Types
static void display(int value) {

    System.out.println(
            "Integer: " + value
    );

}

static void display(String value) {

    System.out.println(
            "String: " + value
    );

}

Overloading by Parameter Order

Different Parameter Order
static void show(
        String name,
        int age
) {

}

static void show(
        int age,
        String name
) {

}

Invalid Overloading

Changing only the return type does not create a valid overloaded method.

Invalid Overloading
static int calculate(int number) {

    return number * 2;

}

// Compilation error

static double calculate(int number) {

    return number * 2.0;

}

How Java Selects an Overload

Overload Resolution
static void show(int value) {

    System.out.println("int");

}

static void show(double value) {

    System.out.println("double");

}

show(10);

show(10.5);
Output
int
double
Overload Selection
  • Java examines the method name.
  • Java compares the number of arguments.
  • Java compares argument types.
  • Java selects the most specific compatible method.
  • Ambiguous calls cause compilation errors.

Variable Arguments

Variable arguments, called varargs, allow a method to receive zero or more values of the same type.

Varargs Syntax

Syntax
static void methodName(
        dataType... values
) {

}

Varargs Example

Sum Any Number of Values
static int sum(int... numbers) {

    int total = 0;

    for (int number : numbers) {

        total += number;

    }

    return total;

}

System.out.println(
        sum()
);

System.out.println(
        sum(10, 20)
);

System.out.println(
        sum(10, 20, 30, 40)
);

Varargs with Other Parameters

Regular Parameter and Varargs
static void printNumbers(
        String label,
        int... numbers
) {

    System.out.println(label);

    for (int number : numbers) {

        System.out.println(number);

    }

}

Varargs Rules

Varargs Rules
  • A method can have only one varargs parameter.
  • The varargs parameter must be the last parameter.
  • Inside the method, varargs behave like an array.
  • The caller may pass zero or more values.
  • An array can also be passed directly to a compatible varargs parameter.

Method Scope

Scope determines where a variable can be accessed.

Method Scope
static void firstMethod() {

    int number = 10;

    System.out.println(number);

}

static void secondMethod() {

    // Cannot access number here

}

Local Variables

A variable declared inside a method is called a local variable. It exists only during that method call and can only be accessed within its scope.

Local Variable
static void calculate() {

    int result = 10 + 20;

    System.out.println(result);

}

Parameter Scope

Parameter Scope
static void greet(String name) {

    System.out.println(name);

}

// name is not accessible here

Block Scope

Block Scope
static void check(int number) {

    if (number > 0) {

        String message =
                "Positive";

        System.out.println(message);

    }

    // message is not accessible here

}

Variable Shadowing

Variable shadowing occurs when a local variable or parameter has the same name as a variable declared in an outer scope.

Variable Shadowing
public class Main {

    static int number = 100;

    static void show() {

        int number = 50;

        System.out.println(number);

    }

}
Output
50

Java Pass-by-Value

Java always passes arguments by value. The method receives a copy of the value supplied by the caller.

Important Rule
  • Java is always pass-by-value.
  • Primitive values are copied.
  • Object reference values are also copied.
  • Java does not use pass-by-reference.

Primitive Arguments

Primitive Pass-by-Value
static void change(int number) {

    number = 100;

}

public static void main(String[] args) {

    int value = 10;

    change(value);

    System.out.println(value);

}
Output
10

The method changes only its local copy. The original primitive variable remains unchanged.

Reference Arguments

When an object is passed to a method, Java copies the reference value. Both the original reference and the copied reference can point to the same object.

Reference Copy
ORIGINAL REFERENCE

        │
        ▼

      OBJECT
        ▲
        │

COPIED REFERENCE

Both references point to the same object

Can a Method Change an Object?

Yes. A method can modify the state of an object through its copied reference because both references point to the same object.

Modify Array Content
static void changeFirst(
        int[] numbers
) {

    numbers[0] = 999;

}

public static void main(String[] args) {

    int[] values = {
        10, 20, 30
    };

    changeFirst(values);

    System.out.println(
            values[0]
    );

}
Output
999

Can a Method Change a Reference?

Reassigning the copied reference inside a method does not change the caller reference.

Reassign Copied Reference
static void replace(
        int[] numbers
) {

    numbers = new int[] {
        100, 200, 300
    };

}

public static void main(String[] args) {

    int[] values = {
        10, 20, 30
    };

    replace(values);

    System.out.println(
            values[0]
    );

}
Output
10

Arrays as Method Arguments

Array Parameter
static void printArray(
        int[] numbers
) {

    for (int number : numbers) {

        System.out.println(number);

    }

}

int[] values = {
    10, 20, 30
};

printArray(values);

Returning Arrays

Return Array
static int[] createNumbers() {

    return new int[] {
        10, 20, 30
    };

}

int[] numbers =
        createNumbers();

Methods Calling Methods

Method Calls Another Method
static int square(int number) {

    return number * number;

}

static int sumOfSquares(
        int first,
        int second
) {

    return square(first)
            + square(second);

}

Call Stack

The call stack keeps track of active method calls. The most recently called method completes first.

Call Stack
main()

   CALLS

firstMethod()

   CALLS

secondMethod()


CALL STACK

┌────────────────────┐
│ secondMethod()     │  ← TOP
├────────────────────┤
│ firstMethod()      │
├────────────────────┤
│ main()             │
└────────────────────┘

Stack Frame

Each active method call has its own stack frame containing information such as parameters, local variables, and the location to return to after the method finishes.

Stack Frame Concept
METHOD CALL

┌──────────────────────────┐
│                          │
│  Parameters              │
│                          │
│  Local Variables         │
│                          │
│  Return Information      │
│                          │
└──────────────────────────┘

Nested Method Calls

Nested Calls
static int add(
        int first,
        int second
) {

    return first + second;

}

static int square(int number) {

    return number * number;

}

int result =
        square(
            add(2, 3)
        );

System.out.println(result);
Execution
add(2, 3)

     │
     ▼

returns 5

     │
     ▼

square(5)

     │
     ▼

returns 25

Recursion

Recursion occurs when a method calls itself to solve a smaller version of the same problem.

Recursive Structure
static void recursiveMethod() {

    recursiveMethod();

}
Incomplete Recursion
  • A recursive method cannot call itself forever.
  • It needs a stopping condition.
  • Without a stopping condition, the call stack keeps growing.
  • Eventually, StackOverflowError occurs.

How Recursion Works

Recursive Process
METHOD(3)

   │
   ▼

METHOD(2)

   │
   ▼

METHOD(1)

   │
   ▼

BASE CASE

   │
   ▼

RETURN

   │
   ▼

RETURN

   │
   ▼

RETURN

Base Case

The base case is the condition that stops recursion.

Base Case
static void countdown(int number) {

    if (number == 0) {

        return;

    }

    System.out.println(number);

    countdown(number - 1);

}

Recursive Case

The recursive case calls the same method with a smaller or simpler version of the problem.

Recursive Case
countdown(number - 1);

Factorial using Recursion

Recursive Factorial
static long factorial(int number) {

    if (number <= 1) {

        return 1;

    }

    return number
            * factorial(number - 1);

}
factorial(5)
factorial(5)

5 × factorial(4)

5 × 4 × factorial(3)

5 × 4 × 3 × factorial(2)

5 × 4 × 3 × 2 × factorial(1)

5 × 4 × 3 × 2 × 1

120

Countdown using Recursion

Recursive Countdown
static void countdown(int number) {

    if (number == 0) {

        System.out.println("Go!");

        return;

    }

    System.out.println(number);

    countdown(number - 1);

}

Fibonacci using Recursion

Recursive Fibonacci
static long fibonacci(int number) {

    if (number <= 1) {

        return number;

    }

    return fibonacci(number - 1)
            + fibonacci(number - 2);

}
Performance Warning
  • The simple recursive Fibonacci solution repeats many calculations.
  • Its performance becomes poor for larger values.
  • An iterative solution is usually more efficient.
  • Recursion is not automatically better than loops.

Recursion vs Loops

Comparison
LOOPS

Use repeated iteration
Usually use less memory
Often faster
Good for straightforward repetition


RECURSION

Method calls itself
Uses call stack
Can express recursive problems naturally
Requires a base case

Stack Overflow

Infinite Recursion
static void repeat() {

    repeat();

}

Each recursive call adds another stack frame. If recursion continues too deeply, the available stack space is exhausted and Java throws StackOverflowError.

Method Design

Good methods are not only syntactically correct. They should also be easy to understand, reuse, test, and maintain.

Single Responsibility

A method should ideally perform one clear task.

Focused Methods
static double calculateTotal(
        double price,
        int quantity
) {

    return price * quantity;

}

static double calculateTax(
        double total,
        double taxRate
) {

    return total * taxRate;

}

static void printReceipt(
        double total
) {

    System.out.println(
            "Total: " + total
    );

}

Method Naming

Good Method Names
calculateTotal()

validateEmail()

findMaximum()

printReport()

isEligible()

hasPermission()

getUserName()

saveFile()
Poor Method Names
doIt()

process()

x()

method1()

handleEverything()

Method Length

Keep Methods Focused
  • There is no universal maximum number of lines.
  • A method should perform one understandable task.
  • Long methods often indicate multiple responsibilities.
  • Extract meaningful sections into smaller methods.
  • Do not split code into tiny methods without a clear benefit.

Pure Methods

A pure method returns a result based only on its inputs and does not modify external state.

Pure Method
static int add(
        int first,
        int second
) {

    return first + second;

}

Side Effects

A side effect occurs when a method changes something outside its local calculation, such as printing output, modifying an object, writing a file, or changing shared state.

Method with Side Effect
static void printMessage(
        String message
) {

    System.out.println(message);

}

Validation Methods

Age Validation
static boolean isValidAge(int age) {

    return age >= 0
            && age <= 120;

}
Password Validation
static boolean isValidPassword(
        String password
) {

    return password != null
            && password.length() >= 8;

}

Utility Methods

Utility Methods
static int square(int number) {

    return number * number;

}

static boolean isEven(int number) {

    return number % 2 == 0;

}

static int maximum(
        int first,
        int second
) {

    return first > second
            ? first
            : second;

}

Calculator using Methods

Calculator Methods
public class Main {

    static double add(
            double first,
            double second
    ) {

        return first + second;

    }

    static double subtract(
            double first,
            double second
    ) {

        return first - second;

    }

    static double multiply(
            double first,
            double second
    ) {

        return first * second;

    }

    static double divide(
            double first,
            double second
    ) {

        if (second == 0) {

            throw new IllegalArgumentException(
                    "Cannot divide by zero"
            );

        }

        return first / second;

    }

    public static void main(String[] args) {

        System.out.println(
                add(10, 5)
        );

        System.out.println(
                subtract(10, 5)
        );

        System.out.println(
                multiply(10, 5)
        );

        System.out.println(
                divide(10, 5)
        );

    }
}

Grade Calculator

Grade Method
static String calculateGrade(
        int marks
) {

    if (marks < 0 || marks > 100) {

        return "Invalid";

    }

    if (marks >= 90) {

        return "A";

    }

    if (marks >= 80) {

        return "B";

    }

    if (marks >= 70) {

        return "C";

    }

    if (marks >= 60) {

        return "D";

    }

    return "F";

}

Prime Number Method

Prime Check Method
static boolean isPrime(int number) {

    if (number <= 1) {

        return false;

    }

    for (
        int divisor = 2;
        divisor * divisor <= number;
        divisor++
    ) {

        if (number % divisor == 0) {

            return false;

        }

    }

    return true;

}

Factorial Method

Iterative Factorial Method
static long factorial(int number) {

    if (number < 0) {

        throw new IllegalArgumentException(
                "Number cannot be negative"
        );

    }

    long result = 1;

    for (
        int value = 2;
        value <= number;
        value++
    ) {

        result *= value;

    }

    return result;

}

Palindrome Method

Palindrome Check
static boolean isPalindrome(
        int number
) {

    int original = number;
    int reversed = 0;

    while (number != 0) {

        int digit =
                number % 10;

        reversed =
                reversed * 10 + digit;

        number /= 10;

    }

    return original == reversed;

}

Array Utility Methods

Calculate Sum
static int sum(int[] numbers) {

    int total = 0;

    for (int number : numbers) {

        total += number;

    }

    return total;

}
Find Maximum
static int findMaximum(
        int[] numbers
) {

    int maximum = numbers[0];

    for (int number : numbers) {

        if (number > maximum) {

            maximum = number;

        }

    }

    return maximum;

}
Calculate Average
static double average(
        int[] numbers
) {

    return (double) sum(numbers)
            / numbers.length;

}
Menu with Methods
import java.util.Scanner;

public class Main {

    static double add(
            double first,
            double second
    ) {

        return first + second;

    }

    static double subtract(
            double first,
            double second
    ) {

        return first - second;

    }

    static void showMenu() {

        System.out.println(
                "1. Add"
        );

        System.out.println(
                "2. Subtract"
        );

        System.out.println(
                "3. Exit"
        );

    }

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        int choice;

        do {

            showMenu();

            System.out.print(
                    "Enter choice: "
            );

            choice =
                    scanner.nextInt();

            if (choice == 1 || choice == 2) {

                System.out.print(
                        "Enter first number: "
                );

                double first =
                        scanner.nextDouble();

                System.out.print(
                        "Enter second number: "
                );

                double second =
                        scanner.nextDouble();

                if (choice == 1) {

                    System.out.println(
                            add(first, second)
                    );

                } else {

                    System.out.println(
                            subtract(first, second)
                    );

                }

            } else if (choice != 3) {

                System.out.println(
                        "Invalid choice"
                );

            }

        } while (choice != 3);

        System.out.println(
                "Program closed."
        );

    }
}

Common Method Errors

Common Errors
METHOD ERRORS

├── Forgetting Parentheses
├── Forgetting Return Type
├── Wrong Return Type
├── Missing Return Statement
├── Not Returning on Every Path
├── Returning Value from void Method
├── Ignoring Returned Value
├── Wrong Number of Arguments
├── Wrong Argument Types
├── Wrong Argument Order
├── Calling Instance Method Statically
├── Calling Non-Static Method from static Context
├── Duplicate Method Signature
├── Overloading Only by Return Type
├── Ambiguous Overloaded Call
├── Declaring Multiple Varargs Parameters
├── Placing Varargs Before Other Parameters
├── Accessing Local Variable Outside Scope
├── Assuming Primitive Argument Changes Original
├── Believing Java Uses Pass-by-Reference
├── Reassigning Reference and Expecting Caller to Change
├── Modifying Mutable Object Unexpectedly
├── Missing Recursive Base Case
├── Base Case Never Reached
├── Incorrect Recursive Progress
├── Infinite Recursion
├── Excessive Recursion Depth
├── StackOverflowError
├── Very Long Methods
├── Too Many Parameters
├── Unclear Method Names
├── Methods with Multiple Responsibilities
├── Hidden Side Effects
├── Duplicated Logic
├── Unnecessary Methods
├── Unreachable Code after return
└── Ignoring Input Validation

Best Practices

  • Give every method one clear responsibility.
  • Use descriptive method names.
  • Use camelCase for method names.
  • Prefer verb-based names for actions.
  • Use names like calculateTotal, validateEmail, printReport, and findMaximum.
  • Use is, has, and can prefixes for boolean methods when appropriate.
  • Keep method names consistent.
  • Avoid meaningless names such as doIt or method1.
  • Keep methods focused.
  • Avoid methods that perform unrelated tasks.
  • Extract repeated logic into reusable methods.
  • Avoid copying the same code into multiple places.
  • Use parameters to make methods flexible.
  • Avoid unnecessary parameters.
  • Keep parameter lists manageable.
  • Consider grouping related data when parameter lists become too long.
  • Use meaningful parameter names.
  • Match argument order carefully.
  • Choose return types deliberately.
  • Return calculated values when callers may need them.
  • Use void when the method performs an action without producing a reusable result.
  • Do not ignore useful returned values.
  • Use boolean return values for yes-or-no checks.
  • Use early returns to handle invalid conditions clearly.
  • Avoid deeply nested conditions when early return improves readability.
  • Ensure every non-void execution path returns a value.
  • Never place statements after an unconditional return.
  • Use method overloading when operations are conceptually the same.
  • Do not overload unrelated operations just because they can share a name.
  • Remember that return type alone cannot overload a method.
  • Avoid ambiguous overloads.
  • Use varargs when the number of same-type arguments is genuinely variable.
  • Keep the varargs parameter last.
  • Remember that only one varargs parameter is allowed.
  • Understand variable scope.
  • Keep local variables in the smallest useful scope.
  • Avoid unnecessary variable shadowing.
  • Remember that Java always uses pass-by-value.
  • Do not expect primitive arguments to change caller variables.
  • Understand that object reference values are copied.
  • Document methods that intentionally modify mutable objects.
  • Avoid unexpected side effects.
  • Prefer pure methods for calculations when practical.
  • Separate calculation from printing when reuse is useful.
  • Separate validation from business logic when programs become complex.
  • Use helper methods for repeated validation.
  • Validate method inputs.
  • Reject invalid arguments clearly.
  • Use exceptions when invalid input represents a programming or contract error.
  • Use arrays as parameters when a method processes multiple values.
  • Check arrays for required conditions before accessing elements.
  • Handle empty arrays when necessary.
  • Avoid accessing numbers[0] before verifying that an array is not empty.
  • Return arrays only when the caller genuinely needs multiple values.
  • Remember that returned arrays are mutable.
  • Use methods to organize menu-driven programs.
  • Keep input handling separate from calculations when possible.
  • Understand the call stack.
  • Remember that every active method call uses a stack frame.
  • Use recursion only when it makes the problem clearer.
  • Always define a recursive base case.
  • Ensure every recursive call moves toward the base case.
  • Avoid unnecessary deep recursion.
  • Prefer loops when recursion adds complexity without benefit.
  • Consider performance before using recursive Fibonacci.
  • Use iterative solutions for simple repeated calculations when appropriate.
  • Test methods independently.
  • Test normal inputs.
  • Test boundary values.
  • Test invalid inputs.
  • Test zero.
  • Test negative values when relevant.
  • Test empty strings when relevant.
  • Test empty arrays when relevant.
  • Test null when relevant.
  • Keep methods easy to read.
  • Use consistent indentation.
  • Use blank lines to separate logical steps.
  • Avoid excessive comments inside simple methods.
  • Comment why complex logic exists.
  • Write methods that are easy to reuse.
  • Write methods that are easy to test.
  • Write methods that are easy to change.
  • Prefer clarity over cleverness.

Method Selection Guide

Method Design Decisions
DOES THE TASK NEED INPUT?

        │
        ├── YES ─────► ADD PARAMETERS
        │
        └── NO ──────► NO PARAMETERS


DOES THE CALLER NEED A RESULT?

        │
        ├── YES ─────► RETURN A VALUE
        │
        └── NO ──────► void


DO MULTIPLE VERSIONS PERFORM
THE SAME CONCEPTUAL OPERATION?

        │
        ├── YES ─────► CONSIDER OVERLOADING
        │
        └── NO ──────► USE DIFFERENT NAMES


VARIABLE NUMBER OF SAME-TYPE VALUES?

        │
        ├── YES ─────► CONSIDER VARARGS
        │
        └── NO ──────► REGULAR PARAMETERS


PROBLEM NATURALLY DEFINED
IN TERMS OF SMALLER VERSIONS?

        │
        ├── YES ─────► CONSIDER RECURSION
        │
        └── NO ──────► USE NORMAL METHODS OR LOOPS

Method Checklist

Checklist
METHOD CHECKLIST

[ ] Method has one clear responsibility

[ ] Method name clearly describes its purpose

[ ] camelCase naming is used

[ ] Parameters are necessary

[ ] Parameter names are meaningful

[ ] Parameter order is logical

[ ] Parameter list is not unnecessarily long

[ ] Return type is correct

[ ] void is used only when no result is needed

[ ] Every non-void path returns a value

[ ] Returned value matches return type

[ ] No unreachable code follows return

[ ] Input values are validated when needed

[ ] Early returns improve clarity where appropriate

[ ] Static or instance behavior is intentional

[ ] Method is called correctly

[ ] Returned value is used when needed

[ ] Overloading represents the same operation

[ ] Overloaded signatures are genuinely different

[ ] Overloading does not depend only on return type

[ ] Overloaded calls are not ambiguous

[ ] Varargs is genuinely useful

[ ] Only one varargs parameter exists

[ ] Varargs parameter is last

[ ] Variable scope is understood

[ ] Local variables stay in appropriate scope

[ ] Variable shadowing is intentional

[ ] Java pass-by-value behavior is understood

[ ] Primitive arguments are not expected to change originals

[ ] Mutable objects are not modified unexpectedly

[ ] Array inputs are validated when needed

[ ] Empty arrays are handled when relevant

[ ] Recursive method has a base case

[ ] Recursive call moves toward base case

[ ] Recursion depth is reasonable

[ ] Loop would not be clearer than recursion

[ ] Method is not excessively long

[ ] Repeated logic has been extracted

[ ] Side effects are intentional

[ ] Method can be tested independently

[ ] Normal values are tested

[ ] Boundary values are tested

[ ] Invalid values are tested

[ ] Method remains readable and maintainable

Common Misconceptions

Avoid These Misconceptions
  • A method does not execute merely because it is declared.
  • A method executes when it is called.
  • Parameters are variables in the method declaration.
  • Arguments are actual values supplied during a call.
  • A void method does not return a result value.
  • A non-void method must return a compatible value.
  • return ends the current method immediately.
  • Code after an unconditional return is unreachable.
  • The caller does not have to store every returned value.
  • Ignoring a returned value is legal but may waste useful information.
  • Methods can be called multiple times.
  • Methods can call other methods.
  • Methods can call themselves.
  • Recursion requires a stopping condition.
  • Java is always pass-by-value.
  • Java does not use pass-by-reference.
  • Passing an object does not copy the entire object.
  • Java copies the object reference value.
  • A method can modify an object through the copied reference.
  • Reassigning a copied reference does not reassign the caller reference.
  • Arrays are objects.
  • Array contents can be modified through a method parameter.
  • Static methods belong to the class.
  • Instance methods belong to objects.
  • An instance method normally requires an object.
  • Method overloading requires different parameter lists.
  • Changing only the return type is not valid overloading.
  • Parameter names do not determine method signatures.
  • Varargs behave like arrays inside methods.
  • A method can have only one varargs parameter.
  • The varargs parameter must be last.
  • Local variables exist only within their scope.
  • Each method call gets its own local variables.
  • Each active method call uses a stack frame.
  • Recursive calls consume stack space.
  • Recursion is not always faster than loops.
  • More methods do not automatically make code better.
  • Methods should represent meaningful tasks.
  • Short code is not automatically readable code.
  • A good method should be easy to understand, test, and maintain.

Practice Exercises

Exercise 1: Greeting Method
  • Create a method named greet.
  • Accept a name as a parameter.
  • Print a personalized greeting.
  • Call the method with at least three names.
Exercise 2: Calculator Methods
  • Create add, subtract, multiply, and divide methods.
  • Accept two numbers in each method.
  • Return the calculated result.
  • Handle division by zero.
Exercise 3: Even Number Method
  • Create a method named isEven.
  • Accept an integer.
  • Return true when the number is even.
  • Return false otherwise.
Exercise 4: Maximum Method
  • Create a method that accepts three integers.
  • Return the largest value.
  • Do not use Math.max in the first solution.
  • Create a second solution using Math.max.
Exercise 5: Method Overloading
  • Create overloaded area methods.
  • Calculate the area of a square.
  • Calculate the area of a rectangle.
  • Calculate the area of a circle.
Exercise 6: Varargs Sum
  • Create a sum method using varargs.
  • Allow zero or more integer arguments.
  • Return the total.
  • Test with different argument counts.
Exercise 7: Prime Number Method
  • Create an isPrime method.
  • Accept one integer.
  • Return a boolean result.
  • Test negative values, zero, one, two, and larger numbers.
Exercise 8: Array Methods
  • Create a method to calculate array sum.
  • Create a method to calculate array average.
  • Create a method to find the maximum.
  • Create a method to find the minimum.
Exercise 9: Recursive Factorial
  • Create a recursive factorial method.
  • Define a correct base case.
  • Test 0, 1, and positive values.
  • Compare it with an iterative solution.
Exercise 10: Menu Program
  • Create a menu-driven calculator.
  • Use separate methods for displaying the menu.
  • Use separate methods for calculations.
  • Keep the main method focused on program flow.

Common Interview Questions

What is a method in Java?

A method is a named block of code designed to perform a specific task and executed when it is called.

What is the difference between a parameter and an argument?

A parameter is a variable declared in a method definition, while an argument is the actual value supplied during a method call.

What is a return type?

The return type specifies the type of value a method sends back to its caller.

What does void mean?

void means the method does not return a result value.

What does the return statement do?

It immediately ends the current method and optionally sends a value back to the caller.

What is method overloading?

Method overloading allows multiple methods in the same class to share a name while having different parameter lists.

Can methods be overloaded only by changing the return type?

No. The parameter list must be different.

What are varargs?

Varargs allow a method to accept zero or more values of the same type.

Is Java pass-by-value or pass-by-reference?

Java is always pass-by-value.

What happens when an object is passed to a method?

A copy of the object reference value is passed. The copied reference can still point to and modify the same object.

What is recursion?

Recursion occurs when a method calls itself to solve a smaller version of the same problem.

What is a base case?

A base case is the condition that stops recursive calls.

What is the call stack?

The call stack tracks active method calls and their execution state.

What is a stack frame?

A stack frame stores information for one active method call, including parameters, local variables, and return information.

What causes StackOverflowError?

It commonly occurs when recursion is too deep or never reaches a stopping condition.

Frequently Asked Questions

Should every piece of code be placed in a method?

Executable Java code belongs inside methods, constructors, initialization blocks, or similar language structures, but not every small expression needs its own separate method.

How many parameters can a method have?

Java allows many parameters, but a long parameter list often makes a method harder to use and maintain.

Can a method return multiple values?

A method directly returns one value, but that value can be an array, object, record, or collection containing multiple pieces of data.

Can a method call itself?

Yes. This is called recursion.

Can a void method use return?

Yes. A void method can use return without a value to end execution early.

Can static methods call instance methods directly?

No. A static method needs an object reference to call an instance method.

Can instance methods call static methods?

Yes. Static methods can be called from instance methods.

Are methods and functions the same?

The terms are similar, but in Java executable functions are defined as methods inside classes.

Should I use recursion or loops?

Use the approach that makes the solution clearest and sufficiently efficient. Loops are often better for straightforward repetition, while recursion can naturally express recursive structures.

What should I learn after methods?

The next lesson covers arrays in Java.

Key Takeaways

  • A method is a named block of reusable code.
  • Methods perform specific tasks.
  • Methods execute when called.
  • Methods improve code reuse.
  • Methods improve modularity.
  • Methods improve readability.
  • Methods improve maintainability.
  • Methods make testing easier.
  • Methods make debugging easier.
  • A method declaration defines the method.
  • A method call executes the method.
  • Method execution returns to the caller when the method ends.
  • A method can receive input through parameters.
  • Arguments are actual values passed during calls.
  • Parameters and arguments are different concepts.
  • Argument count must match the method requirements.
  • Argument types must be compatible.
  • Argument order matters.
  • A void method does not return a result value.
  • A non-void method returns a value.
  • The return type describes the result type.
  • The return statement ends method execution.
  • return can send a value to the caller.
  • A void method can use return without a value.
  • Early returns can simplify validation logic.
  • Code after an unconditional return is unreachable.
  • Methods can have no parameters and no return value.
  • Methods can have parameters and no return value.
  • Methods can have no parameters and return a value.
  • Methods can have parameters and return a value.
  • Static methods belong to classes.
  • Instance methods belong to objects.
  • Static methods do not require an object.
  • Instance methods normally require an object.
  • Java provides many built-in methods.
  • String provides useful text methods.
  • Math provides useful mathematical methods.
  • Method overloading allows the same method name with different parameter lists.
  • Overloading can differ by parameter count.
  • Overloading can differ by parameter type.
  • Overloading can differ by parameter order.
  • Changing only the return type is not valid overloading.
  • Java selects overloaded methods based on compatible arguments.
  • Varargs accept zero or more values.
  • Varargs behave like arrays inside methods.
  • Only one varargs parameter is allowed.
  • The varargs parameter must be last.
  • Scope determines where variables can be accessed.
  • Local variables belong to their local scope.
  • Parameters belong to the method scope.
  • Variables declared inside blocks belong to those blocks.
  • Variable shadowing can hide an outer variable.
  • Java is always pass-by-value.
  • Primitive values are copied.
  • Object reference values are copied.
  • Java does not use pass-by-reference.
  • A copied reference can point to the same object.
  • A method can modify mutable object state.
  • Reassigning a copied reference does not reassign the caller reference.
  • Arrays can be passed to methods.
  • Arrays can be returned from methods.
  • Methods can call other methods.
  • Nested method calls are evaluated from the inside outward.
  • The call stack tracks active method calls.
  • Each method call has a stack frame.
  • Recursion occurs when a method calls itself.
  • Recursive methods need a base case.
  • Recursive calls must move toward the base case.
  • Missing base cases can cause StackOverflowError.
  • Recursion uses stack space.
  • Loops are often more efficient for simple repetition.
  • Good methods have clear responsibilities.
  • Good method names describe behavior.
  • Boolean methods often use is, has, or can.
  • Pure methods return results without changing external state.
  • Side effects change something outside the local calculation.
  • Validation logic can be placed in reusable methods.
  • Utility methods perform reusable operations.
  • Methods should be easy to understand.
  • Methods should be easy to test.
  • Methods should be easy to reuse.
  • Methods should be easy to maintain.

Summary

Methods allow Java programs to divide complex problems into smaller, reusable, and understandable units. Instead of placing every statement inside the main method, developers create focused methods that perform specific tasks.

A method declaration defines its modifiers, return type, name, parameters, and body. A method call transfers execution to the method, and execution returns to the caller when the method finishes.

Parameters allow methods to receive input, while return values allow methods to send results back to callers. Methods can be designed with or without parameters and with or without return values.

Static methods belong to classes, while instance methods belong to objects. During the early stages of Java programming, static methods are commonly used with the static main method.

Method overloading allows multiple methods to share a name when their parameter lists differ. Variable arguments allow a method to accept a flexible number of values.

Java always uses pass-by-value. Primitive values are copied directly, while object reference values are copied. A copied reference can modify the same object, but reassigning that copied reference does not change the caller reference.

The call stack tracks active method calls, and every active call has its own stack frame. Recursion uses this mechanism by allowing a method to call itself until a base case is reached.

Well-designed methods have clear names, focused responsibilities, appropriate parameters, meaningful return values, controlled side effects, and predictable behavior.

Learning to design methods correctly is essential because methods form the foundation for classes, objects, constructors, inheritance, interfaces, and almost every advanced Java concept.

Lesson 14 Completed
  • You understand what methods are.
  • You understand why methods are needed.
  • You understand how methods work.
  • You understand method anatomy.
  • You know method syntax.
  • You can declare methods.
  • You can call methods.
  • You understand method execution flow.
  • You can create void methods.
  • You can call methods multiple times.
  • You can create methods with parameters.
  • You understand parameters and arguments.
  • You can use single parameters.
  • You can use multiple parameters.
  • You understand parameter types.
  • You understand argument order.
  • You can create methods with return values.
  • You understand the return statement.
  • You can return int values.
  • You can return double values.
  • You can return boolean values.
  • You can return String values.
  • You can use returned values.
  • You understand return type rules.
  • You can use early returns.
  • You understand unreachable code.
  • You understand the four common method categories.
  • You understand static methods.
  • You understand why static is commonly used with main.
  • You can call static methods.
  • You understand instance methods.
  • You can compare static and instance methods.
  • You can use built-in methods.
  • You can use String methods.
  • You can use Math methods.
  • You understand method overloading.
  • You can overload by parameter count.
  • You can overload by parameter type.
  • You can overload by parameter order.
  • You understand invalid overloading.
  • You understand overload resolution.
  • You can use variable arguments.
  • You understand varargs syntax.
  • You can combine regular parameters with varargs.
  • You understand varargs rules.
  • You understand method scope.
  • You understand local variables.
  • You understand parameter scope.
  • You understand block scope.
  • You understand variable shadowing.
  • You understand Java pass-by-value.
  • You understand primitive arguments.
  • You understand reference arguments.
  • You understand how methods modify objects.
  • You understand why reassigning a reference does not change the caller reference.
  • You can pass arrays to methods.
  • You can return arrays from methods.
  • You can make methods call other methods.
  • You understand the call stack.
  • You understand stack frames.
  • You understand nested method calls.
  • You understand recursion.
  • You understand recursive execution.
  • You understand base cases.
  • You understand recursive cases.
  • You can calculate factorial recursively.
  • You can create recursive countdowns.
  • You understand recursive Fibonacci.
  • You can compare recursion and loops.
  • You understand StackOverflowError.
  • You understand method design.
  • You understand single responsibility.
  • You know how to name methods.
  • You understand method length considerations.
  • You understand pure methods.
  • You understand side effects.
  • You can create validation methods.
  • You can create utility methods.
  • You can build a calculator using methods.
  • You can build a grade calculator.
  • You can create a prime number method.
  • You can create a factorial method.
  • You can create a palindrome method.
  • You can create array utility methods.
  • You can organize menu-driven programs with methods.
  • You can identify common method errors.
  • You know method best practices.
  • You know how to choose an appropriate method design.
  • You are ready to learn arrays.
Next Lesson →

Arrays in Java