Skip to content

VOL 01 / CH 05 / LESSON 01

5.1 Why Methods Help ​

Prerequisites: Variables, Conditions, and Loops Estimated time: 20 minutes You are ready to continue when: You can extract repeated code into a named method with clear inputs and outputs

Copying three blocks is quick. Fixing all three later takes longer. Give the shared steps a name.

Encapsulating Callable Behavior ​

Save this as BuildDemo.java in your practice directory. It only prints build steps so you can observe the calls; it does not perform a build.

java
public class BuildDemo {
    static void buildItem() {
        System.out.println("prepare");
        System.out.println("compile");
        System.out.println("package");
    }

    public static void main(String[] args) {
        buildItem();
        buildItem();
        buildItem();
    }
}
bash
mkdir -p out
javac -d out BuildDemo.java
java -cp out BuildDemo

A method declaration provides:

text
modifier  return type  method name  (parameter list)  { method body }
static   void          buildItem()      { ... }
  • static: The method belongs to a class, and main can call this method directly within the same class;
  • void: It does not return a Java value under normal execution;
  • buildItem: The name used by the caller;
  • (): No parameters are currently defined;
  • Method body: the statements executed each time the method is invoked.

In Java 17, ordinary method definitions belong inside a class, interface, or another suitable type. They cannot appear directly at file level or inside another method body. The following excerpts omit the enclosing class: place each static ... { ... } definition in the class body and each call inside main or another method.

Parameters Make Behavior Respond to Change ​

java
static void buildItem(String name, int days) {
    System.out.println("Building " + name + " requires " + days + " days");
}

buildItem("Standard item", 3);
buildItem("Premium item", 5);

The name and days in the declaration are parameters; the "Standard item" and 3 at the call site are argument expressions. Before the call, Java evaluates the arguments from left to right and then copies each resulting value into the corresponding parameter.

Return Values Allow the Caller to Continue Composing ​

java
static int materialCost(int kilograms, int pricePerKilogram) {
    return Math.multiplyExact(kilograms, pricePerKilogram);
}

int cost = materialCost(4, 12);
System.out.println(cost); // 48

The return type is int. On the normal path, the method must return a value compatible with this type. return terminates the current method call and passes the value to the caller. Here, Math.multiplyExact explicitly fails when an integer overflow occurs, rather than silently wrapping around.

A void method can use return;, without a value, to exit early:

java
static void printPositive(int value) {
    if (value <= 0) {
        return;
    }
    System.out.println(value);
}

Extract Methods Around a Shared Responsibility ​

Suitable signals for extraction:

  • The same business rule appears in multiple locations;
  • A code segment can be accurately named with a clear, descriptive verb;
  • A specific calculation or decision needs to be tested independently;
  • The main flow is obscured by low-level implementation details.

Two identical code segments do not necessarily represent the same business concept. If their future changes stem from different causes, forcing them into a shared method creates erroneous coupling. First assess responsibilities, then eliminate duplication.

Inputs, Outputs, and Failures Define a Contract ​

java
static int unitPrice(String material) {
    if (material == null) {
        throw new IllegalArgumentException("material is null");
    }
    return switch (material) {
        case "iron" -> 12;
        case "silver" -> 30;
        default -> throw new IllegalArgumentException("material: " + material);
    };
}

Professional readers typically start by examining: what inputs are allowed, what output is returned, which external state is modified, and how failures might occur. Method names and types alone convey only a partial picture; boundary tests and concise documentation complete the contract.

Professional Quick Reference ​

QuestionAnswer
Is void equivalent to "doing nothing"?No, it only means no Java value is returned.
When are arguments evaluated?Before the call, from left to right.
How do parameters enter a method?The result value is copied into the formal parameters.
Where does return affect execution?It terminates the current method call.
Should you extract when seeing repetition?Only if the changes and responsibilities are identical.

Before Proceeding ​

Extract a method from the three repeated processing steps. First, define the method name, inputs, and outputs. Then state what it may modify and how it can fail. If two blocks merely look similar but change for different reasons, keep them separate rather than creating accidental coupling.

→ Next Step: Method Declaration and Invocation

Built with VitePress | Software Systems Atlas