§ — — Object-Oriented Programming with Java
This lesson explains how to define and call methods, pass arguments, return values, pass arrays, and overload methods.
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.
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!");
}
ProReviewer — locked
Drills, code labs, and full solutions.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
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:
Return type alone is not enough to overload a method.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
Call the methods with different arguments and try writing your own method below main.
Done with this module? Track it — your progress shows on the subject list.
Up next
Classes and Objects→←Previous: Arrays and Strings