Beginner level · Module 2: Decisions, Loops and Methods in Java · Lesson 3 of 3
Writing Methods
Break programs into methods with parameters and return values, and understand variable scope.
In this lesson you will
- Write static methods that take parameters and return results
- Explain local scope and pass-by-value for primitives
Key concepts
method signaturereturn typeparametersscopeoverloading
The lesson
A method is a named block of code: static double total(int qty, double price) { return qty * price; }. The signature names the return type, the method name and the parameters. Calling total(3, 3500) returns 10500.0. A method with return type void does work but returns nothing.
Variables declared inside a method exist only while it runs — this is their scope. Java passes primitive values by copying them, so changing a parameter inside a method does not change the caller's variable.
Good methods do one job and have names that say what they do, such as isValidMark or calculateDiscount. Overloading lets two methods share a name if their parameter lists differ, for example area(double radius) and area(double width, double height).
Step by step
- Move the grade logic from the previous lesson into a method gradeFor(int mark).
- Write a boolean method isValidMark(int mark).
- Call both methods from main for several marks.
- Add an overloaded method that formats a mark with or without the grade.
Practice activity
Refactor the till program so that reading prices, calculating the average and printing the receipt are three separate methods called from main.
Expected result: main becomes a few lines of method calls, and the output is the same as before the refactor.
Check your understanding
-
What does a void method return?
Show answer
Nothing; it performs an action only.
-
If a method changes its int parameter, does the caller's variable change?
Show answer
No. Primitives are passed by value, so the method works on a copy.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.