Course outline · 0% complete

0/29 lessons0%

Course overview →

Defining methods

lesson 4-1 · ~6 min · 10/29

Quiz

Warm-up from lesson 3-3: what does for (int s : scores) do, where scores is an int array?

A Python function, translated

Methods exist so a piece of logic is written once, named, and reused — the alternative is the same ten lines pasted in five places, where a bug fixed in four of them lives on in the fifth. They are also the unit of teamwork: a teammate can call your average method correctly knowing only its one-line signature, never reading its body. In Python:

def square(n):
    return n * n

In Java, a method declares the type of everything, including what it returns:

static int square(int n) {
  return n * n;
}

Reading left to right: static (ignore for one more lesson), int is the return type, square is the name, (int n) declares one parameter of type int. A method that returns nothing uses the return type void.

The name plus its parameter types form the method's signature. The compiler checks every call against it: square("hi") will not compile.

Code exercise · java

Run this program with two methods defined beside main. Note that methods can call other methods, and calls can nest inside expressions.

Rules of return

  • A non-void method must return a value of its declared type on every path. Forget one branch and the compiler tells you "missing return statement".
  • return in a void method just exits early, like Python's bare return.
  • Parameters are also typed: static double average(double a, double b) takes exactly two doubles.

Where methods live: for now, write them as siblings of main inside the class, each marked static. Order does not matter, main can call a method defined below it.

Quiz

A method is declared static int half(int n) but its body says return n / 2.0;. What happens?

Code exercise · java

Your turn. Define two methods: average, which takes two doubles and returns their mean, and isEven, which takes an int and returns a boolean. From main, print average(4, 7) then isEven(10). Expect 5.5 and true.