AP Computer Science A · Unit 1 lecture · Part 6 of 11 · 11 min

1.7 APIs and libraries · 1.8 Documentation with comments · 1.9 Method signaturesUsing code you didn't write

Mr. Thompkins
Real programmers almost never start from nothing. They use code other people wrote and tested, and they read its documentation to learn how. That's exactly what the exam does too: it hands you a class and asks you to use it correctly.

Libraries and APIs

A library is a collection of classes that are already written and tested. An API (application programming interface) is the documentation that tells you what those classes do and how to use them, without showing you how they work inside. Classes are grouped into packages. The package java.lang, which holds String and Math, is available in every Java program automatically. Other packages are brought in with an import statement, like import java.util.Scanner;.

A class describes attributes, the data each object stores, and behaviors, what objects can do, written as methods. The Java Quick Reference on the exam is a tiny API: the String, Math, Integer, Double and ArrayList methods you can rely on.

?Wait, what's a class again?
A class is the container Java code lives in, and it's also a blueprint: it defines a new type, with attributes (data) and behaviors (methods). String is a class. Math is a class. Any class you are given on the exam is described by its API, often just a list of method headers with comments.

Comments, preconditions and postconditions

Comments are notes for humans. The compiler ignores them completely. Java has three styles: // starts a comment that runs to the end of the line, /* and */ wrap a comment that can span several lines, and /** and */ wrap a Javadoc comment, the kind used to write API documentation for a class or method.

Two kinds of comments matter on the exam. A precondition is a condition that must be true before a method is called. The method assumes it and does not have to check it. If you call the method when the precondition is false, there's no promise about what happens. A postcondition is a condition that will be true after the method finishes: what it returns, or how it changed things. On a free-response question, the preconditions tell you which cases you don't have to handle.

1/**2 * Returns how many boxes are needed to pack items.13 * Precondition: items >= 0 and perBox > 024 * Postcondition: returns the smallest number of35 *   boxes that holds all the items36 */7public static int boxesNeeded(int items, int perBox)48{9    // add perBox - 1 so integer division rounds up510    return (items + perBox - 1) / perBox;11}
  1. line 2 A Javadoc comment: what the method does
  2. line 3 What must be true before you call it
  3. line 4-5 What will be true after it finishes
  4. line 7 The header: return type, name, parameters
  5. line 9 A one-line comment; the compiler ignores it
A method with its documentation. Read the comment first: it tells you what the method promises, and what you must promise in return.

Methods and their signatures

A method is a named block of code that runs only when it's called. Using a method without knowing how it works inside is called procedural abstraction. You call Math.sqrt all the time and you have never seen its code, and you don't need to.

The first line of a method is its header. A method's signature is its name plus its parameter list: the types, in order, of the values it needs. The header also gives the return type, the type of value the method sends back. A method whose return type is void sends nothing back. It does a job (prints something, changes an object) and that's it. A non-void method returns a value, and the call is replaced by that value wherever it appears.

publicstaticdoubleaverage(int a, int b)accessclass methodreturn typenameparametersthe signature: name + parameterscall: average(3, 8)a gets a copy of 3, b a copy of 8the call is replaced bythe double it returns: 5.5
The parts of a method header. When you call the method, each argument is copied into its parameter, in order, and the call becomes the value returned.

The values you pass in a call are called arguments. The variables in the header that receive them are parameters. Arguments must match the parameters in number, order and type (an int argument can go into a double parameter, because it widens). Java passes arguments by value: the parameter gets a copy. If a method changes its own parameter, the caller's variable doesn't change.

?Wait, what's the difference between a parameter and an argument?
The parameter is the variable in the method's header, like int a in average(int a, int b). The argument is the actual value you send when you call it, like the 3 in average(3, 8). Each call copies the arguments into the parameters, in order.

Overloading

Two methods in the same class can share a name as long as their parameter lists are different: a different number of parameters, different types, or a different order of types. That's called overloading. Java picks the version whose parameters match your arguments. Math.abs is overloaded: one version takes an int and returns an int, the other takes a double and returns a double. The return type alone doesn't count, so two methods that differ only in return type can't coexist.

CallWhich version runsResult
Math.abs(-4)abs(int x)4 (an int)
Math.abs(-4.0)abs(double x)4.0 (a double)
Ship.cost(3)cost(int lbs)matches by type
Ship.cost(3, true)cost(int lbs, boolean rush)matches by count
Ship.cost(true)nonedoes not compile
Java picks the overloaded version that matches the arguments. Ship is a made-up class with two cost methods.
Pause and think
What does boxesNeeded(25, 12) return? And what happens if someone calls boxesNeeded(30, 0)?
I thought about it. Show me
boxesNeeded(25, 12) is (25 + 11) / 12, which is 36 / 12, so 3 boxes: two full boxes hold 24, and one more holds the last item. boxesNeeded(30, 0) breaks the precondition perBox > 0. The method doesn't promise anything for it, and in fact dividing by 0 throws an ArithmeticException. That's the caller's fault, not the method's.
Match the call to the header

A class Shop has these three methods.

public static double price(int qty)
public static double price(int qty, double discount)
public static void printReceipt(double total)

Which of these statements compile?

(a) double p = Shop.price(3);
(b) double q = Shop.price(3, 0.1);
(c) int r = Shop.price(2);
(d) double t = Shop.printReceipt(9.5);
(e) double u = Shop.price(2.5);
  1. (a) compiles. One int argument matches price(int qty), and it returns a double, which goes into a double.
  2. (b) compiles. An int and a double match price(int qty, double discount).
    Why?
    Overloading: Java chooses the version by the number and types of the arguments.
  3. (c) does not compile. price returns a double, and a double can't be stored in an int without a cast.
    Why?
    The call is replaced by the value it returns, so check that value's type against the variable.
  4. (d) does not compile. printReceipt is void: it returns nothing, so there's no value to store.
    Why?
    A void method can only be called as a statement on its own: Shop.printReceipt(9.5);
  5. (e) does not compile. 2.5 is a double, and no price method takes a double as its only parameter. A double can't be passed to an int parameter.

Answer: Only (a) and (b) compile.

Stuck? Get a hint
  1. For each call, count the arguments and name their types. Which header matches?
  2. Then look at the return type. Can that type be stored in the variable on the left?
  3. void means no value at all. You can't store nothing in a variable.
Check yourself
Which pair of methods could NOT both appear in the same class?
  1. Aint area(int side) and int area(int w, int h)
  2. Bdouble area(double r) and int area(int side)
  3. Cint area(int side) and double area(int len)
  4. Dint area(int w, double h) and int area(double w, int h)
Show the answer

C. Choice C has the same signature twice: the name area with one int parameter. Only the return type differs, and that is not enough to overload. The others differ in the number, types or order of parameters, which is what overloading needs. D looks odd, but swapping the order of types counts.

Check yourself
A method's comment says "Precondition: name is not empty." Which statement is true?
  1. AThe method must check whether name is empty and print an error.
  2. BCallers are responsible for passing a name that is not empty; the method may assume it.
  3. CThe method will not compile if name is empty.
  4. DThe method returns an empty String if name is empty.
Show the answer

B. A precondition is a promise the caller makes. The method is allowed to assume it and doesn't have to check. Choice A is the top trap: checking is allowed, but not required, and on an FRQ you never have to handle cases the preconditions rule out.

  • A library is a set of tested classes; its API tells you how to use them. java.lang (String, Math) is always available.
  • Comments: //, /* */, /** */. Preconditions are what the caller must make true; postconditions are what the method promises.
  • Signature: name plus parameter types in order. Return type: what comes back; void means nothing.
  • Arguments are copied into parameters, in order, and must match in number and type.
  • Overloaded methods share a name but have different parameter lists. Return type alone doesn't count.