java-foundations 16 min read

Methods: The Why and the Header

Naming a block of code so you can call it by name

In a nutshell

A method is a named block of code you can run on demand by writing its name with parentheses. You have already used dozens: System.out.println(...), Math.abs(...), kb.nextInt(). In this lesson you learn to read and write your own. Today’s job is small: spot the parts of a method, and tell the difference between declaring a method (writing the recipe) and calling it (running the recipe).

Today in three sentences. A method is a recipe. A call is a jump. The header tells you what the recipe is named, what it takes in, and what it gives back.

After this lesson, you will be able to:

  • Identify the five labeled pieces of any Java method header (access, storage, return type, name, parameter list) and say what each piece tells the reader.
  • Distinguish declaring a method from calling it. Predict what happens in a program where a method is declared but never called.
  • Write a one-line method that takes inputs and returns a value, and call it from main.

From CSCD 110. In Python you wrote def add(a, b): return a + b. Java does the same job with one extra requirement: every parameter and the return value must declare its type. Same idea, more paperwork up front, fewer surprises later.


The problem methods solve

After loops and conditionals, your programs can already do quite a lot. But as main grows past forty or fifty lines, two things start to hurt.

First, you cannot find anything. Where is the grade-calculation logic in a 300-line main? You scroll, you skim, you give up.

Second, you copy code. You compute average score for the first student, then again for the second student, then again for the third. Three near-identical blocks. Change the formula once and you have to change it in three places. Forget one, and you have a bug that appears only for student three.

A method names a block of code so you can call it by name and reuse it. Read this:

double average = computeAverage(scores);
String grade   = letterGrade(average);
printReport(name, average, grade);

You can read that out loud. You do not need to know how letterGrade works to know what it does. The what lives at the call site; the how lives somewhere else, where you can ignore it until you need it. That separation is the entire point of methods.

Check your understanding. A main method has 250 lines and does four things: read input, validate it, compute, print results. A reader who sees the file for the first time wants to find the validation step. Which of these helps the most?

Reveal answer

Splitting main into four method calls (readInput, validateInput, compute, printReport) so the body of main reads like a four-line outline. The reader then jumps to whichever method they care about. Comments help, but they are not enforced and they drift out of sync with the code. Method names are enforced (the compiler checks they exist) and they appear at the call site every time, so they cannot drift.


Anatomy of a method

Every method has two halves: a header and a body. The header tells the world about the method (what it is named, what it expects, what it gives back). The body is the recipe itself.

public static int add(int a, int b) {   // <-- header
    return a + b;                        // <-- body
}

The header has five labeled pieces. Read them left to right.

Position Piece What it tells the reader
1 public Access modifier. Who is allowed to call this method. For now it is always public.
2 static Storage class. This method belongs to the class itself, not to an instance of it. For now it is always static.
3 int Return type. What kind of value this method hands back. int, double, boolean, String, void, etc.
4 add Method name. A camelCase verb. The compiler uses this name (plus the parameter list) to find the method when someone calls it.
5 (int a, int b) Parameter list. The inputs the method accepts. Each parameter has a type and a name.

The body sits inside the curly braces. It runs only when the method is called. Until then it is just text on the page.

You will treat public and static as required boilerplate for the rest of this quarter. You’ll learn what they actually mean once you have classes (around Week 9). For now: write public static, and trust that it works.

Common pitfall: the parameter list is a contract, not a wish list. A method header announces exactly what the method takes in. If add is declared with (int a, int b), you cannot call it with one argument or with three, and you cannot call it with a String. The compiler will reject the call before the program runs.

Here is a second example. Read the header out loud before you read the body.

public static String letterGrade(int score) {
    if (score >= 90) return "A";
    if (score >= 80) return "B";
    if (score >= 70) return "C";
    if (score >= 60) return "D";
    return "F";
}

Out loud: public static, returns a String, named letterGrade, takes an int parameter named score. That sentence is everything you need to call this method correctly. You do not have to read the body.

Check your understanding. Look at this header. Name the five pieces.

public static double celsiusToFahrenheit(double c)
Reveal answer

Access: public. Storage: static. Return type: double. Name: celsiusToFahrenheit. Parameter list: (double c) — one parameter named c of type double. The method hands back a double and takes one double in. You can call it as celsiusToFahrenheit(0.0) and store the result in a double variable.

Check your understanding. Which of the following is not a legal method header?

A. public static int square(int n) B. public static void greet(String name) C. public static int max(int a, int b, int c) D. public static add(int a, int b)

Reveal answer

D. It is missing the return type. Every Java method header must declare a return type before the name (use void if the method returns nothing). The compiler error you would see is invalid method declaration; return type required.


Declaring vs calling: the jump

Writing a method header and body declares the method. The body does not run when the compiler reads it. A declaration is a recipe sitting in a cookbook: nobody is cooking yet.

public class Demo {

    public static int add(int a, int b) {
        System.out.println("inside add");
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println("hello");
        // nothing here calls add(), so add never runs
    }
}

Run this program. The output is one line: hello. The line inside add never prints, because add is declared but never called.

To call a method, you write its name followed by parentheses around the arguments. A call is a jump: the JVM pauses where it is, runs the method body all the way through, and then comes back exactly where it left off, holding the returned value (if any).

public class Demo {

    public static int add(int a, int b) {
        System.out.println("inside add");
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println("before");
        int sum = add(3, 4);                 // <-- call site: jump in, jump back
        System.out.println("after, sum = " + sum);
    }
}

Run that. The output is:

before
inside add
after, sum = 7

Notice the order. before prints first. Then control jumps into add, prints inside add, computes 3 + 4, returns 7. Control jumps back to main, holding the value 7, which gets stored in sum. Then after, sum = 7 prints.

The jump is the central mental model for the rest of this week. Every call site is a pair: jump out, then jump back with the answer.

You can call the same method multiple times, with different arguments each time. Each call is its own jump.

int a = add(1, 2);    // jumps in, returns 3
int b = add(10, 20);  // jumps in again, returns 30
int c = add(a, b);    // jumps in again, returns 33

Common pitfall: forgetting the parentheses on the call. add (no parens) is not a method call. It is the name of the method itself, which Java will treat as an attempt to use the method as a value (and reject). To call a no-argument method named printHeader, you must write printHeader(), including the empty parens.

Check your understanding. What does this program print?

public class Q {
    public static int square(int n) {
        return n * n;
    }

    public static void main(String[] args) {
        System.out.println("start");
        square(5);
        System.out.println("end");
    }
}
Reveal answer
start
end

The call square(5) runs and produces the value 25, but nothing in main stores or prints that value. The returned 25 is computed and immediately discarded. (Compilers do not warn about this for int-returning methods, so silently throwing away a return value is a real bug source. We come back to this in lesson 5c.)

Check your understanding. Which line is the call site?

public static int triple(int n) {     // line 1
    return n * 3;                     // line 2
}                                     // line 3

int result = triple(7);               // line 4
Reveal answer

Line 4 is the call site. Line 1 is the header (declaration). Lines 2–3 are the body. The expression triple(7) on line 4 is what runs the body and produces the value 21, which gets stored in result.


Wrap up and what’s next

Recap.

  • A method is a named recipe: a header (five pieces) and a body (the recipe itself).
  • The five header pieces left to right: access modifier, storage class, return type, method name, parameter list.
  • Declaring a method writes the recipe. Calling a method runs it. A call is a jump: into the body, then back to the call site, possibly carrying a returned value.
  • For the next several weeks, every method you write starts with public static. You’ll unpack what those mean once you have classes.

What you can do now. Read any Java method header and translate it into one English sentence. Tell which lines are declarations and which are call sites. Predict whether a method body runs (yes if there is a call to it; no if there is only a declaration).

Next up: How a Method Call Actually Works. The mechanics of the jump, in three steps. You will learn the rule that explains why a method “swap” that looks correct does not actually swap anything in main, and you’ll meet the parameter-mystery format you will see again on the quiz and the exam.


  • Reges & Stepp, Building Java Programs, Chapter 3 sections 3.1 and 3.2.
  • FAQ entries on static and missing return statements.