Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Application Program Interface (API) and Libraries

Lesson ~10 min read 8 MCQs

In simple terms: 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).

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
This is a class diagram showing the relationship between programming concepts. A box labeled "Library" points to a box labeled "Package," indicating a library contains many packages. The "Package" box points to a "Class" box, which is then specified as a "String" class, indicating a package contains many classes. The "String" class box lists private attributes like 'value' and public behaviors like 'length()' and 'substring()'.

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) and java.util (for utility tools).
A visual hierarchy of how libraries, packages, and classes are organized in Java.

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.

  • Attributes
    are 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 Student object, attributes might be studentID, firstName, and gpa.
    • For a String object like "Hello", the core attribute is the sequence of characters 'H', 'e', 'l', 'l', 'o'.
  • Behaviors
    are 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 Student object, a behavior might be calculateGPA() or printTranscript().
    • For a String object, behaviors include .length() (get the number of characters) and .toUpperCase() (get a new string in all caps).

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.

  • Attributes
    Its 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.
  • Behaviors
    We 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.

Comparing the internal details of a class (chef's secret) versus its public API (menu).

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    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:

    1. 1
      Identify the Tool
      These 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 Math class.
    2. 2
      Consult the API (The Menu)
      We look at the documentation for the Math class. 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 a double value." This is a behavior of the Math class.
      • 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.
    3. 3
      Write the Code
      Now we can use these behaviors. The Math class is special because its methods are static, 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
    Tracing the use of `Math.abs()` and `Math.pow()` methods.
    Example 2

    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:

    1. 1
      Identify the Tool
      The name "Aaliyah Jones" is a String. So, we need to use the behaviors available in the String class.
    2. 2
      Consult the API
      We look at the String class 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 String object are the actual characters, but we can't (and shouldn't) access them directly. We use the length() method to get information about those attributes.
    3. 3
      Write the Code
      We create a String object 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
      }
    Flowchart for checking if a string's length exceeds a limit.

    Try it yourself

    Ready to try reading the menu yourself?

    1. The Scanner Class: We use the Scanner class to get user input, like this: Scanner keyboard = new Scanner(System.in);. The Scanner class is in the java.util package. 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?

    2. String Detective: Go to the official Oracle Java documentation for the String class (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?

    The `Scanner` class, its package, and common methods.
    Using `startsWith()` for string prefixes versus manual character checking.