Lesson Overview
This lesson explains how to define and call methods, pass arguments, return values, pass arrays, and overload methods.
What Is a Method?
A method is a named block of code that performs a specific task. In procedural languages, similar blocks may be called procedures, functions, or subroutines. In Java, they are called methods.
Methods help make programs easier to read, test, and reuse.
Parts of a Method Header
A method header usually contains:
| Part | Example | Meaning |
|---|---|---|
| Access modifier | public | Controls visibility |
static optional keyword | static | Allows the method to belong to the class rather than an object |
| Return type | void, int, double | Type of value returned by the method |
| Method name | greet | Identifier used to call the method |
| Parameter list | (int number) | Values the method can receive |
Example:
public static void greet() {
System.out.println("Welcome!");
}
Activity: Simple Method with No Argument and No Return Value
Methods with Arguments
A method can receive values through parameters. The values sent during the method call are called arguments.
The number and type of arguments in the call must match the method's parameter list.
Activity: Method with One Argument
Activity: Method with Multiple Arguments
Methods That Return Values
A method can send a value back to the statement that called it. The method's return type must match the returned value.
public static int square(int x) {
return x * x;
}
A void method does not return a value.
Activity: Method That Returns a Value
Calling Class Methods from Another Class
A static method belongs to a class. It can be called inside its own class using its name, or from another class using the class name followed by a dot.
Utility.greet();
The class containing the method must be compiled and available to the other class.
Activity: Calling a Method from Another Class
Passing Arrays to Methods
An entire array can be passed to a method by using the array name without brackets.
When an array is passed to a method, the method receives access to the same array object. Changes made to the array elements inside the method affect the original array.
Activity: Pass an Array to a Method
Method Overloading
Method overloading means creating multiple methods with the same name but different parameter lists. The compiler chooses which method to run based on the arguments used.
Methods can differ by:
- number of parameters
- parameter types
- parameter order
Return type alone is not enough to overload a method.
Activity: Overloaded Methods
Practice Exercises
Laboratory Exercises
Try It: Methods
Call the methods with different arguments and try writing your own method below main.