Tutorial 1: Parameters, Return Values, and Scope

Unit 5 ยท Methods and decomposition

Objectives

A method contract states what a method needs, what it produces, and important assumptions. Prefer methods that return values rather than printing internally; callers can then reuse and test the result.

static double average(int total, int count) {
    if (count == 0) throw new IllegalArgumentException("count");
    return (double) total / count;
}

static boolean passed(double mark) {
    return mark >= 50.0;
}

Variables declared inside a method are local to that method. Java passes arguments by value: a method receives a copy of a primitive value. Returning a new value is usually clearer than relying on shared mutable state.

Practice

  1. Decompose a grade calculator into input, validation, average, and report methods.
  2. Write max(int a, int b) and test equal values.
  3. Write a method contract before implementing each method.

Self-check

  1. What is the difference between a parameter and an argument?
  2. Why should a method avoid mixing calculation and user input?
  3. What happens when a non-void method reaches its end?

Mastery task: Refactor a long menu program into at least five cohesive methods and explain each method's contract.