Overview
This lecture covers Java methods: what they are, why they're used, how to define and call them, and basic method syntax.
Introduction to Java Methods
- A method is a block of code that runs when called.
- Methods can take data inputs called parameters.
- Methods are also known as functions in Java.
- Methods allow code reuse: define once, use many times.
Creating a Method in Java
- Methods must be declared inside a class.
- A method consists of its name followed by parentheses ().
- Java has pre-defined methods (e.g., System.out.println()) and allows custom methods.
- Example:
static void myMethod() {
// code to be executed
}
static means the method belongs to the class, not an object.
void means the method does not return any value.
Calling a Method
- Call a method by writing its name followed by parentheses and a semicolon:
myMethod();
- Methods can be called from the
main method or other methods.
- Methods can be called multiple times in a program.
- Example:
myMethod();
myMethod();
myMethod();
Key Terms & Definitions
- Method — A block of code that performs a specific action and runs when called.
- Parameter — Data passed into a method for use inside the method.
- Static — Indicates a method belongs to the class itself, not an instance/object.
- Void — Used as the return type to indicate a method does not return a value.
Action Items / Next Steps
- Practice creating and calling methods in a Java program.
- Read the next chapter on passing parameters to methods.