AP® Computer Science A · Unit 1 · Topic 1.7
APIs, Libraries, and import
An API is a library of prewritten, tested classes and methods you can call without seeing their code, and an import statement tells the compiler where to find a class so you can use its short name.
You call Math.√25 and get 5.0 back without ever writing a square root algorithm because someone already wrote, tested, and packaged that code into the Java API. An API, application programming interface, is a collection of classes grouped into packages, each class offering methods you can call by name once you know what they need as input and what they hand back. You don't need the source code. You need the documentation: the method's name, its parameter types, and its return type.
Classes in the java.lang package, like Math and String, are available automatically. Everything else needs an import statement naming the class's package, written above the class definition, like import java.util.Scanner;. This doesn't paste Scanner's code into your file. It tells the compiler where in the Java library to look so that when you write Scanner later, the compiler knows you mean java.util.Scanner and not some other class with the same short name. The compiled class stays put in the library; your program just gets permission to reference it by its short name.
Reading documentation is the skill that makes imports useful. For a method like nextInt() in the Scanner class, the documentation lists the return type, usually first, and any parameters in parentheses. Match what a method needs and returns to what your program is doing, then import the package that holds it. This is the bridge from reading Java to writing it: once you trust that Scanner, ArrayList, and Math work correctly, you can build programs on top of them instead of reinventing basic tools every time.
Key terms
- API
- Application programming interface, a set of prewritten classes and methods available for use without needing their source code.
- package
- A named group of related classes in the Java library, such as java.util.
- import statement
- A line of code that tells the compiler which package a class belongs to so its short name can be used.
- java.lang
- The one package, including Math and String, whose classes are available automatically without an import.
Watch it explained
- How it worksHow does an import statement make a class from a package available by its short name?
- How it worksWalk me through reading a method's documentation to find its parameters and return type.
- Worked exampleFind which imports a program needs before it can create a Scanner and an ArrayList.
- Common mistakeWhy isn't importing a package the same as copying its code into your own program?
Check yourself
End of topic.