AP CSA 1.7 — Application Program Interface (API) and Libraries

Using existing code effectively

What Is an API?

An Application Program Interface (API) is a set of prewritten code and rules that allows programmers to use existing software components instead of writing everything from scratch. In Java, an API defines how your program can interact with built-in classes, methods, and packages provided by Java’s Standard Library.

Analogy: An API is like a restaurant menu.

Example in Java: When you write Math.sqrt(9), you are using the Math class API. You don’t need to know how the square root is calculated internally — only how to call it.

What Is a Library?

A library is a collection of prewritten classes and methods designed for common tasks. Java provides an extensive Standard Library that you can use in your own programs.

Package Purpose Example Classes / Usage
java.lang Core classes that are automatically available Math, String, System
java.util Utilities like user input, lists, collections Scanner, ArrayList
java.io Input/Output operations (files, streams) File, PrintWriter

These built-in libraries save time and reduce bugs because they have already been tested and optimized.

How APIs and Libraries Work Together

The API is the interface: it’s the documentation that tells you what classes exist, what methods they have, what parameters to pass, and what each method returns.

The library is the implementation: it’s the actual code that runs and does the work.

When you use a method from a library, you rely on the API to answer questions like:

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); // Using Scanner from java.util
        System.out.print("Enter your name: ");
        String name = input.nextLine();         // Calling a method from Scanner API
        System.out.println("Hello, " + name + "!");
    }
}

Here:

Why This Matters in AP CSA

In AP Computer Science A, you are expected to:

Important for the AP Exam:
You do not have to memorize every method. You will be given the official Java Quick Reference during the AP Exam. You must know how to read it and use it.

Summary

Concept Description
API A set of definitions that explains how to use prewritten code (which classes and methods exist, how to call them, and what they return).
Library A collection of ready-to-use classes and methods, such as Math, Scanner, and ArrayList.
Main benefit You save time, avoid bugs, and reuse reliable code instead of reinventing it.
Example you already know Math.random(), System.out.println(), new Scanner(System.in)