Lesson 1.7 · Unit 1 · CED topics 1.7 and 1.8

APIs, libraries, and documenting code

Nobody writes every piece of a program from scratch. The System.out.println you have used since Lesson 1.1 was written by someone else, and so were String, Math, and ArrayList. This lesson covers how to find out what such pre-written code does, and how to leave the same kind of information for the next reader of your own code.

Required content · LO 1.7.A, LO 1.8.A

Learning objectives.

  • 1.7.A. Identify the attributes and behaviors of a class found in the libraries contained in an API.
  • 1.8.A. Describe the functionality and use of code through comments.

Essential knowledge.

  • 1.7.A.1. Libraries are collections of classes. An application programming interface (API) specification informs the programmer how to use those classes. Documentation found in API specifications and libraries is essential to understanding the attributes and behaviors of a class defined by the API. A class defines a specific reference type. Classes in the APIs and libraries are grouped into packages. Existing classes and class libraries can be utilized to create objects.
  • 1.7.A.2. Attributes refer to the data related to the class and are stored in variables. Behaviors refer to what instances of the class can do (or what can be done with them) and are defined by methods.
  • 1.8.A.1. Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run. Three types of comments in Java include /* */, which generates a block of comments; //, which generates a comment on one line; and /** */, which are Javadoc comments and are used to create API documentation.
  • 1.8.A.2. A precondition is a condition that must be true just prior to the execution of a method in order for it to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
  • 1.8.A.3. A postcondition is a condition that must always be true after the execution of a method. Postconditions describe the outcome of the execution in terms of what is being returned or the current value of the attributes of an object.

Libraries and APIs

A library is a collection of classes. An application programming interface (API) specification is the documentation that tells a programmer how to use those classes: what each class is for, what it can store, and what it can do. A class defines a specific reference type, and classes in a library are grouped into packages.

  • java.lang holds String, Math, Integer, and Double. It is available by default; you never import it.
  • java.util holds ArrayList and Scanner. You make its classes available with an import statement at the top of the file.
  • java.io holds File and IOException. It needs an import too.
import java.util.ArrayList;
import java.util.Scanner;

Existing classes can be used to create objects, so a library is a toolbox you can reach into without knowing how each tool is built.

### Attributes and behaviors

Documentation describes a class in two parts. Attributes are the data related to the class, stored in variables. Behaviors are what instances of the class can do (or what can be done with them), and they are defined by methods. A String has the attribute "a sequence of characters" and behaviors such as finding its length.

### Reading an API entry

A typical API page lists the class's constructors and methods in a summary table. Here is the shape of such an entry for a made-up class, Thermometer, written the way real documentation reads.

Method summaryWhat it does
double getCelsius()Returns the current reading in degrees Celsius.
double getFahrenheit()Returns the current reading in degrees Fahrenheit.
void setCelsius(double c)Sets the reading to c degrees Celsius.
boolean isFreezing()Returns true if the reading is at or below 0 degrees Celsius.

Read each row from left to right: the return type (what you get back, or void for nothing), the name, and the parameter list (what you must provide). That is everything you need to call a method correctly, without seeing one line of its code. Using a method knowing what it does but not how it works is the idea of procedural abstraction, which Lesson 1.9 builds on.

Documenting code with comments

A comment is text for human readers. The compiler ignores it and it never runs. Java has three kinds.

// A single-line comment runs to the end of the line.

/* A block comment can
   span several lines. */

/** A Javadoc comment is used to create API documentation.
 *  It sits just above a class or method. */

Comments exist for both the original programmer and other programmers to understand the code and its functionality. Good comments say why or state what must be true; poor comments restate the code.

### Preconditions and postconditions

Two kinds of comment have exact meanings in this course.

  • A precondition is a condition that must be true just before a method runs for it to behave as expected. There is no expectation that the method checks it. If a caller breaks the precondition, the result is whatever happens.
  • A postcondition is a condition that must always be true after the method runs. Postconditions describe the outcome: what is returned, or what the values of an object's attributes are.
/** Returns the average of the two values.
 *  Precondition: count > 0
 *  Postcondition: the value returned is sum divided by count, as a double
 */
public static double average(int sum, int count)

The precondition is a promise the caller makes ("I will not pass a count of zero"). The postcondition is the promise the method makes in return ("if you kept your promise, here is exactly what you get").

Worked example · choosing a method from the documentation

Using the Thermometer table above, which statements do the job?

Thermometer t = new Thermometer();
t.setCelsius(100);
double f = t.getFahrenheit();
boolean frozen = t.isFreezing();
TaskMethodWhy
store a reading of 100 degrees CelsiussetCelsius(100)void, takes a double; an int argument is widened
find the reading in FahrenheitgetFahrenheit()no parameters, returns a double
decide whether it is at or below freezingisFreezing()returns a boolean

You can write correct calls without knowing how any of these methods work. If you called t.isFreezing(0), the compiler would object, because the documentation says the method has no parameters.

Worked example · what comments do to a program

Predict the output. Comments never execute, so commenting out a statement removes it.

int a = 1;
// a = a + 10;
/* a = a + 100;
   a = a + 1000; */
a = a + 5;
System.out.println(a);
6

Only a = a + 5; is live code. A frequent exam trick is a statement that looks active but sits inside a block comment, or a closing */ that ends the comment earlier than it seems.

Worked example · writing a precondition and a postcondition

A method returns what percent part is of whole. State what the caller must guarantee and what the method guarantees.

/** Returns part as a whole-number percent of whole (the fraction is dropped).
 *  Precondition: whole > 0
 *  Postcondition: the value returned is part * 100 / whole in integer division
 */
public static int percent(int part, int whole) {
    return part * 100 / whole;
}

The first call keeps the precondition and receives the promised value.

System.out.println(percent(3, 8));
37

The second call breaks the precondition, and the method does not check it for you.

System.out.println(percent(3, 0));
Exception in thread "main" java.lang.ArithmeticException: / by zero

That is exactly what the definitions predict: the caller broke the precondition, so the method owes no postcondition. Nothing in the method stops the call; a precondition is a promise the caller makes, not a check the method performs.

Exam focus

Expect to be shown an API-style table or a method header and asked which method call completes a task. Know the three comment forms, and know that preconditions are not checked by the method. The postcondition describes the result (what is returned or the new state of the object's attributes). The packages to remember: java.lang is automatic, and java.util and java.io need import.

Practice
  1. Which package must be imported with an import statement before you can use ArrayList?
    Show answer

    java.util. Classes in java.lang, such as String and Math, are available by default, but ArrayList is in java.util.

  2. What does the compiler do with the text // reset the counter?
    Show answer

    It ignores it. Comments are for human readers and are not executed or compiled into the program.

  3. What is printed?
    int n = 2;
    /* n = n * 100;
    // n = n * 10; */
    n = n + 1;
    System.out.println(n);
    Show answer

    3. The block comment starts at /* and ends at the first */, so both multiplications (even the one that begins with //) are inside it. Only n = n + 1; runs.

  4. A method's comment says "Precondition: items is not empty." A caller passes an empty list and the program fails. Whose responsibility was that?
    Show answer

    The caller's. A precondition states what must be true before the call, and the method is not required to check it. Breaking it means the method's postcondition no longer has to hold.

  5. Using the Thermometer table, write a call that stores 21.5 degrees Celsius in the object room.
    Show answer

    room.setCelsius(21.5);. The method is void, takes one double, and returns nothing, so the call is a statement by itself.

  6. In a class description, what is the difference between an attribute and a behavior?
    Show answer

    An attribute is data related to the class, stored in variables. A behavior is something instances of the class can do (or have done to them), defined by a method.

← 1.6 Compound assignment operators1.8 Method signatures →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course