What Is a Method?
By the end of this lesson, you'll be able to:
- Define what a method is and why it exists
- Recognize the parts of a method: name, parameters, return type, body
- Explain how methods relate to the "don't repeat yourself" principle
Prerequisites: Module 8: "Project: Calculator"
The problem methods solve
In Module 8's calculator, the same tax-style formatting logic would need to repeat anywhere a Decimal needed to be shown with 2 decimal places. Copy-pasting that logic in ten places means ten places to fix if the formatting rule ever changes. A method solves this: write the logic once, give it a name, and call that name wherever you need it.
The anatomy of a method
public Integer square(Integer number) {
return number * number;
}
public— who can call this method (more on this in a later module).Integer(before the name) — the return type: what kind of value this method hands back.square— the method's name.(Integer number)— the parameter list: what data the method needs to do its job.{ ... }— the body: the actual instructions.
A real-world analogy: a vending machine
A vending machine has one button per snack, but internally it always follows the same steps: check payment, release item, return change. You don't need to know those internal steps every time — you press a button (call the method) and trust it does its job. That's exactly the relationship between calling a method and the code inside it.
Exercise
As a comment, name the four parts of a method signature shown in the square(Integer number) example above.
Show hint
Return type, name, parameters, body.
What Is a Method? Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A method is a named, reusable block of code — instead of copying the same instructions everywhere you need them, you write them once as a method and call that method by name.