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.
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.
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.
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:
Scanner is a class from the java.util library.nextLine() is a method described in the API for Scanner.In AP Computer Science A, you are expected to:
String, Math, and ArrayList.| 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) |