Application Program Interface (API) and Libraries
Why this matters
Imagine you're at a new food truck in downtown Austin. The menu board is glowing, listing all your options: "ATX Brisket Tacos," "Spicy Chicken Sandwich," "Classic Cheeseburger." You don't need to know the chef's secret spice blend or the exact temperature of the grill. You just need to know what's on the menu, what it costs, and how to order it.
You point and say, "I'll have the cheeseburger." You've just used a simple interface—the menu—to get a complex product.
Programming works the same way. You don't have to write every single piece of code from scratch. Instead, you can use pre-built "kitchens" of code called libraries. The "menu" that tells you what's available in those libraries and how to order it is called an API. In this lesson, we'll learn how to read that menu to become more powerful and efficient programmers.
Concept overview
classDiagram
direction LR
class Library {
+Collection of Packages
}
class Package {
+Collection of Classes
}
class String {
-char[] value
-int count
+int length()
+String substring(int begin)
+char charAt(int index)
}
note for String "Attributes (data) are private (-)\nBehaviors (methods) are public (+)"
Library "1" -- "many" Package : contains
Package "1" -- "many" Class : contains
Class <|-- String
Core explanation
Welcome! Let's dive into one of the most powerful ideas in programming: not having to do everything yourself.
The Restaurant Analogy: APIs and Libraries
Think back to that food truck. The entire operation—the truck, the kitchen, the staff, the pantry full of ingredients—is like a code library.
- A Library is a huge collection of pre-written, pre-tested code that you can use in your own programs. Java comes with a massive, fantastic library full of tools to handle math, text, user input, and so much more.
Inside that giant library, things are organized.
- A Package is a group of related classes, like a folder on your computer. In our analogy, this is like a section of the pantry, such as the "spices" shelf or the "fresh produce" cooler. In Java, you'll see packages like
java.lang(for fundamental language features) andjava.util(for utility tools).
So what's in the packages? Classes!
- A Class is a blueprint for creating objects. It defines what an object of that type knows and what it can do. In the food truck, a recipe for a "Classic Cheeseburger" is a class. It's not a burger itself, but it's the complete set of instructions for making one.
Finally, we get to the most important part for us as users.
- An Application Programming Interface (API) is the official documentation that tells you how to use the classes in a library. It's the menu! The menu doesn't show you the messy details of how the chef cooks. It just tells you what you can order ("Cheeseburger"), what you need to provide (your payment), and what you'll get back (a delicious burger). The API for a class tells you what methods you can call and what they will do.
Attributes and Behaviors
Every class blueprint defines two key things: attributes and behaviors. The AP exam requires you to be able to identify these from the API documentation.
- Attributesare the data or properties associated with an object. They are the "nouns"—the things an object has or is. Attributes are stored in instance variables.
- For a
Studentobject, attributes might bestudentID,firstName, andgpa. - For a
Stringobject like"Hello", the core attribute is the sequence of characters 'H', 'e', 'l', 'l', 'o'.
- For a
- Behaviorsare the actions an object can perform or that can be performed on it. They are the "verbs"—the things an object can do. Behaviors are defined by the class's methods.
- For a
Studentobject, a behavior might becalculateGPA()orprintTranscript(). - For a
Stringobject, behaviors include.length()(get the number of characters) and.toUpperCase()(get a new string in all caps).
- For a
Let's look at the String class, which is part of the java.lang package in the Java library.
String greeting = "Hello, world!";
Here, greeting is an object of the String class.
- AttributesIts hidden, internal attribute is the sequence of characters 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'. We don't usually access this directly.
- BehaviorsWe can call methods on it.
int len = greeting.length(); // The length() method is a behavior. It returns 13.
String loudGreeting = greeting.toUpperCase(); // toUpperCase() is a behavior. It returns "HELLO, WORLD!".
The API documentation for the String class is your menu. It lists every single method (behavior) you can use, what information you need to give them (parameters), and what they give you back (return type).
Reading the Documentation (The API)
A typical entry in the API documentation might look something like this (in a simplified form):
Class: java.lang.String
| Method | Description |
|---|---|
int length() |
Returns the number of characters in this string. |
String substring(int beginIndex) |
Returns a new string that is a substring of this string. |
char charAt(int index) |
Returns the character at the specified index. |
boolean equals(Object anObject) |
Compares this string to the specified object for equality. |
When you see this, you can immediately identify the behaviors. The methods length(), substring(), charAt(), and equals() are all things a String object can do. The documentation tells you exactly how to "order" them. To get a substring, you need to provide a starting index number. To get the length, you don't need to provide anything at all.
This is the core skill of Topic 1.7: looking at an API and identifying the available behaviors (methods) for a class.
See it in action
Worked examples
Let's put this into practice. The key is using the API as our guide.
Example 1: Using the Math Class
Problem: Your science teacher, Mr. Davis, asks you to write a program that calculates two things: the distance a dropped object falls (which involves a negative number) and the area of a square. You need to find the absolute value of -9.8 and calculate 5 squared.
Solution Walk-through:
- 1Identify the ToolThese are standard mathematical operations. Instead of writing them ourselves, we suspect they exist in Java's standard library. A quick search of the Java API documentation points us to the
Mathclass. - 2Consult the API (The Menu)We look at the documentation for the
Mathclass. We don't need to read everything, just scan for what we need.- We search for "absolute value" and find a method:
public static double abs(double a). The description says it "returns the absolute value of adoublevalue." This is a behavior of theMathclass. - We search for "power" or "exponent" and find:
public static double pow(double a, double b). The description says it "returns the value of the first argument raised to the power of the second argument." This is another behavior.
- We search for "absolute value" and find a method:
- 3Write the CodeNow we can use these behaviors. The
Mathclass is special because its methods arestatic, meaning we call them on the class itself, not on an object.// Find the absolute value of -9.8 double gravity = -9.8; double absoluteGravity = Math.abs(gravity); // Using the abs() behavior System.out.println(absoluteGravity); // Prints 9.8 // Calculate 5 squared (5 to the power of 2) double sideLength = 5.0; double area = Math.pow(sideLength, 2); // Using the pow() behavior System.out.println(area); // Prints 25.0
Analyzing a User's Name
Problem: Aaliyah signs up for your app with her full name, "Aaliyah Jones". You need to find the length of her name and check if it's longer than a certain limit (say, 20 characters).
Solution Walk-through:
- 1Identify the ToolThe name "Aaliyah Jones" is a
String. So, we need to use the behaviors available in theStringclass. - 2Consult the APIWe look at the
Stringclass API documentation.- We need to find the length. We scan the method list and see
public int length(). The description says it "returns the length of this string." Perfect. This is a behavior. - The attributes of the
Stringobject are the actual characters, but we can't (and shouldn't) access them directly. We use thelength()method to get information about those attributes.
- We need to find the length. We scan the method list and see
- 3Write the CodeWe create a
Stringobject and call the method on it.String fullName = "Aaliyah Jones"; int nameLength = fullName.length(); // Calling the length() behavior on our object System.out.println("The name has " + nameLength + " characters."); // Prints "The name has 13 characters." if (nameLength > 20) { System.out.println("Name is too long!"); } else { System.out.println("Name length is acceptable."); // This will be printed }
Try it yourself
Ready to try reading the menu yourself?
-
The
ScannerClass: We use theScannerclass to get user input, like this:Scanner keyboard = new Scanner(System.in);. TheScannerclass is in thejava.utilpackage. Without looking at the full documentation, think about what it does. What are some behaviors (methods) you'd expect it to have? What kind of attributes (data) might it need to keep track of, even if they're hidden from you? -
String Detective: Go to the official Oracle Java documentation for the
Stringclass (a quick search for "Java 11 String API" will get you there). Your mission is to find the behavior (method) that checks if a string starts with a specific prefix. For example, does the string"INV-12345"start with"INV-"? What is the exact name of the method, and what information do you need to give it?
Practice — 8 questions
In simple terms, an API is like a restaurant menu that tells you what you can order (methods) from a kitchen's library of ingredients and recipes (classes).
String greeting = "Hello, world!";
- 1.7.A: Identify the attributes and behaviors of a class found in the libraries contained in an API.
- 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.
classDiagram
direction LR
class Library {
+Collection of Packages
}
class Package {
+Collection of Classes
}
class String {
-char[] value
-int count
+int length()
+String substring(int begin)
+char charAt(int index)
}
note for String "Attributes (data) are private (-)\nBehaviors (methods) are public (+)"
Library "1" -- "many" Package : contains
Package "1" -- "many" Class : contains
Class <|-- String
Read what Saavi narrates
Hello and welcome. I’m Saavi, and I’m so glad you’re here.
Today, we're talking about one of my favorite topics, because it’s all about working smarter, not harder.
Imagine you're at a food truck in downtown Austin. The menu board is glowing, listing all your options: brisket tacos, a spicy chicken sandwich, a classic cheeseburger. You don't need to know the chef's secret recipe. You just need to know what's on the menu and how to order it.
Programming is a lot like that. You don't have to write everything from scratch. You can use pre-built "kitchens" of code called libraries. And the "menu" that tells you what's available is called an API.
So, we're going to explore how programmers use this pre-written code. We'll focus on how to read the "recipe book"—the API documentation—to understand exactly what tools are available to us.
Let's take a real-world example. Say you need to do some math in your program. You need to find the absolute value of negative nine point eight. Instead of writing that logic yourself, you can use Java's built-in Math class.
You would look at the API, or the menu, for the Math class. You'd scan for "absolute value" and find a behavior called 'abs'. The documentation tells you that if you give this 'abs' method a number, it will return the absolute value.
So in your code, you'd write something like... Math dot abs, and then give it the number negative nine point eight. The result you get back is positive nine point eight. You didn't have to know *how* the computer did it. You just had to read the menu and place your order. That's the power of an API.
Now, a really common mistake here is trying to guess method names. For example, to get the length of a string, is the method called 'length', or 'size', or 'get length'? Guessing will only lead to errors and frustration. The right move is to consult the API documentation. Professional programmers do it all the time, and you should too. It's a skill, not a sign of weakness.
By learning to read APIs, you're not just learning a small piece of Java. You're learning how to unlock the power of vast libraries of code written by experts. Keep practicing, stay curious, and you'll be building amazing things in no time.
The library is the actual code (the kitchen). The API is the documentation (the menu). You use the API to learn how to use the library. Thinking they are the same leads to confusion about what you're supposed to be reading versus what the computer is running.
Remember the analogy: Library = Kitchen, API = Menu. You read the menu to order from the kitchen.
Most classes are designed to protect their data. You can't just reach into a `String` object and grab its internal character array. This is called encapsulation, a key principle we'll cover later.
Use the public methods (behaviors) provided in the API, like `.length()` or `.charAt()`, to get information about the object's state.
Is it `size()` or `length()` or `getCount()`? Guessing wastes time and creates bugs. The `String` class uses `length()`, but the `ArrayList` class (which we'll see later) uses `size()`.
When in doubt, look it up! Get comfortable having the Java API documentation open in a browser tab. It's what professionals do.
The whole point of an API is to hide complexity. You don't need to know the complex algorithm `Math.pow()` uses to calculate exponents. You just need to trust that it works as advertised.
Focus on the method's signature (its name, parameters, and return type) and its description in the API. Trust the abstraction.
Methods that are not marked `static` (like `String.length()`) are called "instance methods" and must be called on an *object* (an instance of the class). `String` is the blueprint; `"hello"` is the object.
First create an object, then call the method on that object. `String myString = "hello"; int len = myString.length();`. (The exception is `static` methods like those in the `Math` class, which are called on the class name itself: `Math.abs()`).