Skip to content
Study Hall
Lesson 1 of 3Methods
Unit 5 · Lesson 1 of 3

Writing and Calling Methods

What a method is, how to read a signature one piece at a time, the difference between void and returning, and exactly where execution goes when you call one.

6 min read10 practice questionsAsk AI about this →

Key things to remember

  1. 1A signature is: access modifier, static, return type, name, then the parameter list in brackets.
  2. 2void means the method hands nothing back; any other return type demands a return on every path.
  3. 3return supplies the value and ends the method immediately — nothing after it runs.
  4. 4A call pauses the current line, runs the method, and resumes at exactly the same point with the returned value.
  5. 5Method names are camelCase verbs starting with a lowercase letter: calculateAverage, not CalculateAverage or avg.
  6. 6Methods are written inside the class but outside every other method; they can never be nested.

Up to now everything has gone inside main, which works until it does not. A program that reads marks, validates them, averages them, finds the highest and prints a report is a few hundred lines in one block, and finding anything in it means reading all of it. A method is a named block of code you can run by writing its name. Once a job has a name, you can use it from three different places, test it on its own, and fix it in one spot instead of three.

  • Reuse: write the code once, then call it as many times as you like from anywhere in the program.
  • Naming: calculateAverage(marks) says what is happening; eight lines of loop leave the reader to work it out.
  • Testing in isolation: a small method can be checked on its own with a few values, which is far easier than testing a whole program at once.
  • DRY — Do not Repeat Yourself: duplicated code has to be fixed in every copy, and the copy you forget becomes the bug.
public static int square(int n) {
    return n * n;
}
//  |      |     |     |      |
//  |      |     |     |      +-- parameter list: what it needs, and of what type
//  |      |     |     +--------- name: what it is called
//  |      |     +--------------- return type: what kind of value it hands back
//  |      +--------------------- static: belongs to the class, not to an object
//  +---------------------------- access modifier: who is allowed to call it
The first line is the signature. Everything between the braces is the body.
PartExampleWhat it controls
Access modifierpublicWho may call the method. public means anywhere; private means only inside this class
staticstaticThe method belongs to the class itself, so no object is needed to call it
Return typeintThe type of value handed back. void means nothing is handed back
NamesquareHow you call it. By convention a verb in camelCase, starting lowercase
Parameter list(int n)The values the method needs, with a type and a name for each. Empty brackets mean it needs nothing
A call is a detour, not a restart — control always comes back to the next line.mainpublic static void main(String[] a) { System.out.print("A"); show(); System.out.print("C");}show()public static void show() { System.out.print("B");}121the call — main pauses and execution jumps into show()2the return — execution resumes at the very next line of mainOutput: A B C B lands in the middle because that is where the call sits.
Fig 1Execution jumps to the method, runs the body, and returns to the exact point it left.

void versus a returning method

A void method does something — it prints, it draws, it saves. A returning method produces something — a number, a string, a boolean — and hands it back to whoever called it. The difference matters at the call site: a returning method's result is a value, so it can be stored in a variable, used inside an expression or printed. A void call is a complete statement on its own and cannot appear on the right of an equals sign.

public class Greeter {

    // void: does something, hands nothing back
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // returning: produces a value the caller can use
    public static int square(int n) {
        return n * n;
    }

    public static void main(String[] args) {
        greet("Amara");                            // a whole statement on its own
        int result = square(7);                    // the value is stored
        System.out.println("7 squared is " + result);
        System.out.println(square(3) + square(4)); // used directly in an expression
    }
}

// Output:
// Hello, Amara!
// 7 squared is 49
// 25
square(3) + square(4) is 9 + 16 = 25 — a returning method can be used anywhere a value is allowed.
A returning method must return on every possible path
If the return type is anything other than void, Java insists that every route through the body ends at a return statement. Writing an if with a return inside it but nothing after the if gives the compile error missing return statement, because the compiler can see a path where the method would finish without producing the value it promised. Add a final return outside the if.
// Will NOT compile: missing return statement
public static int biggest(int a, int b) {
    if (a > b) {
        return a;
    }
    // what happens when a <= b? Java refuses to guess.
}

// Correct
public static int biggest(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;
}
The compiler traces every path through the method, so this error is caught before the program ever runs.

A return does two things at once: it supplies the value and it ends the method on the spot. Nothing after it runs. That is what makes the chain of ifs below correct without any else — if the first condition is true the method is already finished, so each later check can safely assume every earlier one failed.

public static String levelFor(int mark) {
    if (mark >= 80) {
        return "Level 4";      // reaching here ends the method at once
    }
    if (mark >= 70) {
        return "Level 3";      // only reached when mark < 80
    }
    if (mark >= 60) {
        return "Level 2";
    }
    if (mark >= 50) {
        return "Level 1";
    }
    return "Below Level 1";    // the catch-all path
}
levelFor(85) returns Level 4; levelFor(72) returns Level 3; levelFor(41) returns Below Level 1.

What happens when you call a method

A method call is a detour, not a jump. Java remembers precisely where it was, hands the argument values over, runs the method body from the top, and then comes back to the exact spot it left — with the returned value in hand, if there was one. The line that contained the call then finishes. Methods can call other methods, and Java keeps track of every level of detour, unwinding them in reverse order as each one returns.

StepWhat Java does
1Reaches the call int result = square(7); and pauses this line
2Evaluates the argument 7 and copies it into the parameter n
3Runs the body of square, computing 7 * 7
4Hits return 49; — the method ends and 49 travels back to the call
5The paused line resumes with 49 in place of the call, so result becomes 49
6Execution carries on with the next line of main
Calling a returning method and ignoring the result does nothing useful
Writing square(7); on a line by itself is legal Java. The method runs, computes 49, and throws it away, because nothing was done with the value. If the method's only purpose is to compute and return something, you must store the result, print it, or use it in an expression — otherwise the call is wasted work.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
This code appears three times in a program with different radii: double area = 3.14159 * r * r; System.out.println("Area: " + area);. Turn the calculation into a method.
Example 2
Given public static int triple(int n) { return n * 3; }, what does System.out.println(triple(4) + triple(triple(2))); print?
Example 3
Fix the compile error in public static String passOrFail(int mark) { if (mark >= 50) { return "Pass"; } }

Where marks get lost

  • Declaring a method void and then trying to store its result — int x = printTotal(); will not compile, because void produces no value.
  • Forgetting return in a non-void method, giving the compile error missing return statement at the method's closing brace.
  • Calling a returning method as a bare statement, so the value is computed and silently discarded.
  • Printing inside a method that was supposed to return, then finding it cannot be reused anywhere the value is needed rather than displayed.
  • Writing the parameter's type at the call site — square(int 7) — when types belong only in the definition.

Flashcards 10

What is a method?
Name the five parts of a method signature.
What does void mean?
What does return do?
+ 6 more

Practice

1
What does a return type of void tell you about a method?
2
Given public static int square(int n) { return n * n; }, what does square(square(3)) evaluate to?
3
Why does public static int biggest(int a, int b) { if (a > b) { return a; } } fail to compile?
4
What two things does a return statement do at the same time?
5
Order what Java does when it reaches the line int result = square(7);
  1. 1Store 49 in result and continue with the next line of main
  2. 2Hit return and send 49 back to the call site
  3. 3Run the body of square, computing 7 * 7
  4. 4Pause the current line in main
  5. 5Copy the argument 7 into the parameter n
6
Match each part of public static double average(int total, int count) to its meaning.
public
static
double
average
(int total, int count)
7
Which line correctly calls public static int square(int n) and keeps the answer?
8
Given public static int triple(int n) { return n * 3; }, what is printed by System.out.println(triple(4) + triple(2));?
9
The same eight lines of averaging code appear in four places in a program. What is the strongest argument for making it a method?
10
A method prints the average instead of returning it. Why is that usually the weaker design?

Spot a mistake on this page? Let us know