What is a Method?
- A method is a block of code that performs a specific task.
- It is like a function in other programming languages.
- Methods are used to:
- Break down complex problems into smaller pieces.
- Avoid code repetition.
- Improve code readability and maintainability.
- Once defined, a method can be called multiple times.
Why Use Methods?
- Reusability: Write once, use many times.
- Modularity: Divide program into logical parts.
- Abstraction: Hide implementation details.
- Ease of debugging: Test and fix individual methods.
- Code organization: Cleaner structure.
Method Declaration Syntax
accessModifier [static] returnType methodName(parameterList) {
// method body
// optionally return a value
}
- accessModifier:
public, private, protected, or default (package‑private).
- static: Optional – indicates class‑level method.
- returnType: Data type of value returned, or
void if nothing returned.
- methodName: Should be a verb in camelCase (e.g.,
calculateSum).
- parameterList: Comma‑separated list of input parameters (type + name).
Simple Method Example