Why methods: naming and reuse
On This Lesson 11 topics
Lesson Overview
So far every program you have written lived inside main. That works for ten lines. At a hundred lines it becomes one long scroll where you cannot tell where the greeting ends and the calculation begins, and where a rule copied into three places has to be fixed in three places.
This module introduces the tool that solves both problems: the method, a named block of code that you write once and run as often as you like. Think of a recipe card in a kitchen. The card has a name ("Tomato sauce"), a list of steps, and a place on the shelf. When a cook needs sauce, they do not rewrite the steps from memory; they take the card and follow it. We will use that picture through the whole module.
You have been using methods since the first lesson: main is a method, and System.out.println(...) and nextInt() are methods somebody else wrote. Now you write your own.
This lesson builds on Module 8 (the shape of a Java program), Module 12 (decisions) and Module 13 (loops). The next lesson adds the missing piece: sending data into a method and getting a result back.
Learning Objectives
By the end of this lesson you will be able to:
- Define a method and explain the benefit of writing logic once and calling it by name.
- Read a simple method declaration: modifiers, return type, name, parentheses, body.
- Write and call a method that takes no input and returns nothing.
- Trace what happens at a method call: Java jumps to the method, runs it, then returns to the line after the call.
- Choose a clear, verb-based method name that follows Java's naming convention.
- Recognise when repeated or tangled code should become a method.
Written Explanation
What a method is
A method is a named block of code. You declare it once (write the recipe card) and call it whenever you need it (follow the card). Here is the smallest useful method:
static void greet() {
System.out.println("Hello!");
}Read it from left to right:
| Part | In greet | Meaning |
|---|---|---|
| Modifier | static | For now, write static on every method you call from main (see the note below) |
| Return type | void | The method gives nothing back; it only does something |
| Name | greet | The name you use to call it |
| Parameter list | () | Empty parentheses: no input yet (next lesson) |
| Body | { ... } | The steps to run |
The Oracle Java Tutorials list the same parts of a declaration and say that the return type, name, parentheses and body are the only required ones; modifiers are optional.
A note on static. In Module 8 you learned that static means a method belongs to the class itself and can be called without creating an object. Our main is static, and a static method can call other static methods of the same class directly by name. That is all we need for now. Objects, and methods that belong to them, come much later in the course.
Calling a method
To run a method, write its name followed by parentheses and a semicolon:
greet();That one line is a method call. When Java reaches it, the following happens:
- Java pauses
mainat the call. - It jumps into the method body and runs every statement there.
- When the body ends, Java returns to
mainand continues with the next line after the call.
The method only runs when it is called. Declaring greet and never calling it prints nothing, just as a recipe card on the shelf cooks nothing. The order of declarations in the file does not matter: main may be written above or below the methods it calls.
Why methods exist
Four benefits, all of which you will feel within a week.
- Reuse. Write the logic once, call it from anywhere. Three calls to
greet()replace three copies of theprintlnline. - One place to fix. If the greeting must change, edit one body. Copies pasted into five places are five chances to forget one.
- Readability. A call such as
printDivider()says what happens. The reader only looks inside when they need how. - Testing and debugging. A small method with one job can be checked on its own. When something breaks you can narrow the search to one method instead of one hundred lines.
This is why professional programmers treat the method as the basic unit of clean code, and why unit testing (Module 45) works on methods.
Naming: say what it does
A method name is the label on the recipe card. The Oracle tutorial's convention is a lowercase verb, or a name that starts with a lowercase verb and capitalises each further word (camelCase): run, printReport, calculateTax, isEmpty.
- Good:
printDivider,showMenu,calculateTax. You know what each does without opening it. - Weak:
doStuff,method1,process. You must read the body to learn anything. - Wrong by convention:
PrintDivider(capital first letter looks like a class) andprint_divider(underscores are for constants in Java).
Java is case sensitive, so greet and Greet are different names. Calling Greet() when you declared greet gives a compiler error you will see in Example 1.
When to extract a method
Turn code into a method when you notice one of these signs:
- Repetition. The same lines, or nearly the same, appear in two or more places.
- A name for a chunk. You find yourself writing a comment such as
// print the menuabove a block. The comment is a method name asking to get out. - Length.
mainno longer fits on one screen and you cannot summarise it in a sentence.
A useful rule of thumb is that a method should do one clear job. If you struggle to name a method without using the word "and" (readAndPrintAndSave), it probably does too much. This is a guideline, not a law; you will refine it as you write more code.
Examples
Example 1: your first method (simple)
public class Greeter {
static void greet() {
System.out.println("Hello!");
}
public static void main(String[] args) {
greet();
greet();
greet();
}
}Output (compiled and run with JDK 21):
Hello!
Hello!
Hello!Three calls, one body. Now see what the compiler says about the case mistake mentioned earlier. If main contained Greet(); instead, compilation would stop with:
Bad.java:7: error: cannot find symbol
Greet();
^
symbol: method Greet()
location: class BadRead it as: "you asked for a method called Greet, and this class has none." The fix is the spelling, not the logic.
Example 2: a divider reused (practical)
A report prints the same line of dashes in four places. Instead of four copies, name it.
public class Report {
static void printDivider() {
System.out.println("--------------------");
}
public static void main(String[] args) {
printDivider();
System.out.println("Sales report");
printDivider();
System.out.println("North: 120");
System.out.println("South: 95");
printDivider();
System.out.println("End of report");
printDivider();
}
}Output:
--------------------
Sales report
--------------------
North: 120
South: 95
--------------------
End of report
--------------------Need a different line style, say ====? Change one line in printDivider and all four dividers change. That is the "one place to fix" benefit in action.
Example 3: main as an outline (realistic)
Real programs read best when main is a table of contents and the methods hold the detail. Here is the skeleton of a small shop program.
public class Outline {
static void showWelcome() {
System.out.println("Welcome to the shop");
}
static void showMenu() {
System.out.println("1) Buy 2) Quit");
}
static void showGoodbye() {
System.out.println("Thanks, goodbye");
}
public static void main(String[] args) {
showWelcome();
showMenu();
showGoodbye();
}
}Output:
Welcome to the shop
1) Buy 2) Quit
Thanks, goodbyeEven if each method grows to twenty lines, main stays three lines and still tells the whole story. A new teammate reads main first, then opens only the method they care about. In Lesson 7 you will grow a calculator in exactly this way.
Backend Insight
A backend service is, at heart, a large collection of small methods with names like findCustomerById, calculateShipping and sendConfirmationEmail. A request arrives and a short top-level method calls a few of these in order, much like main in Example 3.
That structure pays off in daily work. When an invoice total is wrong, you do not search the whole program: you open calculateTotal. When the tax rule changes, you change it in one method and every feature that uses it gets the fix. And when you later write automated tests, you will test these methods one at a time. Reviewers also read method names first, so good names make code review faster and cheaper.
Common Mistakes
Mistake 1: Declaring a method but never calling it
static void greet() { System.out.println("Hello!"); }
public static void main(String[] args) { } // prints nothingA declaration is only the recipe card. Nothing runs until a call such as greet(); executes.
Mistake 2: Forgetting the parentheses in the call
Writing greet; is not a call. The compiler rejects it with not a statement, because a bare name is not something Java can execute. Always write greet();, with parentheses and a semicolon.
Mistake 3: Vague or wrongly cased names
doStuff() and method1() force every reader to open the body. PrintReport() compiles, but the capital letter breaks the convention and confuses readers, who expect capitalised names to be classes. Use printReport.
Mistake 4: One giant method, or many tiny ones that mean nothing
Extracting every single line into its own method makes the program harder to follow, not easier. Extract chunks that have a meaningful name and a single job.
Mistake 5: Copy-pasting instead of extracting
Pasting the same block twice feels quick. The cost arrives later, when a fix is applied to one copy and the other keeps the bug. If you paste the same code a second time, stop and make it a method.
Exercises
Try each exercise yourself before opening the solutions. Compile and run your answers where you can; menus differ between editors, but the command line works everywhere: javac File.java and then java File.
Level A: Foundation
A1. In one sentence, explain what a method is and what it does for you.
Show solution A1
A1. A method is a named block of code. You write it once and run it by calling its name, so you can reuse the logic, fix it in one place, and make the program easier to read.
A2. Look at static void printLine() { System.out.println("***"); }. Name its return type, its name, and say whether it takes input.
Show solution A2
A2. Return type void (nothing is returned), name printLine, and no input because the parentheses are empty.
A3. A program declares static void sayHi() and its main is empty. What does it print? Why?
Show solution A3
A3. It prints nothing. A method only runs when it is called, and main never calls sayHi.
Level B: Application
B1. This main repeats itself. Rewrite it with a method called printStars and calls to it:
System.out.println("*****");
System.out.println("Welcome");
System.out.println("*****");
System.out.println("Enjoy your stay");
System.out.println("*****");Show solution B1
B1.
static void printStars() {
System.out.println("*****");
}
public static void main(String[] args) {
printStars();
System.out.println("Welcome");
printStars();
System.out.println("Enjoy your stay");
printStars();
}B2. Predict the output of the program below, then say in which order the lines of code run.
static void a() { System.out.println("in a"); }
public static void main(String[] args) {
System.out.println("start");
a();
System.out.println("end");
}Show solution B2
B2. Output: start, in a, end, each on its own line. Order of execution: the first println in main, then the call to a() jumps into a and prints in a, then control returns to main and prints end.
B3. Suggest a better name for each: m1(), Show_Menu(), stuff() (it prints the main menu, a single line each).
Show solution B3
B3. m1 becomes showMenu (or printMenu). Show_Menu becomes showMenu, because Java uses camelCase and not underscores. stuff also becomes showMenu, since it should say what it does. Any clear verb-first name that fits is fine.
Level C: Challenge
C1. Write a program with three methods, printHeader, printBody and printFooter, that prints a short three-part notice. Make main contain only calls. Then change the footer text in one place and run again.
Show solution C1
C1. One possible answer:
static void printHeader() { System.out.println("== Notice =="); }
static void printBody() { System.out.println("The office opens at 9."); }
static void printFooter() { System.out.println("-- Management --"); }
public static void main(String[] args) {
printHeader();
printBody();
printFooter();
}Changing the text inside printFooter changes the footer everywhere it is used, with no edit to main.
C2. A colleague's main has 60 lines: it prints a menu, reads a choice, and prints the result for each choice. List three methods you would extract, with names, and explain how main would look afterwards. No code needed.
Show solution C2
C2. For example printMenu (prints the options), readChoice (reads and returns the user's choice) and printResult (prints the answer for a choice). main would then be a few lines: call printMenu, call readChoice, call printResult. Methods that return a value, such as readChoice, are covered in the next lesson.
Mini Challenge
Take any program you wrote in Module 12 or 13 that prints something more than once, such as a menu, a banner, or a table header. Extract the repeated printing into a method with a verb-first name, call it from the places where the copies were, and run the program to check that the output is identical to before.
Check your work: the program prints exactly what it printed before, the repeated lines now exist in only one place, and main is shorter.
Summary & Next Lesson
Key takeaways
- A method is a named block of code: declare it once, call it by name as many times as needed.
- A declaration has a return type (
voidif nothing comes back), a name, parentheses and a body. For now, mark methods called frommainasstatic. - A call jumps into the method, runs the body, and returns to the line after the call. A method never runs unless it is called.
- Methods give you reuse, a single place to fix a rule, readable code and units that can be tested.
- Name methods with a lowercase verb in camelCase, such as
printDivider, so that the name says what the method does.
Next lesson
Our methods so far take nothing in and give nothing back. The next lesson, "Parameters and return values", shows how to pass data into a method and get a result out of it, and why a method should usually compute or print, not both.
Self-check
- What is the main benefit of a method?
- What does
voidtell you about a method? - What happens in
mainwhen Java reaches the callprintDivider();? - Which of these follows Java's naming convention:
PrintDivider,print_divider,printDivider? - Name one sign that a block of code should become a method.
Show answers
- You write the logic once and reuse it by name, so there is one place to fix and the code reads better.
- That the method returns no value; it only performs actions.
- Java jumps into
printDivider, runs its body, then returns and continues with the next line inmain. printDivider.- The same lines are repeated, a comment labels a chunk of code, or
mainhas grown too long to summarise.
References
- Oracle, Defining Methods. Verified: the parts of a method declaration, which parts are required, and the naming convention of a lowercase verb followed by capitalised words.
- Oracle, The Java Language Specification, SE 21, Chapter 8 (Classes). The page loaded, but the section on methods lay outside the part I could read, so the
staticstatement relies on the course's earlier lesson (Module 8) rather than on a quoted line. - The compiler messages in Example 1 and the program outputs were produced by compiling and running the code with JDK 21 (
javac 21.0.10).
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.