AP Computer Science A • Using Objects and Methods

Application Program Interface (API) and Libraries

How pre-built classes and documented interfaces let you write powerful programs without reinventing the wheel.

AP Computer Science A illustration with code, binary digits, and programming braces
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

Software development in the 1950s and 1960s was characterized by a painful reality: every team wrote virtually every routine from scratch. Something as fundamental as reading input from a punch card required hand-crafted machine-level instructions that varied across hardware. As programs grew larger and more ambitious, this approach became untenable—projects exceeded budgets, deadlines slipped, and bugs multiplied. The computing community recognized that a standardized way to share and reuse code was essential to scaling the discipline.

The concept of an Application Program Interface (API) arose from the desire to separate what a piece of code can do from how it does it. By documenting the public-facing contracts of reusable components—constructors, methods, parameters, return types—developers could build on each other's work without understanding every implementation detail. This principle of information hiding became a cornerstone of modern software engineering and is at the heart of the Java language specification you study for the AP exam.

1960s • Subroutine Libraries

Early FORTRAN and COBOL compilers ship with standard subroutine libraries for mathematical functions and I/O, marking the first systematic code reuse.

1972 • C Standard Library

The C language formalizes a standard library (stdio, stdlib, math) with documented function signatures—an early API in the modern sense.

1983 • Object-Oriented Paradigm

C++ and Smalltalk popularize classes and objects, transforming APIs from flat function lists into hierarchies of classes with constructors and methods.

1996 • Java API & Javadoc

Java 1.0 launches with an extensive class library and Javadoc, the auto-generated API documentation tool that became the gold standard for communicating how to use library classes.

2003–Present • AP CS A Quick Reference

The College Board publishes the AP Java Quick Reference sheet—a curated mini-API listing the classes and methods every AP student must know.

The central question this lesson addresses is deceptively simple: how do you use code that someone else wrote? Understanding the relationship between an API (the documented interface), a library (the collection of compiled classes), and your own client code is essential for every problem you will encounter on the AP Computer Science A exam.

SECTION 2

Core Principles & Definitions

Before writing any Java code, you need a precise vocabulary for the building blocks of reuse. The AP exam consistently tests whether you can read API documentation, identify what a method does based on its signature, and use library classes correctly without seeing their source code. The following four concepts form the foundation.

1

API (Application Program Interface)

A formal specification of the public constructors, methods, and constants a class exposes to client code. The API tells you what you can do, not how it is implemented.
2

Library (Class Library)

A collection of pre-written, compiled classes packaged together for reuse. Java's standard library includes thousands of classes organized into packages such as java.lang, java.util, and java.math.
3

Method Signature

The combination of a method's name, its parameter types (in order), and its return type. For example, int indexOf(String str) tells you the input and output without revealing any implementation detail.
4

Client Code

Code that uses a class by calling its public API. On the AP exam, you are almost always the client—you call methods on objects of library classes such as String, Math, ArrayList, and others listed on the Quick Reference.
5

Abstraction & Information Hiding

The principle that a client should depend only on the API, never on internal details. If the library's authors change the implementation but keep the API stable, your code still works—a crucial guarantee for large-scale software.
✦

KEY TAKEAWAY

Think of an API like a restaurant menu. The menu lists every dish (method) you can order, describes its ingredients (parameters), and tells you what you will receive (return type). You do not need to know the chef's recipe (implementation) to place your order. A library is the entire kitchen—equipped with ingredients and staff—that fulfills those orders. Your job as a client is simply to read the menu and order correctly.

SECTION 3

Visual Explanation: How Client Code Interacts with an API

The diagram below illustrates the relationship between your client code, the API boundary, and the library's internal implementation. Notice that the API acts as a contract: the client can see method signatures and documentation but is shielded from private fields, helper methods, and algorithmic details inside the library class.

Client Code → API Boundary → Library ImplementationYOUR CLIENT CODEString s = "Hello";int n = s.length();String sub = s.substring(0,3);ArrayList<Integer> list = new ArrayList<>();list.add(42);list.size();double d = Math.sqrt(25);int r = (int)(Math.random() * 10);API BOUNDARYPublic ConstructorsPublic Methods(name, params, return type)Documented Behavior(preconditions,postconditions)Public Constants(e.g., Integer.MAX_VALUE)Quick Reference SheetLIBRARY INTERNALSPrivate fields(char[] value in String)Private helper methodsAlgorithm choices(hash tables, arrays,linked nodes, etc.)Memory managementOptimization details🔒 Hidden from clientThe dashed boundary is the abstraction barrier: clients interact only with what is on the left side.
The dashed yellow boundary represents the API—it is the only thing visible to your client code on the left. The library internals on the right are hidden behind the abstraction barrier.

In the diagram, notice that the client code on the left only references method names, parameters, and return types—elements defined in the API boundary. The client never directly accesses the char[] array inside String or the resizing logic inside ArrayList. This separation is the fundamental principle you must internalize: on the AP exam, you will be expected to use classes based solely on their documented API, as listed on the Quick Reference sheet.

Mechanical and electronic counting instruments have matching front controls and different interiors.Two implementations can provide the same public counting behavior while storing their internal state differently. A representation change must preserve the interface’s promised behavior.

Two Counter implementations trace public outputs 0, 1, 2 and 3 while storing opposite internal values.Starting at zero, one Counter stores count and increments it; another stores negativeCount and decrements it, returning its negation. Three increment calls make both getCount results 3. Their private representations differ while the public trace agrees.

SECTION 4

How APIs Work: Reading Method Signatures

Although this topic is not mathematical in the traditional sense, there is a precise "grammar" to Java method signatures that functions like a formula. Every method signature in the AP Quick Reference follows a consistent pattern that, once mastered, allows you to call any method correctly on the first try.

METHOD SIGNATURE PATTERN

returnTypemethodName(ParamType1param1,ParamType2param2,...)returnType methodName(ParamType₁ param₁, ParamType₂ param₂, ...)

returnType — the data type of the value sent back to the caller (e.g., int, String, boolean, or void if nothing is returned). methodName — the identifier you use to invoke the behavior. ParamType param — each parameter specifies the type and a descriptive name for the data the method needs to do its work.

CONSTRUCTOR SIGNATURE PATTERN

ClassName(ParamType1param1,ParamType2param2,...)ClassName(ParamType₁ param₁, ParamType₂ param₂, ...)

Constructors have no return type and share the class name. They initialize a new object. Example: ArrayList() creates an empty list.

When reading the Quick Reference, you should systematically extract four pieces of information from each entry: (1) whether the method is static or instance-based, (2) the return type, (3) the parameter list (types and order), and (4) any documented preconditions. A static method like Math.abs(int x) is called on the class itself, whereas an instance method like str.length() is called on a specific object. This distinction is tested frequently.

💡

AP EXAM TIP

The Quick Reference sheet is available during the exam. You do not need to memorize every method signature, but you must know how to read it fluently. Practice translating each line into a valid Java call. For instance, int compareTo(String other) tells you the method returns an int, takes one String argument, and must be called on a String object: "apple".compareTo("banana").

SECTION 5

Key AP Library Classes & Packages

The AP Computer Science A exam focuses on a curated subset of Java's standard library. Understanding which classes belong to which packages, when you need an import statement, and whether methods are static or instance-level is essential. The table below organizes the primary classes you must know, along with representative methods from their APIs.

ClassPackageImport Needed?Key API Methods
Stringjava.langNolength(), substring(), indexOf(), equals(), compareTo()
Mathjava.langNoabs(), pow(), sqrt(), random() (all static)
Integerjava.langNoInteger.MIN_VALUE, Integer.MAX_VALUE, intValue()
Doublejava.langNodoubleValue()
ArrayList<E>java.utilYesadd(), get(), set(), remove(), size()
List<E> (interface)java.utilYesSame methods as ArrayList (defines the API contract)

AP Computer Science A — Essential Library Classes

Java Package Hierarchy for the AP ExamJava Standard Libraryjava.langAuto-imported — no import neededjava.utilMust use import statementStringlength()substring()indexOf()equals()Mathabs()pow()sqrt()random()Integer / DoubleMIN_VALUEMAX_VALUEintValue()ArrayList<E>add(E obj)get(int index)set(int, E)remove(int)size()List<E>(interface)Defines the APIcontract thatArrayList implementsKey Rule: java.lang classes need no import; java.util classes require:import java.util.ArrayList; // or import java.util.*;
Java package hierarchy showing the two main packages tested on the AP exam. Classes in java.lang (purple) are auto-imported, while java.util classes (cyan) require an explicit import statement.

A critical distinction in the diagram is the difference between java.lang and java.util. The java.lang package is so fundamental to Java that it is automatically imported into every program—you can use String, Math, Integer, and Double without writing a single import statement. In contrast, ArrayList lives in java.util and requires import java.util.ArrayList; at the top of your file. Forgetting this import is a common source of compilation errors.

SECTION 6

Worked Example: Using Library Classes from Their API

Let's walk through a realistic scenario: given only the API documentation (as on the Quick Reference sheet), write a method that takes a sentence as a String and returns a new String containing only the characters from index 0 up to (but not including) the first space. If there is no space, return the entire string.

Extracting the First Word Using String API Methods

  1. 1

    Step 1 — Identify Relevant API Methods

    From the Quick Reference, we identify two String methods: int indexOf(String str) returns the index of the first occurrence of str or −1 if not found; String substring(int from, int to) returns the substring from index from (inclusive) to index to (exclusive).
  2. 2

    Step 2 — Find the Space Index

    Call int spaceIdx = sentence.indexOf(" "); For the input "Hello World", this returns 5. For "Java", it returns −1.
    spaceIdx = 5 for "Hello World"
  3. 3

    Step 3 — Handle the Two Cases

    If spaceIdx == -1, there is no space, so return the original sentence. Otherwise, return sentence.substring(0, spaceIdx). Notice we rely on the API's guarantee that substring excludes the to index, so the space character itself is not included.
  4. 4

    Step 4 — Write the Complete Method

    Combining the steps:
    public static String firstWord(String sentence) { int spaceIdx = sentence.indexOf(" "); if (spaceIdx == -1) return sentence; return sentence.substring(0, spaceIdx); }
  5. 5

    Step 5 — Trace and Verify

    Trace with "Hello World": indexOf(" ") → 5, substring(0, 5) → "Hello". Trace with "Java": indexOf(" ") → −1, return "Java". Both results match expectations.
    firstWord("Hello World") → "Hello"

This example demonstrates the core workflow for using any library class: consult the API to identify which methods are available, match the method signatures to your problem, and compose calls with the correct argument types and order. At no point did we need to know how indexOf searches internally or how substring allocates memory—only what the API promised about their behavior.

SECTION 7

Static Methods vs. Instance Methods in the API

One of the most frequently tested distinctions on the AP exam is whether a method should be called on the class name (static) or on an object reference (instance). Getting this wrong causes a compilation error—a detail the exam exploits in its multiple-choice distractors. The table below clarifies the distinction with concrete examples drawn from the AP library.

FeatureStatic MethodInstance Method
Called onThe class name itselfA specific object (instance)
SyntaxClassName.method(args)objectRef.method(args)
AP ExampleMath.sqrt(16.0)"hello".length()
Object needed?No — no constructor call requiredYes — must create or have a reference to an object
AP ClassesMath (all methods are static)String, ArrayList, Integer, Double
Common errorCalling on an object: m.sqrt(16) ✗Calling on the class: String.length() ✗

Static vs. Instance Method Comparison

✦

KEY TAKEAWAY

A useful heuristic: if a method needs to operate on specific data stored inside an object (like the characters in a particular String), it must be an instance method called on that object. If it simply performs a general computation (like computing a square root), it is likely static and called on the class itself. On the AP exam, the Quick Reference clearly marks static methods—always check.

SECTION 8

Connection to Advanced Concepts: Interfaces, Polymorphism, and Frameworks

The API concept you have learned is the gateway to more powerful object-oriented design patterns. In college-level software engineering, APIs evolve into formal interfaces and abstract classes that enforce contracts at the compiler level. The AP exam introduces you to this through the List<E> interface: you can declare a variable as List<String> names and assign it an ArrayList<String>. The variable type references the API (the interface), while the actual object type is the library class. This is polymorphism in action.

ConceptAP Level UnderstandingAdvanced / College Level
APIRead Quick Reference to call methods on String, Math, ArrayListDesign your own APIs using interfaces and abstract classes; version APIs for backward compatibility
LibraryUse java.lang and java.util classes as a clientBuild and distribute your own libraries (JAR files, Maven packages); manage dependencies
AbstractionUnderstand that private details are hidden; trust the API contractApply SOLID principles; design by contract (preconditions, postconditions, invariants)
PolymorphismDeclare a variable as List<E> and assign an ArrayList<E>Use dependency injection; program entirely to interfaces; strategy and observer design patterns

AP-Level vs. Advanced Understanding

Beyond the AP exam, the concept of APIs expands into web APIs (REST, GraphQL), operating system APIs, and hardware APIs. In every case, the fundamental principle is the same: a documented contract allows one piece of software to use another without coupling to its implementation. Mastering this principle in the context of Java's class library gives you a transferable skill that applies across every programming language and software architecture you will encounter.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Which of the following best describes the purpose of an API in the context of Java programming?
  • A. It provides the source code for all methods in a class so that programmers can modify them.
  • B. It specifies the public constructors, methods, and their signatures so that client code can use a class without knowing its implementation.
  • C. It is the compiled bytecode (.class file) that the JVM executes at runtime.
  • D. It is a debugging tool that traces method calls during program execution.
Show answer (B)
B is correct. An API (Application Program Interface) documents the public-facing contract of a class—its constructors, method names, parameter types, and return types—so that client code can use it without seeing the implementation. A is incorrect because an API deliberately hides source code; it shows only the interface, not the implementation. C is incorrect because compiled bytecode is the library itself, not the documentation of how to use it. D is incorrect because an API is not a debugging tool; it is a specification of available functionality.

Question 2: BASIC

Consider the following code segment: String word = "Computer"; int result = word.indexOf("put"); What value is stored in result?
  • A. 3
  • B. 4
  • C. 6
  • D. −1
Show answer (A)
A is correct (value is 3). According to the String API, indexOf(String str) returns the index of the first occurrence of the substring. In "Computer", the characters are indexed C(0), o(1), m(2), p(3), u(4), t(5), e(6), r(7). The substring "put" starts at index 3 where 'p' is located. B (4) is incorrect—this would be the index of 'u', not the start of "put". C (6) is incorrect—this might result from incorrectly calculating the index after "put" ends; the method returns where the substring starts, not where it ends or beyond. D (−1) is incorrect because "put" is found in the string; −1 would indicate no match.

Question 3: INTERMEDIATE

Which of the following code segments correctly generates a random integer in the range 5 to 15, inclusive, using the Math class API?
  • A. int num = (int)(Math.random() * 15) + 5;
  • B. int num = (int)(Math.random() * 11) + 5;
  • C. int num = (int)(Math.random() * 10) + 5;
  • D. int num = (int)(Math.random() * 11) + 4;
Show answer (B)
B is correct. The API specifies that Math.random() returns a double in [0.0, 1.0). To get integers from 5 to 15 inclusive, you need 11 possible values (15 − 5 + 1 = 11). Multiplying by 11 gives [0.0, 11.0), casting to int gives 0–10, and adding 5 gives 5–15. A is incorrect because multiplying by 15 produces [0.0, 15.0), casting to int gives 0–14, then adding 5 gives 5–19—too wide a range. C is incorrect because multiplying by 10 produces [0.0, 10.0), casting to int gives 0–9, then adding 5 gives 5–14—missing 15. D is incorrect because multiplying by 11 gives [0.0, 11.0) and adding 4 gives [4.0, 15.0). Casting to int truncates, producing 4–14. This shifts the range down by 1, missing 15 and incorrectly including 4.

Question 4: APPLIED

4 pts
Write a method countLong that takes an ArrayList<String> called words and an int called threshold, and returns the number of strings in the list whose length is strictly greater than threshold. You must use only methods from the AP Quick Reference for ArrayList and String.
Show answer
Point-by-Point Rubric (4 points): Point 1 — Correct method header: The method must be declared with return type int and accept ArrayList<String> words and int threshold as parameters. Point 2 — Correct loop over ArrayList: Uses words.size() as the loop bound and words.get(i) to access each element (or uses an enhanced for loop). Point 3 — Correct comparison: Calls .length() on the String and compares with > threshold (strictly greater than, not >=). Point 4 — Correct accumulation and return: Initializes a counter to 0, increments it when the condition is met, and returns the final count. Sample Solution: public static int countLong(ArrayList<String> words, int threshold) { int count = 0; for (String w : words) { if (w.length() > threshold) { count++; } } return count; }

Question 5: CRITICAL THINKING

3 pts
A student writes the following code and is confused by the result: String a = "hello"; String b = new String("hello"); System.out.println(a == b); System.out.println(a.equals(b)); Explain why the two print statements produce different output. In your answer, discuss the difference between == and the equals() method from the String API, and explain why understanding the API contract matters for correctness.
Show answer
Point-by-Point Rubric (3 points): Point 1 — Explains == vs. equals(): The == operator compares object references (memory addresses), not content. Since a points to a String in the string pool and b is created with new (creating a separate object on the heap), they are different references. Thus a == b prints false. Point 2 — Explains equals() API behavior: The String API specifies that equals(Object other) returns true if the two strings contain the same sequence of characters, regardless of whether they are the same object in memory. Since both contain "hello", a.equals(b) prints true. Point 3 — Connects to API understanding: This illustrates why reading and trusting the API is critical. The API documents that equals() is the correct way to compare String content. A programmer who ignores the API and uses == will introduce subtle bugs—the code may appear to work with string literals (due to the string pool) but fail when strings are constructed dynamically. The API contract explicitly tells you which method provides the behavior you need.

SUMMARY

Summary

Summary

An Application Program Interface (API) is the documented contract specifying the public constructors, methods, and constants that a class exposes to client code. A library is a packaged collection of compiled classes organized into packages (such as java.lang and java.util). The key principle of abstraction ensures that you use a class through its public interface without depending on hidden implementation details.

For the AP exam, you must fluently read method signatures (return type, name, parameter list), distinguish between static methods (called on the class, e.g., Math.abs()) and instance methods (called on an object, e.g., str.length()), know which classes require an import statement, and use the Quick Reference sheet to translate API documentation into correct Java method calls.

Varsity Tutors • AP Computer Science A • Application Program Interface (API) and Libraries