L9: Methods

Overview

  • Methods promote reusability and modularity by allowing you to group related statements together and give them a name. This makes programs easier to write, debug, and maintain.
  • Examples like System.out.println() in Java demonstrate how methods package common tasks into easily invokable structures.

Writing Methods

A method is a block of code designed to perform a specific task. It can take inputs (parameters), process them, and return a result.

Basic Structure

returnType methodName(parameters) {
    // method body
    return value; // if applicable
}
  • Example:

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

Parts of a Method Header

Return Type

  • Indicates what type of value the method will return. If the method doesn’t return anything, use void.

  • Examples of return types: intdoubleStringbooleanvoid.

  • The return type must match the type of the value being returned in the method body.

    double calculateArea(double length, double width) {
        return length * width;
    }
    
    void printMessage(String message) {
        System.out.println(message);
    }

Method Name

  • Should be descriptive and follow camelCase convention (e.g., calculateAreaprintReport).
  • Typically starts with a verb to indicate action.

Formal Parameters

  • The input values that the method requires to perform its task.

  • Defined as a type followed by a name (e.g., int num).

  • Multiple parameters are separated by commas in the method header.

    public static double calculateArea(double length, double width) {
        return length * width;
    }
  • When you call a method, the values you provide are called actual parameters or arguments.

Other Modifiers

  • public: The method can be accessed from any other class.

  • private: The method can only be accessed within the class it is defined in.

  • static: Belongs to the class itself rather than any specific instance. Can be called without creating an object of the class.

  • final: Prevents the method from being overridden in subclasses.

    public static int getMaxValue(int[] numbers) {
        // method implementation
    }

Keywords

return

  • Used to exit a method and optionally send a value back to the caller.

  • The data type of the returned value must match the method’s declared return type.

  • Once a return statement is executed, the method terminates, and any code after the return statement is not executed.

    public boolean isEven(int number) {
        if (number % 2 == 0) {
            return true;
        }
        return false;
    }
  • For methods with a void return type, no return statement is needed unless you want to exit the method early.

    public void printMessage(String message) {
        if (message == null) {
            return; // Exit the method if message is null
        }
        System.out.println(message);
    }

Method Overloading

  • Method overloading allows multiple methods with the same name but different parameters (number, order, or type) in the same class.
  • Rules for Overloading:
    • The methods must have the same name.
    • They must have different parameter lists (different number, types, or order of parameters).
    • The return type alone is not enough to distinguish overloaded methods.

Example of Method Overloading

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

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

public int add(int a, int b, int c) {
    return a + b + c;
}
  • In the above example:
    • The add method is overloaded with different parameter types (intdouble) and a different number of parameters.
    • The compiler determines which method to call based on the arguments passed during the method call.

Key Points

  • Method overloading improves code readability and reusability by providing a single method name that works for different inputs.
  • The correct method is selected at compile-time based on the arguments provided in the method call.
  • Examples include the built-in println() method, which is overloaded to handle different types of arguments (Stringintdouble, etc.).

Defining and Calling Methods

Defining a Method

  • To define a method, you provide its header followed by the method body:

    public static int multiply(int a, int b) {
        return a * b;
    }

Calling a Method

  • To call a method, use the method name followed by parentheses containing any required arguments:

    int result = multiply(4, 5);
    System.out.println(result);  // Outputs: 20

External Method Calls

  • Static Methods: To call a static method in another class, use the class name:

    int max = Math.max(10, 20);
  • Public Methods: When a method is marked public, it can be called from other classes if the classes are in the same project and accessible.

Benefits of Using Methods

  • Code Reusability: Write a block of code once and call it whenever needed.
  • Modularity: Break complex programs into smaller, manageable, and reusable parts.
  • Readability: Provide meaningful names to blocks of code, making it clear what the code does.