Introduction to Java Methods: Definition, Invocation, and Parameter Passing – Get It After Reading

Introduction to Java Methods: Definition, Calling, and Parameter Passing

1. What is a Method?

In Java, a “method” is like a little tool. We can encapsulate repeated tasks (such as calculating the sum of two numbers or printing a text) into a method. When we need to use it later, we can simply “call” this method instead of writing the code repeatedly each time. It’s like writing the “chopping vegetables” step as a method when cooking—subsequent cooking can directly call this method, saving time and effort.

2. Method Definition Format

To define a method, we need to clarify its function, input, and output. The basic format of a Java method is as follows:

Modifier ReturnType MethodName(ParameterList) {
    // Method body: specific code to be executed by the method
    return ReturnValue; // If there is a return value, use return to return the result
}

Key Part Explanation:

  • Modifier: For now, understand public static (indicating a public, static method; details will be covered later). Beginners can initially ignore specifics.
  • ReturnType: Whether the method needs to return a result after execution. If yes, specify the type (e.g., int for integers, String for strings, void for no return value).
  • MethodName: Should reflect the method’s function, following camelCase naming (e.g., add, printName).
  • ParameterList: Data required when calling the method, formatted as ParameterType ParameterName1, ParameterType ParameterName2... (empty parentheses if no parameters).
  • MethodBody: Code within curly braces {}, representing the actual logic executed by the method.
  • return: If there is a return value, use return to return the corresponding type of result; for void methods, return; can be written or omitted.

Definition Example 1: No Parameters, No Return Value (Print Information)

public static void printHello() {
    // Method body: Print a sentence
    System.out.println("Hello, Method!");
}

Definition Example 2: With Parameters and Return Value (Calculate Sum of Two Numbers)

public static int add(int a, int b) {
    // Parameters a and b are formal parameters (parameters defined in the method)
    int sum = a + b;
    return sum; // Return the calculation result
}

3. Method Calling

After defining a method, we need to “call” it elsewhere to execute it. The calling format is: Object.MethodName(ParameterValues) (for static methods, it can also be directly ClassName.MethodName(ParameterValues)).

1. Calling a No-Parameter Method

public class MethodDemo {
    // Define the printHello method (from previous example)
    public static void printHello() {
        System.out.println("Hello, Method!");
    }

    public static void main(String[] args) {
        // Call the printHello method: write the method name directly with empty parentheses
        printHello(); // Output: Hello, Method!
    }
}

2. Calling a Parameterized Method

public class MethodDemo {
    // Define the add method (from previous example)
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        // Call the add method, passing actual parameters (specific values when calling)
        int result = add(3, 5); // Actual parameters 3 and 5 are passed to formal parameters a and b
        System.out.println("Result of 3+5: " + result); // Output: Result of 3+5: 8
    }
}

3. Notes on Calling

  • Matching Parameter Order and Type: The parameters passed when calling must match the parameter list in order and type with the method definition.
  • Handle Return Values: If the method has a return value (e.g., int), use a variable to receive the result when calling (e.g., int result = add(3,5)); for void methods with no return value, call directly.

4. Parameter Passing: The Mystery of Value Passing

Parameter passing is a crucial concept in Java methods. Here, we focus on parameter passing for basic data types (e.g., int, double, boolean).

1. Formal Parameters vs. Actual Parameters

  • Formal Parameters: Parameters declared in method definition (e.g., a and b in the add method), valid only within the method.
  • Actual Parameters: Specific values passed when calling the method (e.g., 3 and 5 in add(3,5)), which are the actual data passed to formal parameters.

2. Characteristics of Value Passing

Java uses value passing for parameter passing: When a method is called, the value of the actual parameter is “copied” and passed to the formal parameter. Modifications to the formal parameter do not affect the actual parameter.

Example: Basic Type Parameter Passing

public class ValuePassDemo {
    // Define a method to modify parameters
    public static void changeNum(int num) {
        num = 100; // Modify the value of the formal parameter num
        System.out.println("After modification inside the method, num = " + num); // Output: 100
    }

    public static void main(String[] args) {
        int x = 10; // Value of the actual parameter x
        System.out.println("Before calling the method, x = " + x); // Output: 10
        changeNum(x); // Call the method and pass x
        System.out.println("After calling the method, x = " + x); // Output: 10 (original x remains unchanged)
    }
}

Result Analysis:
When changeNum(x) is called, the value of x (10) is copied and passed to the formal parameter num. The method modifies num to 100, but the original variable x remains unaffected because they are independent variables.

3. Comparison: Reference Type Parameter Passing

If the parameter is a reference type (e.g., arrays, objects, String, ArrayList), the situation is different. For beginners, we focus on basic types first, and reference types will be covered in detail later.

5. Practice Exercise: Write a Method to Calculate Average

Requirement: Define a method that takes 3 int numbers and returns their average (result rounded down).

Code Example:

public class MethodPractice {
    // Define the method to calculate the average
    public static int average(int a, int b, int c) {
        int sum = a + b + c;
        return sum / 3; // Integer division, result is rounded down
    }

    public static void main(String[] args) {
        int avg = average(10, 20, 30);
        System.out.println("Average of the three numbers: " + avg); // Output: 20
    }
}

6. Summary

  • Method: A reusable code block that encapsulates functionality to improve code reusability.
  • Definition Format: Modifier ReturnType MethodName(ParameterList) { MethodBody; }
  • Calling Method: ClassName.MethodName(ActualParameters) (for static methods) or Object.MethodName(ActualParameters) (for non-static methods).
  • Parameter Passing: Basic type parameters use “value passing”—modifications to formal parameters do not affect actual parameters; reference types will be learned later.

With today’s learning, you’ve mastered the basics of Java methods. Next, try writing more methods with different functionalities (e.g., calculating Fibonacci sequences, determining prime numbers) to consolidate your knowledge!

Xiaoye