Module 4

Module 4: Methods and Functions

🧩 Module 4: Methods and Functions

4.1 Introduction

Methods (also called functions) are blocks of code designed to perform specific tasks. They help make code reusable, organized, and easier to understand.

In this module, you’ll learn:

  • How to define and call methods
  • Parameters and return types
  • Method overloading
  • Variable scope
  • Recursion

4.2 What Is a Method?

A method is a named block of code that performs a task. You define it once, and call it multiple times.

public class Example {
    // Method definition
    static void greet() {
        System.out.println("Hello from a method!");
    }

    public static void main(String[] args) {
        greet(); // Method call
    }
}

Output: Hello from a method!

4.3 Method Syntax

modifier returnType methodName(parameterList) {
    // method body
}
  • modifier: defines access level (e.g., public, private, static)
  • returnType: the type of value returned by the method (or void if none)
  • methodName: the name of the method (use verbs)
  • parameterList: variables passed to the method

4.4 Methods with Parameters

public class Greeting {
    static void greetUser(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        greetUser("Alice");
        greetUser("Bob");
    }
}

Output:

Hello, Alice!
Hello, Bob!

4.5 Return Values

Methods can return a value using the return keyword.

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

    public static void main(String[] args) {
        int result = add(5, 3);
        System.out.println("Sum: " + result);
    }
}

4.6 Multiple Parameters and Return Types

static double average(double a, double b, double c) {
    return (a + b + c) / 3;
}

public static void main(String[] args) {
    double avg = average(10.5, 8.2, 9.0);
    System.out.println("Average: " + avg);
}

4.7 Method Overloading

Two or more methods can have the same name but different parameter lists.

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

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

public static void main(String[] args) {
    System.out.println(add(2, 3));       // calls int version
    System.out.println(add(2.5, 3.7));   // calls double version
}

4.8 Scope of Variables

The scope of a variable defines where it can be accessed.

  • Local variables: declared inside a method
  • Instance variables: declared inside a class, but outside any method
  • Static variables: shared across all instances of a class
public class Example {
    static int count = 0; // static variable

    void increment() {
        int step = 1;     // local variable
        count += step;
    }

    public static void main(String[] args) {
        Example e = new Example();
        e.increment();
        System.out.println(count);
    }
}

4.9 Recursion

Recursion occurs when a method calls itself. Commonly used in problems like factorials, Fibonacci, and tree traversal.

Example: Factorial

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

public static void main(String[] args) {
    System.out.println("Factorial of 5: " + factorial(5));
}

Output: Factorial of 5: 120

4.10 Passing Arrays to Methods

You can pass entire arrays as arguments to methods.

static int sumArray(int[] arr) {
    int sum = 0;
    for (int num : arr) {
        sum += num;
    }
    return sum;
}

public static void main(String[] args) {
    int[] numbers = {1, 2, 3, 4, 5};
    System.out.println("Sum: " + sumArray(numbers));
}

4.11 Best Practices for Methods

  • Use descriptive method names (e.g., calculateAverage()).
  • Keep methods short and focused on one task.
  • Limit the number of parameters.
  • Use comments and meaningful variable names.
  • Avoid deep recursion (can cause stack overflow).

4.12 Practice Exercises

  1. Temperature Converter: Write a method to convert Celsius to Fahrenheit and vice versa.
  2. Max Finder: Write a method that returns the largest of three numbers.
  3. Palindrome Checker: Write a method to check if a string is a palindrome.
  4. Sum of Digits: Create a recursive method that returns the sum of digits in an integer.
  5. Array Average: Write a method that takes an array and returns its average value.

4.13 Summary

  • Methods organize code into reusable blocks.
  • Parameters pass data; return types send results back.
  • Overloading allows multiple versions of a method with different arguments.
  • Variable scope controls visibility and lifespan of data.
  • Recursion allows a method to call itself for repetitive logic.

Next up: Module 5: Object-Oriented Programming (OOP) Basics — you’ll explore classes, objects, constructors, and encapsulation, forming the heart of Java development.

Latest Notes

View Archive [ -> ]