Part 1 · The core language

5Methods

Until now every program has been one long list of statements inside main. This lesson shows how to cut a program into named pieces called methods, how to hand a piece some information and get an answer back, and what the JVM is doing while one piece calls another. Methods are the main tool for keeping programs short, correct and easy to change, and every later lesson uses them.

By the end you will be able to

  • write a static method with parameters and a return value, and call it
  • trace which statement runs next when one method calls another
  • explain the difference between printing a result and returning it, and choose the right one
  • draw the call stack of a small program and read a multi-line stack trace
  • say which variables a method can see, and why it cannot change its caller's variables
  • call Math methods, overload a method, and read a short recursive method
  • read and fix the compiler errors that methods produce

Why methods exist

This program prints three receipts. Each begins with the same three-line header.

code/m05-methods/RepeatedLines.java
public class RepeatedLines {
    public static void main(String[] args) {
        System.out.println("==============");
        System.out.println("  GREEN CAFE");
        System.out.println("==============");
        System.out.println("Tea        1.80");
        System.out.println();
        System.out.println("==============");
        System.out.println("  GREEN CAFE");
        System.out.println("==============");
        System.out.println("Cake       3.25");
        System.out.println();
        System.out.println("==============");
        System.out.println("  GREEN CAFE");
        System.out.println("==============");
        System.out.println("Soup       4.50");
        System.out.println();
    }
}
Terminal, in code/m05-methods
> javac RepeatedLines.java
> java RepeatedLines
==============
  GREEN CAFE
==============
Tea        1.80

==============
  GREEN CAFE
==============
Cake       3.25

==============
  GREEN CAFE
==============
Soup       4.50

It works, and it has a weakness. The header job is written out three times, nine statements for a job that needs three. If the cafe changes its name you must find and edit three places, and if you miss one, one receipt disagrees with the others. Copies of the same code drift apart.

The remedy is a method: a named block of statements that you can run, by name, as often as you like. You have been using methods since lesson 1: println is one that someone else wrote. What is new in this lesson is writing your own. A method gives you three things:

Defining a method and calling it

Here is the same program with the header moved into a method of its own.

code/m05-methods/Receipt.java
public class Receipt {
    public static void main(String[] args) {
        printHeader();
        System.out.println("Tea        1.80");
        System.out.println();
        printHeader();
        System.out.println("Cake       3.25");
        System.out.println();
        printHeader();
        System.out.println("Soup       4.50");
        System.out.println();
    }

    static void printHeader() {
        System.out.println("==============");
        System.out.println("  GREEN CAFE");
        System.out.println("==============");
    }
}
Terminal, in code/m05-methods
> javac Receipt.java
> java Receipt
==============
  GREEN CAFE
==============
Tea        1.80

==============
  GREEN CAFE
==============
Cake       3.25

==============
  GREEN CAFE
==============
Soup       4.50

The output is the same as before. Two different things appear in the code, and it matters to keep them apart.

The first line of a definition is called its header. Here is each part of static void printHeader():

PartIts job
staticExplained in the section Why every method here says static. Until then, write it on every method you add.
voidThis method hands no value back to its caller. Lesson 1 told you main is void as well. The section Returning a value covers the alternative.
printHeaderThe name. Method names start with a lower-case letter and join further words with a capital (camelCase). A method that does something is usually named with a verb, as here. The section Writing good methods gives the full convention.
()The parameter list. It is empty here, so this method needs no information from its caller.
{ ... }The body: the statements that run when the method is called.

A definition sits inside the class but outside every other method. Putting one inside main is a mistake that beginners make:

code/m05-methods/broken/Nested.java
public class Nested {
    public static void main(String[] args) {
        System.out.println("start");

        static void greet() {
            System.out.println("hello");
        }

        greet();
    }
}
Terminal, in code/m05-methods/broken
> javac Nested.java
Nested.java:5: error: illegal start of expression
        static void greet() {
        ^
Nested.java:9: error: invalid method declaration; return type required
        greet();
        ^
Nested.java:11: error: class, interface, annotation type, enum, record, method or field expected
}
^
3 errors

The first error points at static on line 5: inside a method, the compiler is expecting a statement, and a definition is not one. The other two errors are fallout from the first: after it, the compiler's picture of the file no longer matches what you meant. This is why lesson 1 said to start with the first error: later ones are often side effects of it. Fix it and compile again.

A second small mistake is to name a method and leave off the parentheses:

code/m05-methods/broken/NoParens.java
public class NoParens {
    public static void main(String[] args) {
        greet;
    }

    static void greet() {
        System.out.println("hello");
    }
}
Terminal, in code/m05-methods/broken
> javac NoParens.java
NoParens.java:3: error: not a statement
        greet;
        ^
1 error

The parentheses are what makes it a call. Without them, greet; is just a name sitting on a line, and that is not a statement.

What happens at a call

Follow the flow of control in this program. Each line it prints says where it was printed from.

code/m05-methods/Flow.java
public class Flow {
    public static void main(String[] args) {
        System.out.println("main: before the first call");
        sayHello();
        System.out.println("main: between the calls");
        sayHello();
        System.out.println("main: after the second call");
    }

    static void sayHello() {
        System.out.println("    sayHello: running");
    }
}
Terminal, in code/m05-methods
> javac Flow.java
> java Flow
main: before the first call
    sayHello: running
main: between the calls
    sayHello: running
main: after the second call

A call works in four steps:

  1. The caller (here main) pauses at the call.
  2. Control jumps to the first statement of the method.
  3. The method's statements run, top to bottom.
  4. At the closing brace, control goes back to the caller and carries on with the statement after the call.

The second call repeats the same four steps, which is why sayHello: running appears twice.

In Flow the definition is below main. Does the position matter? Here is the same program with the definition above it:

code/m05-methods/FlowReordered.java
public class FlowReordered {
    static void sayHello() {
        System.out.println("    sayHello: running");
    }

    public static void main(String[] args) {
        System.out.println("main: before the first call");
        sayHello();
        System.out.println("main: between the calls");
        sayHello();
        System.out.println("main: after the second call");
    }
}
Terminal, in code/m05-methods
> javac FlowReordered.java
> java FlowReordered
main: before the first call
    sayHello: running
main: between the calls
    sayHello: running
main: after the second call

The output is identical. The compiler reads the whole class before it checks the calls, so a definition can be above or below the code that calls it. The order of definitions in the file does not affect the order in which things run. That is decided only by the calls. This course puts main first and the helper methods below it, so the file reads from the big picture down to the details.

Predict

Here main calls first, and first calls second. Write down the five lines this program prints, in order.

code/m05-methods/Order.java
public class Order {
    public static void main(String[] args) {
        System.out.println("main 1");
        first();
        System.out.println("main 2");
    }

    static void first() {
        System.out.println("first 1");
        second();
        System.out.println("first 2");
    }

    static void second() {
        System.out.println("second");
    }
}
Reveal the answer
Terminal, in code/m05-methods
> javac Order.java
> java Order
main 1
first 1
second
first 2
main 2

The order is main 1, first 1, second, first 2, main 2. When first calls second, first pauses in the same way that main paused. Only when second finishes does first carry on with first 2, and only when first finishes does main reach main 2. Calls nest like brackets: the last one opened is the first one finished. The section The call stack shows how the JVM keeps track of this.

Parameters and arguments

printHeader always does the same thing. Most useful methods need to be told something: how wide, which name, what amount. You tell them through parameters: variables declared in the parentheses of the header, each with a type and a name, separated by commas. The values supplied at a call are the arguments.

code/m05-methods/Params.java
public class Params {
    public static void main(String[] args) {
        printRule(10);
        printRow("Tea", 180);
        printRow("Cake", 325);
        int n = 4;
        printRule(n * 2);
    }

    static void printRule(int width) {
        for (int i = 0; i < width; i++) {
            System.out.print("-");
        }
        System.out.println();
    }

    static void printRow(String label, int pence) {
        System.out.println(label + ": " + pence + "p");
    }
}
Terminal, in code/m05-methods
> javac Params.java
> java Params
----------
Tea: 180p
Cake: 325p
--------

Each call fills in the parameters from left to right. In printRow("Tea", 180) the first argument goes into label and the second into pence. Inside the body, a parameter is an ordinary variable that already holds a value when the first statement runs.

That value is a copy. The last call shows it: printRule(n * 2) has an expression as its argument. Java works out the expression first (4 * 2 is 8) and puts that value into width, so the line has eight dashes. The method never sees the variable n, only a number that was calculated from it. The section A method cannot change its caller's variables returns to this.

Both the arguments and the parameters have types, and the compiler checks every call against the header. It checks three things: how many arguments there are, their order, and their types.

Wrong number of arguments

code/m05-methods/broken/WrongCount.java
public class WrongCount {
    public static void main(String[] args) {
        printRow("Tea");
    }

    static void printRow(String label, int pence) {
        System.out.println(label + ": " + pence + "p");
    }
}
Terminal, in code/m05-methods/broken
> javac WrongCount.java
WrongCount.java:3: error: method printRow in class WrongCount cannot be applied to given types;
        printRow("Tea");
        ^
  required: String,int
  found:    String
  reason: actual and formal argument lists differ in length
1 error

This error has extra lines, and they are the useful part. required lists the types the definition asks for, found lists the types you supplied, and reason says how they differ: here the lists have different lengths. Formal means the parameters in the definition and actual means the arguments in the call.

Wrong type, or right types in the wrong order

code/m05-methods/broken/WrongOrder.java
public class WrongOrder {
    public static void main(String[] args) {
        printRow(180, "Tea");
    }

    static void printRow(String label, int pence) {
        System.out.println(label + ": " + pence + "p");
    }
}
Terminal, in code/m05-methods/broken
> javac WrongOrder.java
WrongOrder.java:3: error: incompatible types: int cannot be converted to String
        printRow(180, "Tea");
                 ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

The count is right, but the arguments are in the wrong order. The compiler matches the first argument, 180, against the first parameter, String label, and reports the first mismatch. The caret sits under the argument that does not fit. The Note at the end tells you that javac has shortened its explanation. For a method that has a single definition, the short form is the one to read.

Not every mismatch is an error. An int argument can be given to a double parameter, because the value 7 can be stored as 7.0 without losing anything. It is the same conversion as double d = 7;.

code/m05-methods/Widening.java
public class Widening {
    public static void main(String[] args) {
        showHalf(7);
        showHalf(7.0);
    }

    static void showHalf(double x) {
        System.out.println(x + " halved is " + x / 2);
    }
}
Terminal, in code/m05-methods
> javac Widening.java
> java Widening
7.0 halved is 3.5
7.0 halved is 3.5

Both calls print the same thing. The other direction is refused, for the same reason it is refused in an assignment: the conversion could lose information.

code/m05-methods/broken/LossyArgument.java
public class LossyArgument {
    public static void main(String[] args) {
        printRule(2.5);
    }

    static void printRule(int width) {
        for (int i = 0; i < width; i++) {
            System.out.print("-");
        }
        System.out.println();
    }
}
Terminal, in code/m05-methods/broken
> javac LossyArgument.java
LossyArgument.java:3: error: incompatible types: possible lossy conversion from double to int
        printRule(2.5);
                  ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

If you really want the whole-number part, write a cast at the call: printRule((int) 2.5) (lesson 2). That makes your intention visible to the next reader.

Reading the header of main again

In lesson 1 you were told to treat public static void main(String[] args) as a formula. You can now read most of it. main is a method. It is void, so it returns nothing to the JVM that calls it. It has one parameter, args, whose type String[] means a list of pieces of text. The JVM supplies that argument when it starts your program. Lists of values (arrays) and what args contains are the subject of lesson 7, so for now main ignores its parameter.

Returning a value

A void method does something. Often you want a method that works something out and hands the answer back. For that, replace void in the header with the return type, the type of the answer, and end the method with return and a value of that type.

code/m05-methods/Returns.java
public class Returns {
    public static void main(String[] args) {
        int a = square(5);
        System.out.println(a);
        System.out.println(square(3) + square(4));
        System.out.println(square(square(2)));
        System.out.println(signOf(-8));
        System.out.println(signOf(0));
        System.out.println(signOf(12));
        if (isEven(7)) {
            System.out.println("7 is even");
        } else {
            System.out.println("7 is odd");
        }
    }

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

    static String signOf(int n) {
        if (n < 0) {
            return "negative";
        }
        if (n == 0) {
            return "zero";
        }
        return "positive";
    }

    static boolean isEven(int n) {
        return n % 2 == 0;
    }
}

main makes the calls. Below it, the file defines three methods, each with a return type in front of its name: int, String and boolean.

Terminal, in code/m05-methods
> javac Returns.java
> java Returns
25
25
16
negative
zero
positive
7 is odd

A call to a method that returns a value is an expression: when it finishes, the call is replaced by the value it returned. So you can use it wherever a value of that type fits:

A void method returns no value, so its call is not an expression, and it can only be used as a statement on its own line.

return ends the method at once

When a return statement runs, the method finishes immediately and control goes back to the caller. Any statements after it, in that call, are skipped. signOf uses this: for -8 the first return runs and the other two never do. That is why it needs no else.

A void method can also use return, with no value, to stop early:

code/m05-methods/EarlyExit.java
public class EarlyExit {
    public static void main(String[] args) {
        report(50);
        report(-5);
        report(100);
    }

    static void report(int percent) {
        if (percent < 0 || percent > 100) {
            System.out.println("invalid: " + percent);
            return;
        }
        System.out.println("ok: " + percent);
    }
}
Terminal, in code/m05-methods
> javac EarlyExit.java
> java EarlyExit
ok: 50
invalid: -5
ok: 100

For -5 the method prints invalid: -5 and returns, so the ok: line is skipped. This is a common way to deal with bad input at the top of a method and keep the main work un-nested below it.

Mistakes with return

A path with no return. If a method has a return type, every route the compiler can see through it must end by returning a value. The compiler checks this for you:

code/m05-methods/broken/MissingReturn.java
public class MissingReturn {
    public static void main(String[] args) {
        System.out.println(grade(70));
    }

    static String grade(int mark) {
        if (mark >= 50) {
            return "pass";
        }
    }
}
Terminal, in code/m05-methods/broken
> javac MissingReturn.java
MissingReturn.java:10: error: missing return statement
    }
    ^
1 error

When mark is 50 or more, the method returns "pass". When it is less, the if body is skipped and the method reaches its closing brace with no value to hand back. The compiler reports the line of that closing brace. The fix is a return that covers the other case, either an else or a plain return "fail"; after the if.

You might think that adding else if (mark < 50) solves it, because the two conditions between them cover every number. The compiler does not reason about that:

code/m05-methods/broken/MissingReturnElseIf.java
public class MissingReturnElseIf {
    public static void main(String[] args) {
        System.out.println(grade(70));
    }

    static String grade(int mark) {
        if (mark >= 50) {
            return "pass";
        } else if (mark < 50) {
            return "fail";
        }
    }
}
Terminal, in code/m05-methods/broken
> javac MissingReturnElseIf.java
MissingReturnElseIf.java:12: error: missing return statement
    }
    ^
1 error

It sees only that an if chain without a final else may have every branch skipped. To satisfy it, end the chain with a plain else or a closing return.

Using the result of a void method. A method that is declared void produces no value, so there is nothing to store or print:

code/m05-methods/broken/VoidStored.java
public class VoidStored {
    public static void main(String[] args) {
        int answer = printSquare(4);
        System.out.println(answer + 1);
    }

    static void printSquare(int n) {
        System.out.println(n * n);
    }
}
Terminal, in code/m05-methods/broken
> javac VoidStored.java
VoidStored.java:3: error: incompatible types: void cannot be converted to int
        int answer = printSquare(4);
                                ^
1 error
code/m05-methods/broken/VoidPrinted.java
public class VoidPrinted {
    public static void main(String[] args) {
        System.out.println(printSquare(4));
    }

    static void printSquare(int n) {
        System.out.println(n * n);
    }
}
Terminal, in code/m05-methods/broken
> javac VoidPrinted.java
VoidPrinted.java:3: error: 'void' type not allowed here
        System.out.println(printSquare(4));
                                      ^
1 error

Both messages say the same thing in different words. The cure is to decide what you meant: either change the method so that it returns the value (see the next section), or call it on its own line and do not use a result.

Returning a value from a void method. The mistake can also be on the other side:

code/m05-methods/broken/ReturnInVoid.java
public class ReturnInVoid {
    public static void main(String[] args) {
        double f = toFahrenheit(100.0);
        System.out.println(f);
    }

    static void toFahrenheit(double celsius) {
        return celsius * 9 / 5 + 32;
    }
}
Terminal, in code/m05-methods/broken
> javac ReturnInVoid.java
ReturnInVoid.java:3: error: incompatible types: void cannot be converted to double
        double f = toFahrenheit(100.0);
                               ^
ReturnInVoid.java:8: error: incompatible types: unexpected return value
        return celsius * 9 / 5 + 32;
                               ^
2 errors

There are two errors, and the first one is not where the mistake is. The method was declared void by accident, and line 8 shows the sign of it: unexpected return value means this method promised no value, and you returned one. Line 3 is a consequence, because toFahrenheit promised nothing and the caller expected a double. Here the first error is a side effect of the second, so fixing line 3 would be a mistake. Starting with the first error is a good habit, not a law: when two errors mention the same method, read both before changing anything.

Returning the wrong type. The value after return must fit the declared type:

code/m05-methods/broken/WrongReturnType.java
public class WrongReturnType {
    public static void main(String[] args) {
        System.out.println(half(9));
    }

    static int half(int n) {
        return n / 2.0;
    }
}
Terminal, in code/m05-methods/broken
> javac WrongReturnType.java
WrongReturnType.java:7: error: incompatible types: possible lossy conversion from double to int
        return n / 2.0;
                 ^
1 error

The expression n / 2.0 is a double, and the method promised an int. Either the promise or the expression has to change.

Code after a return. A statement that the compiler can see is never reached is an error in Java, not a warning:

code/m05-methods/broken/Unreachable.java
public class Unreachable {
    public static void main(String[] args) {
        System.out.println(twice(4));
    }

    static int twice(int n) {
        return n * 2;
        System.out.println("finished");
    }
}
Terminal, in code/m05-methods/broken
> javac Unreachable.java
Unreachable.java:8: error: unreachable statement
        System.out.println("finished");
        ^
1 error

This is the confusion that costs beginners the most time, so it gets a section of its own. A method that prints a result shows it to a person. A method that returns a result gives it to the program. The two look similar when you run them, and they are not the same.

Here is one task, converting Celsius to Fahrenheit, written both ways.

code/m05-methods/PrintVersion.java
public class PrintVersion {
    public static void main(String[] args) {
        printFahrenheit(20.0);
        printFahrenheit(100.0);
    }

    static void printFahrenheit(double celsius) {
        System.out.println(celsius * 9 / 5 + 32);
    }
}
code/m05-methods/ReturnVersion.java
public class ReturnVersion {
    public static void main(String[] args) {
        System.out.println(toFahrenheit(20.0));

        double boiling = toFahrenheit(100.0);
        System.out.println("Water boils at " + boiling + " F");

        if (toFahrenheit(30.0) > 80) {
            System.out.println("30 C counts as hot");
        }

        double rise = toFahrenheit(30.0) - toFahrenheit(20.0);
        System.out.println("A 10 degree rise in C is " + rise + " in F");
    }

    static double toFahrenheit(double celsius) {
        return celsius * 9 / 5 + 32;
    }
}

Now look at what each version allows. In ReturnVersion, main uses the method in four different ways: it prints the answer, stores it in a variable and builds a sentence, compares it in an if, and subtracts two answers.

Terminal, in code/m05-methods
> javac PrintVersion.java ReturnVersion.java
> java PrintVersion
68.0
212.0
> java ReturnVersion
68.0
Water boils at 212.0 F
30 C counts as hot
A 10 degree rise in C is 18.0 in F

The first two lines come from PrintVersion, which can show conversions and do nothing else. The rest come from ReturnVersion, which can do all four. Only the first, showing the answer, is possible with the printing version, and only in the one format fixed inside it. Its answer has already gone to the screen, and the program has no way to get hold of it. Trying to store it is the void error from the previous section.

Prints the resultReturns the result
Who gets the answerA person reading the terminalThe code that called the method
Can the caller store it, compare it or calculate with itNoYes
Can the caller choose how to show itNo: the format is fixed inside the methodYes
Return typevoidThe type of the answer

The reverse confusion also exists: a method that returns a value does not print it. Calling toFahrenheit(100.0); on a line of its own is legal, and the value is simply thrown away.

Predict

This program calls twice two times, and throws away the result of the first call. What does it print, line by line?

code/m05-methods/Discarded.java
public class Discarded {
    public static void main(String[] args) {
        twice(5);
        int r = twice(6);
        System.out.println(r);
    }

    static int twice(int n) {
        System.out.println("twice called with " + n);
        return n * 2;
    }
}
Reveal the answer
Terminal, in code/m05-methods
> javac Discarded.java
> java Discarded
twice called with 5
twice called with 6
12

Three lines. Both calls run the whole method, including its println, so twice called with 5 and twice called with 6 both appear. The first call returns 10, and since nothing receives it, it disappears. The second call returns 12, which is stored in r and printed by main. The line 12 exists only because main printed it; twice did not print its result, it returned it.

A good rule: let methods that work something out return it, and let a small number of methods, often main, do the printing. A returning method is easy to reuse, whereas a printing method only suits the one job it was written for. If you need a method whose whole job is to display something, such as printHeader, void is the right type.

The call stack

When first calls second and first must wait, the JVM needs somewhere to remember where first was and what its variables held. It keeps this on the call stack. Think of a pile of trays. Each call puts a new tray on top, and each return takes the top tray off. A tray is called a frame, and it holds three things: the parameters, the local variables, and the place to resume when the call ends.

Only the top frame is running. Every frame below it is paused at the statement that made the call. Here is a program with a call three levels deep. Each method prints its variables so you can compare them with the picture.

code/m05-methods/StackDemo.java
public class StackDemo {
    public static void main(String[] args) {
        int total = 10;
        int result = outer(total);
        System.out.println("result = " + result);
    }

    static int outer(int a) {
        int b = a + 1;
        System.out.println("outer: a = " + a + ", b = " + b);
        return middle(b) + 1;
    }

    static int middle(int c) {
        int d = c * 2;
        System.out.println("middle: c = " + c + ", d = " + d);
        return inner(d) + 1;
    }

    static int inner(int e) {
        int f = e - 5;
        System.out.println("inner: e = " + e + ", f = " + f);
        return f;
    }
}
Terminal, in code/m05-methods
> javac StackDemo.java
> java StackDemo
outer: a = 10, b = 11
middle: c = 11, d = 22
inner: e = 22, f = 17
result = 19

This is the stack at the moment inner prints its line:

TOP OF THE STACK inner(e) e = 22 f = 17 running now the only frame that is doing anything middle(c) c = 11 d = 22 paused return inner(d) + 1; outer(a) a = 10 b = 11 paused return middle(b) + 1; main(args) total = 10 result = (no value yet) paused int result = outer(total); BOTTOM OF THE STACK: main, started by the JVM A call puts a frame on top. A return removes the top frame.

Walking through the program shows how the stack changes:

  1. main starts. The stack holds one frame. total becomes 10.
  2. The call outer(total) pushes a frame. The argument's value, 10, is copied into the parameter a. outer sets b to 11.
  3. outer calls middle(b). Another frame goes on top, with c holding 11, and middle sets d to 22.
  4. middle calls inner(d). A fourth frame goes on, with e holding 22. f is 17. This is the picture above.
  5. inner executes return f;. Its frame is removed, and the value 17 goes to the place where middle was paused. middle evaluates 17 + 1 and returns 18.
  6. outer evaluates 18 + 1 and returns 19. Back in main, 19 is stored in result. The program prints result = 19.

When a frame is removed, so are its variables. e, f, c, d, a and b no longer exist after step 6.

Reading a stack trace

Lesson 1 told you to read the first line of an exception report for what and the at line for where. With the call stack in mind you can read the rest. A stack trace is a printout of the call stack at the moment the exception was thrown, top frame first. Here the failure is three calls deep.

code/m05-methods/StackTrace.java
public class StackTrace {
    public static void main(String[] args) {
        System.out.println("main: start");
        int result = outer(0);
        System.out.println("main: result = " + result);
    }

    static int outer(int x) {
        System.out.println("outer: x = " + x);
        return middle(x) + 1;
    }

    static int middle(int y) {
        System.out.println("middle: y = " + y);
        return inner(y) * 2;
    }

    static int inner(int z) {
        System.out.println("inner: z = " + z);
        return 100 / z;
    }
}
Terminal, in code/m05-methods
> javac StackTrace.java
> java StackTrace
main: start
outer: x = 0
middle: y = 0
inner: z = 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at StackTrace.inner(StackTrace.java:20)
	at StackTrace.middle(StackTrace.java:15)
	at StackTrace.outer(StackTrace.java:10)
	at StackTrace.main(StackTrace.java:4)

Read it from the top:

The last line is the bottom of the stack, here main, where the program started. Everything that was printed before the failure is still on the screen (inner: z = 0 is the last of it), and nothing after the failure ran, so main: result never appears. A trace tells you where the program was and how it got there. It does not show variable values; to find those you read the code, or add a println. In traces from larger programs, the top lines are often in library code. Then look down the list for the first line that names one of your own files, since that is where your code made the call that went wrong.

Scope and lifetime

Lesson 3 said that a variable exists from its declaration to the closing brace of the block it was declared in. That is its scope. A method body is a block, so a variable declared in a method, including its parameters, is a local variable of that method, and no other method can use its name to reach it.

The call stack explains why. A local variable lives in a frame, and the frame belongs to one call. Its lifetime, the time it exists while the program runs, begins when the method is called and ends when it returns. Two methods can therefore each have a variable called count. They are two variables in two frames:

code/m05-methods/ScopeDemo.java
public class ScopeDemo {
    public static void main(String[] args) {
        int count = 100;
        System.out.println("main: count = " + count);
        tick();
        System.out.println("main: count = " + count);
    }

    static void tick() {
        int count = 1;
        count = count + 1;
        System.out.println("tick: count = " + count);
    }
}
Terminal, in code/m05-methods
> javac ScopeDemo.java
> java ScopeDemo
main: count = 100
tick: count = 2
main: count = 100

The count in tick started at 1 and was increased to 2. main's count was 100 before the call and 100 after it. They have a name in common and nothing else.

A method can only use the names that exist in its own frame. If it tries to reach for a variable that belongs to another method, the compiler does not find the name:

code/m05-methods/broken/OutOfScope.java
public class OutOfScope {
    public static void main(String[] args) {
        int total = 25;
        showTotal();
    }

    static void showTotal() {
        System.out.println("total = " + total);
    }
}
Terminal, in code/m05-methods/broken
> javac OutOfScope.java
OutOfScope.java:8: error: cannot find symbol
        System.out.println("total = " + total);
                                        ^
  symbol:   variable total
  location: class OutOfScope
1 error

This is the cannot find symbol error from lesson 1. total exists in main, but showTotal cannot see into main's frame. If showTotal needs the number, main must pass it as an argument.

Predict

The method next sets a local variable to 0, adds one, and returns it. main calls it three times. What are the three lines of output?

code/m05-methods/Fresh.java
public class Fresh {
    public static void main(String[] args) {
        System.out.println(next());
        System.out.println(next());
        System.out.println(next());
    }

    static int next() {
        int n = 0;
        n = n + 1;
        return n;
    }
}
Reveal the answer
Terminal, in code/m05-methods
> javac Fresh.java
> java Fresh
1
1
1

Each line is 1. Every call creates a new frame, and in that frame n starts at 0, becomes 1 and is returned. When the frame goes, so does n. Nothing is carried from one call to the next. A local variable cannot count how many times a method has been called. A memory that survives between calls has to live somewhere that outlasts one call; later lessons, once you have met objects, show where.

A method cannot change its caller's variables

You saw that a parameter receives a copy of the argument's value. This has a consequence: the method works on its copy and can never alter the variable in the caller. Here is a method that tries.

code/m05-methods/PassByValue.java (lines 11 to 18)
static void addBonus(int points) {
    points = points + 10;
    System.out.println("addBonus: points = " + points);
}

static int withBonus(int points) {
    return points + 10;
}
Predict

main declares int score = 5;, calls addBonus(score), and then prints score. Inside addBonus the parameter points is increased by 10. What does main print?

code/m05-methods/PassByValue.java (lines 3 to 8)
int score = 5;
addBonus(score);
System.out.println("main: score = " + score);

score = withBonus(score);
System.out.println("main: score = " + score);
Reveal the answer
Terminal, in code/m05-methods
> javac PassByValue.java
> java PassByValue
addBonus: points = 15
main: score = 5
main: score = 15

After the first call main prints score = 5. addBonus did add ten to points, as its own print shows (points = 15), but points was a separate variable holding a copy of 5. Changing the copy left score alone. The second call does change score, and the difference is in main, not in the method: score = withBonus(score); takes the returned value and assigns it back.

main score = 5 addBonus(points) points = 15 copy of the value 5 Two boxes, two variables. Changing points to 15 never touches score.

This is called pass by value: the method is given the value, not the variable. Java uses it for every kind of argument. If a method is to give a changed value back to its caller, it returns it and the caller assigns it, as withBonus does. Lesson 7 introduces arrays, and with an array a method can appear to change what the caller sees. The rule will be the same, and lesson 7 explains what is being copied that makes it look different.

Why every method here says static

Every method in this lesson has been marked static, and it is time to say why. Leave the word off and see what the compiler says:

code/m05-methods/broken/NonStatic.java
public class NonStatic {
    public static void main(String[] args) {
        greet();
    }

    void greet() {
        System.out.println("hello");
    }
}
Terminal, in code/m05-methods/broken
> javac NonStatic.java
NonStatic.java:3: error: non-static method greet() cannot be referenced from a static context
        greet();
        ^
1 error

A static method belongs to the class itself. A method without static belongs to an object made from the class, and it can only be called on such an object. You have not made any objects yet, because that is the subject of lessons 8 to 11.

In its standard form, main is static, so that the JVM can call it before any object exists. Code in a static method that calls a plain method by its bare name has no object to call it on, and that is the error: it is referring to a non-static method from a static context. For now the rule is simple: mark every method you write with static. Lessons 8 and 11 explain the other kind, and then the word will have its full meaning.

One more fact about static methods leads into the next section. Inside the same class you call one by its bare name, as in printHeader(). From a different class you write the class name and a dot in front, which is how Math.max(3, 7) looks.

Methods that come with Java

The standard library has a class called Math whose methods are static, so you call them with Math. in front. You need nothing extra at the top of the file. A run shows what a few of them give:

code/m05-methods/MathTour.java (lines 3 to 14)
System.out.println(Math.max(3, 7));
System.out.println(Math.min(3, 7));
System.out.println(Math.max(3, 7.5));
System.out.println(Math.abs(-4));
System.out.println(Math.abs(-4.5));
System.out.println(Math.pow(2, 10));
System.out.println(Math.sqrt(144));
System.out.println(Math.round(2.4));
System.out.println(Math.round(2.5));
System.out.println(Math.round(-2.5));
System.out.println(Math.sqrt(-1));
System.out.println(Math.PI);
Terminal, in code/m05-methods
> javac MathTour.java
> java MathTour
7
3
7.5
4
4.5
1024.0
12.0
2
3
-2
NaN
3.141592653589793
CallResultWhat it does, and the type it returns
Math.max(3, 7)7The larger of two numbers. The result has the type of the arguments: int for two ints. If one is an int and the other a double, the int is widened and the result is a double, so Math.max(3, 7.5) is 7.5.
Math.min(3, 7)3The smaller of two numbers. The type follows the same rule as max.
Math.abs(-4)4The distance from zero. It returns an int for an int and a double for a double: Math.abs(-4.5) is 4.5.
Math.pow(2, 10)1024.0The first number to the power of the second. Always a double, even though the answer here is a whole number.
Math.sqrt(144)12.0The square root, as a double. For a negative number the result is the special value NaN (not a number) and the program carries on.
Math.round(2.5)3The nearest whole number, returned as a long. A value halfway between two whole numbers goes up: Math.round(-2.5) is -2.

Alongside the methods there is a constant, Math.PI, which is a value rather than a method and so has no parentheses.

The return types matter, because the compiler enforces them. Two errors that beginners meet with Math come from them.

code/m05-methods/broken/RoundToInt.java
public class RoundToInt {
    public static void main(String[] args) {
        int rounded = Math.round(2.5);
        System.out.println(rounded);
    }
}
Terminal, in code/m05-methods/broken
> javac RoundToInt.java
RoundToInt.java:3: error: incompatible types: possible lossy conversion from long to int
        int rounded = Math.round(2.5);
                                ^
1 error
code/m05-methods/broken/PowToInt.java
public class PowToInt {
    public static void main(String[] args) {
        int cube = Math.pow(2, 3);
        System.out.println(cube);
    }
}
Terminal, in code/m05-methods/broken
> javac PowToInt.java
PowToInt.java:3: error: incompatible types: possible lossy conversion from double to int
        int cube = Math.pow(2, 3);
                           ^
1 error

Both are the lossy-conversion error you know from lesson 2, and the fix is the same: store the result in a variable that is wide enough (long and double), or cast it, which says that you accept losing digits or range. This program does both:

code/m05-methods/MathTypes.java
public class MathTypes {
    public static void main(String[] args) {
        int biggerInt = Math.max(3, 7);
        double biggerDouble = Math.max(3, 7.5);
        int distance = Math.abs(-4);
        double precise = Math.abs(-4.5);
        double power = Math.pow(2, 10);
        double root = Math.sqrt(144);
        long rounded = Math.round(2.5);
        int cube = (int) Math.pow(2, 3);
        int roundedInt = (int) Math.round(2.5);
        System.out.println(biggerInt + " " + biggerDouble + " " + distance + " " + precise);
        System.out.println(power + " " + root + " " + rounded + " " + cube + " " + roundedInt);
    }
}
Terminal, in code/m05-methods
> javac MathTypes.java
> java MathTypes
7 7.5 4 4.5
1024.0 12.0 3 8 3

The table describes Math.round with a double argument. The library has a second version for a smaller decimal type, float, which this course does not use. It returns an int, and it is the one chosen when you pass an int, so Math.round(n) with an int variable n gives an int. Check what you are passing. (The float version can lose digits for a very large int.)

Overloading

Can two methods in one class have the same name? Yes, provided their parameter lists differ in the number or the types of parameters. This is called overloading. The methods are separate definitions that happen to share a name.

code/m05-methods/Overloads.java
public class Overloads {
    public static void main(String[] args) {
        show(5);
        show(5.0);
        show("five");
        show(5, 6);
    }

    static void show(int n) {
        System.out.println("int: " + n);
    }

    static void show(double d) {
        System.out.println("double: " + d);
    }

    static void show(String s) {
        System.out.println("String: " + s);
    }

    static void show(int a, int b) {
        System.out.println("two ints: " + a + " and " + b);
    }
}
Terminal, in code/m05-methods
> javac Overloads.java
> java Overloads
int: 5
double: 5.0
String: five
two ints: 5 and 6

At each call the compiler looks at the arguments (how many, and of what types) and picks the definition that fits. It makes that decision while compiling, before anything runs. If one definition matches the argument types exactly, it is chosen. If none does, the compiler looks for definitions that fit after a widening conversion such as int to double, and takes the closest one. If nothing fits, the call is an error.

Widening shows when the exact version is missing. This program has no show(int):

code/m05-methods/NoIntVersion.java
public class NoIntVersion {
    public static void main(String[] args) {
        show(5);
        show(2.5);
    }

    static void show(double d) {
        System.out.println("double: " + d);
    }

    static void show(String s) {
        System.out.println("String: " + s);
    }
}
Terminal, in code/m05-methods
> javac NoIntVersion.java
> java NoIntVersion
double: 5.0
double: 2.5

The call show(5) ran the double version and printed 5.0. Now for a puzzle that depends on the same rule.

Predict

This program has the same four show methods as Overloads, and main makes one call, with a char argument. There is no show(char). Which version runs, and what does it print?

code/m05-methods/CharArgument.java
public class CharArgument {
    public static void main(String[] args) {
        show('x');
    }

    static void show(int n) {
        System.out.println("int: " + n);
    }

    static void show(double d) {
        System.out.println("double: " + d);
    }

    static void show(String s) {
        System.out.println("String: " + s);
    }

    static void show(int a, int b) {
        System.out.println("two ints: " + a + " and " + b);
    }
}
Reveal the answer
Terminal, in code/m05-methods
> javac CharArgument.java
> java CharArgument
int: 120

It prints int: 120. A char is really a small whole number, so it can be widened to an int just as an int can be widened to a double, and the character x has the number 120. Both show(int) and show(double) could accept it, and the compiler chooses int because it is the closer.

You have been calling an overloaded method

println is overloaded. The library contains a version for text, one for whole numbers, one for decimals, one for boolean, one for char, and one with no parameters at all:

code/m05-methods/PrintlnForms.java (lines 3 to 9)
System.out.println("text");
System.out.println(5);
System.out.println(2.5);
System.out.println(true);
System.out.println('x');
System.out.println();
System.out.println("end");
Terminal, in code/m05-methods
> javac PrintlnForms.java
> java PrintlnForms
text
5
2.5
true
x

end

That is why the same name works for every call in lesson 1, and why println() with nothing in the parentheses printed an empty line. It also explains why System.out.println('x') prints x, while our own show('x') printed 120: println has a char version, and show does not.

What overloading cannot do

The return type is not part of what tells overloads apart. Two methods that differ only in return type are not overloads. They are a clash:

code/m05-methods/broken/ReturnTypeOnly.java
public class ReturnTypeOnly {
    public static void main(String[] args) {
        System.out.println(size(4));
    }

    static int size(int n) {
        return n * 2;
    }

    static double size(int n) {
        return n * 2.0;
    }
}
Terminal, in code/m05-methods/broken
> javac ReturnTypeOnly.java
ReturnTypeOnly.java:10: error: method size(int) is already defined in class ReturnTypeOnly
    static double size(int n) {
                  ^
1 error

The reason is that a call such as size(4) does not say what you intend to do with the result, so the compiler would have nothing to choose between them with. A second kind of trouble arises when two definitions fit equally well:

code/m05-methods/broken/Ambiguous.java
public class Ambiguous {
    public static void main(String[] args) {
        mix(1, 2);
    }

    static void mix(int a, double b) {
        System.out.println("int, double");
    }

    static void mix(double a, int b) {
        System.out.println("double, int");
    }
}
Terminal, in code/m05-methods/broken
> javac Ambiguous.java
Ambiguous.java:3: error: reference to mix is ambiguous
        mix(1, 2);
        ^
  both method mix(int,double) in Ambiguous and method mix(double,int) in Ambiguous match
1 error

The call mix(1, 2) could widen the second argument to reach the first definition, or widen the first argument to reach the second. Neither is closer, so the compiler refuses to guess. Overloads that differ only in the order of their parameter types can run into this.

Overloading as optional parameters

Java has no optional parameters as a language feature. Overloading gives the same effect. Write the full version of the method, then add a shorter one that calls it with a default value for what is missing:

code/m05-methods/Shipping.java
public class Shipping {
    public static void main(String[] args) {
        System.out.println(shipping(2.0));
        System.out.println(shipping(2.0, true));
    }

    // Cost of posting a parcel: 3.00 plus 1.50 per kilogram, doubled if express.
    static double shipping(double kg, boolean express) {
        double cost = 3.0 + kg * 1.5;
        if (express) {
            cost = cost * 2;
        }
        return cost;
    }

    // Standard delivery: the same calculation with express switched off.
    static double shipping(double kg) {
        return shipping(kg, false);
    }
}
Terminal, in code/m05-methods
> javac Shipping.java
> java Shipping
6.0
12.0

shipping(2.0) calls shipping(2.0, false), so the calculation exists in one place only. A call with one argument chooses the short version, and a call with two arguments chooses the long one. The short version does no work of its own: it supplies the default and calls the full method.

A first look at recursion

A method may call any method in its class, and that includes itself. A method that calls itself is recursive. This looks like it could go on for ever, and it does if you are careless, so a recursive method needs a base case: an input for which it answers directly without calling itself.

The classic example is the factorial. 4! means 4 * 3 * 2 * 1, which is 4 * 3!. Written as a method, factorial(4) is 4 * factorial(3), and so on down to factorial(1), which is 1 and needs no further call. This version prints a line on entering and on leaving, so that you can watch the stack grow and shrink.

code/m05-methods/FactorialTrace.java
public class FactorialTrace {
    public static void main(String[] args) {
        long answer = factorial(4);
        System.out.println("answer = " + answer);
    }

    static long factorial(int n) {
        System.out.println("enter factorial(" + n + ")");
        long result;
        if (n <= 1) {
            result = 1;
        } else {
            result = n * factorial(n - 1);
        }
        System.out.println("leave factorial(" + n + ") = " + result);
        return result;
    }
}
Terminal, in code/m05-methods
> javac FactorialTrace.java
> java FactorialTrace
enter factorial(4)
enter factorial(3)
enter factorial(2)
enter factorial(1)
leave factorial(1) = 1
leave factorial(2) = 2
leave factorial(3) = 6
leave factorial(4) = 24
answer = 24

The four enter lines come first, because each call makes another call before it can finish. Then the leave lines come in reverse order: factorial(1) finishes first and returns 1, which lets factorial(2) work out 2 * 1, and so on up. Each call has its own frame with its own n, as the section Scope and lifetime said. This is the stack at the deepest moment:

TOP OF THE STACK factorial(n) n = 1 base case: returns 1 without calling again factorial(n) n = 2 waiting: will return 2 * factorial(1) factorial(n) n = 3 waiting: will return 3 * factorial(2) factorial(n) n = 4 waiting: will return 4 * factorial(3) main answer = (no value yet) waiting: long answer = factorial(4); Four frames hold four separate variables called n.

Now take the base case away. This method has none:

code/m05-methods/NoBase.java
public class NoBase {
    public static void main(String[] args) {
        System.out.println("start");
        System.out.println(countDown(3));
    }

    static int countDown(int n) {
        return countDown(n - 1);
    }
}
Terminal, in code/m05-methods
> javac NoBase.java
> java -XX:MaxJavaStackTraceDepth=4 NoBase
start
Exception in thread "main" java.lang.StackOverflowError
	at NoBase.countDown(NoBase.java:8)
	at NoBase.countDown(NoBase.java:8)
	at NoBase.countDown(NoBase.java:8)
	at NoBase.countDown(NoBase.java:8)

The start line comes from main, before the failure. Every call pushes a frame and nothing ever pops one. The stack has a limited size, and when it is full the JVM stops the program with a StackOverflowError. Without the extra option the trace is far too long to print here: by default the JVM prints up to 1,024 identical at NoBase.countDown lines. The option -XX:MaxJavaStackTraceDepth=4 tells the JVM to print four of them. It is a setting for the JVM, not part of the program, and you will not normally need it. The error means this method keeps calling itself. The usual cause is a missing base case, or a recursive call that does not move closer to it.

For a problem like factorial a loop would do the job just as well. Recursion is the natural fit when a problem is made of smaller copies of itself. Exercise 6 asks you to write two recursive methods.

Writing good methods

A method is easy to use when you can say, in one sentence, what it does. These habits make that possible.

code/m05-methods/Tidy.java
public class Tidy {
    public static void main(String[] args) {
        double mark = average(70, 80, 90);
        printReport("Imran", mark);
        printReport("Wen", average(40, 45, 50));
    }

    // Returns the average of three marks as a decimal number.
    // Needs: three whole-number marks.
    static double average(int a, int b, int c) {
        return (a + b + c) / 3.0;
    }

    // Returns "pass" for a mark of 50 or more, otherwise "fail".
    // Needs: a mark as a decimal number.
    static String verdict(double mark) {
        if (mark >= 50) {
            return "pass";
        }
        return "fail";
    }

    // Prints one line: the name, the mark and the verdict. Returns nothing.
    // Needs: a name and a mark as a decimal number.
    static void printReport(String name, double mark) {
        System.out.println(name + ": " + mark + " (" + verdict(mark) + ")");
    }
}
Terminal, in code/m05-methods
> javac Tidy.java
> java Tidy
Imran: 80.0 (pass)
Wen: 45.0 (fail)

Java has a special form of comment, starting with /**, that the javadoc tool turns into a web page of documentation. Lesson 29 covers it. The plain // comments above do the same job for a reader of the source.

Also keep the printing and the calculating apart, as the section Printing versus returning advised. average and verdict return their answers, and only printReport prints. Because of that, printReport("Wen", average(40, 45, 50)) can use the answer of one method as an argument to the next.

Exercises

Each exercise has a folder waiting in work/m05-methods/ in your course kit. From this lesson on, most exercises ask for methods with an exact header: the same name, the same parameter types in the same order, and the same return type. A hidden test program will call your methods with a range of values and report each result as ok or WRONG. Your own main is yours: write one to try your methods as you go, and print whatever helps you. The test program has a main of its own and does not use yours. Open a hint only after a real attempt.

warm-up

Exercise 5.1 · Unit converters

Work in work/m05-methods/ex1-converters/ in your course kit

Write a file Converters.java with a class Converters and these three methods, exactly:

  • static double milesToKilometres(double miles): multiply by 1.609344.
  • static double fahrenheitToCelsius(double fahrenheit): subtract 32, multiply by 5, divide by 9.
  • static double kilometresToMiles(double kilometres): multiply by 0.621371.

The methods must return their answers and must not print anything. Here is a sample program calling them:

Output of a sample program that calls the methods
milesToKilometres(10.0) = 16.09344
milesToKilometres(0.0) = 0.0
milesToKilometres(26.2) = 42.1648128
fahrenheitToCelsius(212.0) = 100.0
fahrenheitToCelsius(32.0) = 0.0
kilometresToMiles(10.0) = 6.21371
Hint 1

Each method is one line: a return and a formula. Check your formula by hand against two of the sample lines before you test it by running.

Hint 2

Lesson 2 warned about integer division. In fahrenheitToCelsius the fraction 5 / 9 is calculated with two ints if you write it on its own. Write the formula so that the subtraction and multiplication happen before the division.

To check it, run python check.py m05 ex1 in your course kit folder.

warm-up

Exercise 5.2 · Leap years and month lengths

Work in work/m05-methods/ex2-calendar/ in your course kit

Write DateTools.java with a class DateTools and these two methods, exactly. You wrote the leap-year rule as an expression in exercise 3.3; here it becomes a method that other code can call.

  • static boolean isLeapYear(int year): true when the year is divisible by 4, except that a year divisible by 100 is a leap year only if it is also divisible by 400.
  • static int daysInMonth(int month, int year): the number of days in the month, where month is 1 for January to 12 for December. If month is outside 1 to 12, return -1.

daysInMonth must use isLeapYear to decide about February, rather than repeat its rule. A test program will call both. A sample program shows some calls:

Output of a sample program that calls the methods
isLeapYear(2024) = true
isLeapYear(2023) = false
daysInMonth(2, 2024) = 29
daysInMonth(2, 2023) = 28
daysInMonth(11, 2023) = 30
daysInMonth(13, 2023) = -1
Hint 1

Write isLeapYear first and test it alone on 1900, 2000, 2023 and 2024. The 1900 and 2000 cases are the ones a first attempt gets wrong.

Hint 2

The month lengths fall into groups, which is what the lesson 3 switch is good at. Whichever tool you choose, decide what each path returns, so that every route through the method ends in a return.

To check it, run python check.py m05 ex2 in your course kit folder.

core

Exercise 5.3 · Return, don't print

Work in work/m05-methods/ex3-return-dont-print/ in your course kit

Your folder contains Invoice.java. It prints an invoice with three methods that each calculate and print, and the last of them repeats the work of the other two. Money is in pence, so every value is a whole number.

work/m05-methods/ex3-return-dont-print/Invoice.java
public class Invoice {
    public static void main(String[] args) {
        printSubtotal(250, 3);
        printTax(250, 3, 15);
        printTotal(250, 3, 15);
    }

    static void printSubtotal(int unitPrice, int quantity) {
        System.out.println("Subtotal: " + unitPrice * quantity);
    }

    static void printTax(int unitPrice, int quantity, int taxPercent) {
        System.out.println("Tax: " + unitPrice * quantity * taxPercent / 100);
    }

    static void printTotal(int unitPrice, int quantity, int taxPercent) {
        int subtotal = unitPrice * quantity;
        int tax = subtotal * taxPercent / 100;
        System.out.println("Total: " + (subtotal + tax));
    }
}

Rewrite the program so that the calculating is done by three methods that return their answers, with these headers exactly:

  • static int subtotal(int unitPrice, int quantity)
  • static int tax(int amount, int taxPercent): the amount multiplied by the percentage, divided by 100, using whole-number division.
  • static int total(int unitPrice, int quantity, int taxPercent): the subtotal plus the tax on it.

Constraints: delete the three print... methods, and let only main print. total must get its answer by calling subtotal and tax, and not by repeating their formulas. The output of java Invoice must be the same as before:

Output of java Invoice, before and after your change
Subtotal: 750
Tax: 112
Total: 862
Hint 1

Start with subtotal. The old printSubtotal contains the formula; the new method returns it instead of printing it, and main does the printing.

Hint 2

Once subtotal and tax exist, total is a single return statement made of two calls. Notice that the tax is worked out from the subtotal, not from the unit price.

To check it, run python check.py m05 ex3 in your course kit folder.

core

Exercise 5.4 · Predict the stack

Work in work/m05-methods/ex4-trace-worksheet/ in your course kit

This is a written exercise. Your folder contains Trace.java and a worksheet, prediction.md. Do not run the program until you have answered Parts A to D. Work with the code only.

work/m05-methods/ex4-trace-worksheet/Trace.java
public class Trace {
    public static void main(String[] args) {
        int x = 4;
        System.out.println("main: x = " + x);
        int y = twice(x);
        System.out.println("main: x = " + x + ", y = " + y);
        int z = spread(y, x - 4);
        System.out.println("main: z = " + z);
    }

    static int twice(int n) {
        n = n * 2;
        System.out.println("twice: n = " + n);
        return n;
    }

    static int spread(int total, int people) {
        System.out.println("spread: sharing " + total + " among " + people);
        return share(total, people) + 1;
    }

    static int share(int amount, int count) {
        return amount / count;
    }
}

In prediction.md, answer these before running anything:

  1. Part A. Write the exact output of the program, one line at a time, including the exception line and each at line of the stack trace, with line numbers, if you think the program will fail.
  2. Part B. After twice(x) returns, what value does x have in main? Explain in one or two sentences why.
  3. Part C. Write the call stack at the moment of the failure, top frame first. For each frame give the method name and the value of each of its parameters and variables.
  4. Part D. Which statements never finish, or never start, because of the failure, and what would each have done if the failure had not happened?

Then compile and run, and fill in Part E of the worksheet: for each prediction that was wrong, say what you misjudged. Finally, change x - 4 in main to x - 2 and write down what you expect it to print before running it, then run it and compare. Put Trace.java back as you found it when you have finished.

Hint 1

Number the lines of the file, then follow the program with your finger, one statement at a time, writing down every frame you push and pop.

Hint 2

For Part B, reread the section A method cannot change its caller's variables. For Part A, remember that a stack trace lists the line each frame was on, which for the frames below the top is the line holding the call.

To check it, run python check.py m05 ex4 in your course kit folder.

core

Exercise 5.5 · One name, four areas

Work in work/m05-methods/ex5-shapes/ in your course kit

Write Shapes.java with a class Shapes and four overloaded methods called area, with these headers exactly:

  • static int area(int side): the area of a square, side * side.
  • static double area(double radius): the area of a circle, using Math.PI.
  • static double area(double width, double height): the area of a rectangle.
  • static double area(double a, double b, double c): the area of a triangle with sides a, b and c, by Heron's formula. Let s = (a + b + c) / 2. The area is Math.sqrt(s * (s - a) * (s - b) * (s - c)). If a + b <= c, a + c <= b or b + c <= a, no triangle exists, and the method returns 0.0.

Create a file answers.md and answer two questions after you have tested your methods:

  1. area(3) and area(3.0) give different answers. Which method does each call, and how does the compiler decide? What does area(4, 5) call, and what type is the answer?
  2. Add a fifth method, static double area(int side), and compile. Quote the error you get and explain the rule behind it. Then delete the method again.

A sample program calls the methods:

Output of a sample program that calls the methods
area(3) = 9
area(3.0) = 28.274333882308138
area(2.0, 3.5) = 7.0
area(4, 5) = 20.0
area(3.0, 4.0, 5.0) = 6.0
area(1.0, 1.0, 5.0) = 0.0
Hint 1

The three-parameter version should call nothing but Math.sqrt. Do the impossible-triangle test before you calculate, and return early if it is true.

Hint 2

For question 1, the section Parameters and arguments shows what happens to an int that is passed where a double is expected, and the section Overloading says what the compiler prefers when two versions could take the arguments.

To check it, run python check.py m05 ex5 in your course kit folder.

stretch

Exercise 5.6 · Methods that call themselves

Work in work/m05-methods/ex6-recursion/ in your course kit

Write Recur.java with a class Recur and two methods, exactly:

  • static int sumDigits(int n): the sum of the digits of n, where n is not negative. For example sumDigits(472) is 13.
  • static int gcd(int a, int b): the greatest common divisor of a and b, where neither is negative and they are not both zero. Use Euclid's method: gcd(a, 0) is a, and otherwise gcd(a, b) is the same as gcd(b, a % b).

Constraint: both methods must be recursive, and neither may contain a loop. A sample program calls them:

Output of a sample program that calls the methods
sumDigits(472) = 13
sumDigits(7) = 7
sumDigits(0) = 0
gcd(12, 18) = 6
gcd(17, 5) = 1
gcd(0, 9) = 9

Then answer three questions in answers.md:

  1. For sumDigits(472), list the frames on the call stack at the deepest moment, top frame first, giving the value of n in each and the expression it is waiting to finish.
  2. In sumDigits, which test is the base case, and why does every call get closer to it?
  3. Suppose you deleted the base case from gcd. What would happen when you called it, which error would you see, and why? Trace gcd(12, 18) by hand to the end before you answer; the error may not be the one the lesson showed for countDown.
Hint 1

For a whole number n, n % 10 is its last digit, and n / 10 is the number with that digit removed. The sum of the digits is the last digit plus the sum of the digits of the rest.

Hint 2

The base case of sumDigits is the number you reach when there are no digits left to remove. Think about what n / 10 becomes after the last digit has gone.

To check it, run python check.py m05 ex6 in your course kit folder.

Summary

Words introduced in this lesson

TermMeaning
Method definitionThe header and body that say what a method is called and what it does.
Method callA use of a method's name with parentheses, which runs it.
HeaderThe first line of a definition: static int square(int n). The word signature strictly means the name and the parameter types, but in practice people often use it for the whole header.
ParameterA variable in a method's header that receives a value at each call.
ArgumentThe value supplied for a parameter at a call.
Return typeThe type of the value a method hands back, or void for none.
Return valueThe value a method gives back with return.
Call stackThe JVM's pile of frames, one for each call that has started and not yet finished.
FrameThe record of one call: its parameters, local variables and where to resume.
Local variableA variable declared inside a method, which exists during one call of it.
ScopeThe part of the code where a variable's name can be used.
LifetimeThe time while the program runs during which a variable exists.
Pass by valueGiving a method a copy of a value, not the caller's variable.
static methodA method that belongs to the class itself, not to an object.
OverloadingDefining several methods with one name and different parameter lists.
RecursionA method calling itself.
Base caseThe input for which a recursive method answers without calling itself.
StackOverflowErrorThe failure when the call stack runs out of space, usually from recursion without a base case.