What Is Java API? Packages, Examples, and How to Use It
TL;DR: The Java API is the large set of ready-made classes, interfaces, and methods that comes with every Java Development Kit. Instead of writing code for lists, dates, files, or network calls from scratch, you import the right package and call its methods. The API is organized into packages such as java.util, java.io, and java.time, and Java 9 grouped them into modules.

Every time you write System.out.println() or create an ArrayList, you are using the Java API. That's why a few lines of Java can sort a list, read a file, or call a web service: someone has already written and tested that code, and the API is how you access it.

This guide covers what the Java API is, how its packages are organized, how to read its documentation, and how to use and create APIs in your own code. Every example below was compiled and run on Java 21, and each shows its actual output.

Java Certification TrainingENROLL NOW
Take the Leap and Master Java Development

What Is Java API (Application Programming Interface)?

The Java application programming interface, or Java API, is a collection of prewritten classes, interfaces, and methods that your program can use without knowing how they work inside. The API defines what you can call: the class names, method names, parameters, and return types. The implementation, meaning the code that actually does the work, stays hidden behind it.

Think of it as a contract. The List interface promises that add() will put an item in the list and size() will tell you how many items it holds. You rely on that promise, and Java handles the rest.

In practice, "Java API" is used in three ways:

Meaning

What it refers to

Example

Java SE standard API

The built-in class library that ships with the JDK

java.util.ArrayList, java.time.LocalDate

Third-party library API

The public classes and methods of a library you add to a project

Jackson for JSON, Apache Commons, JUnit

Web API built in Java

An HTTP service written in Java that other programs call over a network

A REST endpoint built with Spring Boot

Most of the time, and throughout this guide, "the Java API" means the first one: the standard library every Java developer uses daily.

How Does the Java API Work?

Java API

Using the Java API takes three steps:

  1. Import the class you need from its package, for example, import java.util.ArrayList;. Classes in java.lang, such as String and System, are imported automatically.
  2. Compile your code. The compiler checks that every class and method you call exists in the API and that you pass the right types.
  3. Run it. The Java Virtual Machine (JVM) loads the API classes from the Java runtime as your program needs them.

Here's a short program that uses the Java API three times: the List interface, the ArrayList class, and the String class.

import java.util.ArrayList;
import java.util.List;

public class ApiDemo {
    public static void main(String[] args) {
        List<String> languages = new ArrayList<>();   // List is an interface, ArrayList a class
        languages.add("Java");                       // add() is a method
        languages.add("Python");
        languages.add("Go");

        System.out.println("Size: " + languages.size());
        System.out.println("Contains Java? " + languages.contains("Java"));
        System.out.println("Uppercase first: " + languages.get(0).toUpperCase());
    }
}

Output:

Size: 3
Contains Java? true
Uppercase first: JAVA

You didn't write any code to resize an array, search for an item, or change letter case. The Java API did all three.

Java Certification TrainingENROLL NOW
Dive Deep Into Java Core Concepts

Java API Packages and Modules

The Java API is organized into packages, which group related classes. These are the packages you'll use most:

Package

What it's for

Commonly used classes

java.lang

Core language classes, imported automatically

String, Math, System, Integer, Thread

java.util

Collections, utilities, and randomness

ArrayList, HashMap, List, Map, Optional, Scanner

java.util.stream

Processing collections in a functional style

Stream, Collectors

java.util.concurrent

Multithreading and concurrency

ExecutorService, CompletableFuture, ConcurrentHashMap

java.io

Reading and writing data as streams

InputStream, BufferedReader, File

java.nio.file

Modern file and directory handling

Files, Path, Paths

java.time

Dates, times, and durations

LocalDate, LocalDateTime, Duration, Period

java.net / java.net.http

Networking and HTTP requests

URI, HttpClient, HttpRequest, HttpResponse

java.sql

Database access through JDBC

Connection, PreparedStatement, ResultSet

java.math

Arbitrary-precision numbers

BigDecimal, BigInteger

javax.swing / java.awt

Desktop graphical interfaces

JFrame, JButton, Color

Modules Since Java 9

Java 9 added modules, a level above packages. A module bundles related packages and declares which ones it makes available. The most important is java.base, which contains java.lang, java.util, java.io, java.nio, java.time, and java.net, and is available to every program automatically. Other modules include java.sql for JDBC and java.net.http for the HTTP client.

A standard JDK 21 installation includes 69 modules: 22 Java SE modules (names starting with java.) and the rest JDK-specific modules (names starting with jdk.). You can list them yourself with java --list-modules.

Ready to expand your software development skills? Simplilearn’s Java Course helps you learn Java, Java EE, and service-oriented architecture concepts. Explore the course to build practical knowledge and strengthen your foundation for working with enterprise-level software applications.

Classes, Interfaces, and Methods in the Java API

Every part of the Java API is built from three kinds of pieces:

  • Classes are blueprints you can create objects from. ArrayList is a class, so new ArrayList<>() creates a list.
  • Interfaces define a set of methods without saying how they work. List is an interface, and ArrayList and LinkedList are two different classes that implement it.
  • Methods are the actions you call. add(), size(), and contains() are methods of List.

A common practice is to declare variables using the interface type (List<String> names = new ArrayList<>();). That way, you can swap in a different implementation later without changing the code that uses it. This is the API idea in miniature: depend on the contract, not on the implementation.

Java API Examples

Each example below uses a different part of the standard API.

Collections and Streams (java.util, java.util.stream)

import java.util.List;
import java.util.stream.Collectors;

public class CollectionsExample {
    public static void main(String[] args) {
        List<Integer> scores = List.of(72, 91, 58, 85, 64, 97);

        List<Integer> passed = scores.stream()
                .filter(s -> s >= 65)
                .sorted()
                .collect(Collectors.toList());

        double average = scores.stream()
                .mapToInt(Integer::intValue)
                .average()
                .orElse(0);

        System.out.println("Passed (sorted): " + passed);
        System.out.printf("Average score: %.2f%n", average);
    }
}

Output:

Passed (sorted): [72, 85, 91, 97]
Average score: 77.83

Dates and Times (java.time)

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 1, 15);
        LocalDate end = LocalDate.of(2026, 10, 1);

        Period gap = Period.between(start, end);
        long days = ChronoUnit.DAYS.between(start, end);
        DayOfWeek day = end.getDayOfWeek();

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd MMM yyyy");
        System.out.println("From " + start.format(fmt) + " to " + end.format(fmt));
        System.out.println("Gap: " + gap.getMonths() + " months and " + gap.getDays() + " days");
        System.out.println("Total days: " + days);
        System.out.println("End date falls on a " + day);
        System.out.println("30 days after start: " + start.plusDays(30));
    }
}

Output:

From 15 Jan 2026 to 01 Oct 2026
Gap: 8 months and 16 days
Total days: 259
End date falls on a THURSDAY
30 days after start: 2026-02-14

The java.time API handles month lengths and leap years for you, which is exactly the kind of detail that's easy to get wrong by hand.

Reading and Writing Files (java.nio.file)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class FileExample {
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("notes", ".txt");

        Files.write(file, List.of("Learn the Java API", "Practice with examples", "Read the docs"));

        List<String> lines = Files.readAllLines(file);
        System.out.println("Lines read: " + lines.size());
        for (int i = 0; i < lines.size(); i++) {
            System.out.println((i + 1) + ". " + lines.get(i));
        }

        Files.delete(file);
        System.out.println("File exists after delete? " + Files.exists(file));
    }
}

Output:

Lines read: 3
1. Learn the Java API
2. Practice with examples
3. Read the docs
File exists after delete? false

How to Read the Java API Documentation

Oracle publishes the full Java API documentation, generated with the Javadoc tool, for every Java version. The Java SE 25 API reference is organized from broad to specific:

  1. Modules: The home page lists every module, such as java.base and java.sql.
  2. Packages: Click a module to see its packages.
  3. Classes and interfaces: Click a package to see everything in it.
  4. Class page: Each class page shows a description, its constructors, and a Method Summary table.

Each row in the Method Summary tells you what you need to call the method. For example, ArrayList lists:

boolean    add(E e)    Appends the specified element to the end of this list.

Read it left to right: the method returns a boolean, is named add, and takes one argument of the list's element type. The Since field tells you which Java version introduced a class or method, which matters if your project runs on an older version. Use the search box at the top of the docs to jump straight to a class.

AI-Powered Full Stack Developer ProgramExplore Program
Boost Your Coding Skills. Nail Your Next Interview

How to Use an API in Java

Using Built-In APIs

For the standard API, you don't need to install anything. Import the class and call it:

import java.time.LocalDate;

LocalDate today = LocalDate.now();

If you're not sure which package a class is in, the documentation search or your IDE's auto-import will tell you.

Using Third-Party APIs

For a library that isn't part of the JDK, you add it as a dependency with a build tool such as Maven or Gradle. The build tool downloads the library, and you then import and use its classes like any other API. For example, adding Jackson to a Maven project lets you import com.fasterxml.jackson.databind.ObjectMapper and convert Java objects to JSON.

Calling Web APIs

To call a web API from Java, use the java.net.http package, standard since Java 11. You build an HttpRequest, send it with an HttpClient, and read the HttpResponse. The next section shows this in a complete, runnable example.

How to Create an API in Java

"Creating an API" can mean two things, and Java handles both.

Creating a Library API

A library API is a set of public types other code can call. The cleanest way to define one is with an interface, so callers depend on the contract while you can change the implementation.

// The API: what callers can use
interface TemperatureConverter {
    double toFahrenheit(double celsius);
    double toCelsius(double fahrenheit);
}

// The implementation: hidden behind the API
class SimpleConverter implements TemperatureConverter {
    @Override
    public double toFahrenheit(double celsius) {
        return celsius * 9 / 5 + 32;
    }

    @Override
    public double toCelsius(double fahrenheit) {
        return (fahrenheit - 32) * 5 / 9;
    }
}

public class LibraryApiExample {
    public static void main(String[] args) {
        TemperatureConverter converter = new SimpleConverter();
        System.out.println("37 C = " + converter.toFahrenheit(37) + " F");
        System.out.println("212 F = " + converter.toCelsius(212) + " C");
    }
}

Output:

37 C = 98.6 F
212 F = 100.0 C

Creating a Web (REST) API

A web API exposes functionality over HTTP. The example below uses only what ships with the JDK: it creates a small REST endpoint with the built-in com.sun.net.httpserver package, then calls it with the java.net.http client API.

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class RestApiExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 1. Create a web API with the JDK's built-in HTTP server
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/api/greeting", exchange -> {
            String query = exchange.getRequestURI().getQuery();
            String name = (query != null && query.startsWith("name=")) ? query.substring(5) : "World";
            byte[] body = ("{\"message\": \"Hello, " + name + "!\"}").getBytes(StandardCharsets.UTF_8);

            exchange.getResponseHeaders().add("Content-Type", "application/json");
            exchange.sendResponseHeaders(200, body.length);
            try (OutputStream out = exchange.getResponseBody()) {
                out.write(body);
            }
        });
        server.start();

        // 2. Call it with the java.net.http client API
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8080/api/greeting?name=Java"))
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("Status: " + response.statusCode());
        System.out.println("Content-Type: " + response.headers().firstValue("Content-Type").orElse(""));
        System.out.println("Body: " + response.body());

        server.stop(0);
    }
}

Output:

Status: 200
Content-Type: application/json
Body: {"message": "Hello, Java!"}

The built-in server is ideal for learning and small tools. For production web APIs, most Java teams use a framework such as Spring Boot, Quarkus, or Micronaut. These add routing, JSON conversion, validation, and security, but the idea is the same: define endpoints, accept requests, and return responses.

Most web APIs follow REST principles: a client-server split, stateless requests, a uniform interface built on HTTP methods and URIs, responses that state whether they can be cached, and a layered system.

Types of APIs

Types of API

When you build or consume web APIs in Java, you'll often see them grouped by who can access them. These categories describe web APIs in general, not the Java standard library.

Type

Who can use it

Example

Public (open)

Any external developer, often with an API key

Weather or maps APIs offered to the public

Private (internal)

Only teams inside one organization

A company's internal billing service

Partner

Selected business partners under an agreement

A payment provider's API shared with approved merchants

Composite

Callers who need several operations at once

One request that creates a customer, an order, and an invoice together

A composite API is not a microservice. It combines several API calls into a single request, reducing network round trips.

Java API vs Library vs SDK vs JDK

These four terms overlap, which is why people often confuse them.

Term

What it is

Java example

API

The contract: the classes, interfaces, and methods you can call

The java.util.List interface and its methods

Library

Packaged, reusable code that implements an API

The class library in the JDK; Jackson; Apache Commons

SDK

A software development kit: libraries plus tools, docs, and samples for building on a platform

The Android SDK; the AWS SDK for Java

JDK

Java's SDK: the compiler, tools, runtime, and full standard class library

Oracle JDK, OpenJDK builds such as Eclipse Temurin

Put simply, the API is what you call, a library is the code behind it, an SDK bundles libraries with tools, and the JDK is the SDK for Java itself. So the Java API is not a separate download. It comes inside the JDK.

What Is the Java Development Kit (JDK)?

The Java Development Kit (JDK) is the software package you install to write, compile, and run Java programs. It includes:

1. The Java class library, which is the implementation of the Java API

2. The Java runtime and JVM, which run compiled bytecode

3. Development tools, including:

  • javac, the compiler
  • java, the application launcher
  • jar, for packaging applications
  • javadoc, for generating API documentation
  • jshell, an interactive shell for testing code
  • jdb, the debugger
  • jlink, for building custom, smaller runtimes
  • Monitoring and diagnostic tools such as jconsole, jcmd, and jstack

Several vendors build the JDK, including Oracle and the OpenJDK community (for example, Eclipse Temurin, Amazon Corretto, and Microsoft Build of OpenJDK). New versions arrive every six months, and every few releases are designated long-term support (LTS) versions, which most companies standardize on.

Learn 45+ in-demand full-stack development skills and tools, including Frontend Development, Backend Development, Version Control and Collaboration, Database Management, and AI-Assisted Development, with our Full Stack Developer Course.

JDK vs JRE vs JVM

JVM

JRE

JDK

What it is

The virtual machine that executes bytecode

The JVM plus the class library needed to run programs

The JRE plus development tools

Can it run Java programs?

Yes, with the class library

Yes

Yes

Can it compile Java code?

No

No

Yes

Who needs it

Part of every Java install

End users running Java apps (historically)

Developers

You no longer need to install a JRE alongside the JDK. Since Java 11, Oracle has not offered a separate standalone JRE; the JDK contains everything needed to run Java programs. Developers who want a smaller runtime for an application can build one with jlink.

Advantages of Java APIs

Advantages of Java API

  • Less code to write: Common tasks such as sorting, parsing dates, reading files, and making HTTP calls are already built and tested.
  • Reliability: Millions of developers use the standard API, and Oracle maintains it alongside the language itself.
  • Portability: The same API behaves the same way on Windows, macOS, and Linux, because the JVM handles platform differences.
  • Backward compatibility: Code written against the Java API generally keeps working on newer Java versions, and deprecated methods are flagged well before removal.
  • Clear documentation: The official Javadoc documents every public class and method.
  • Loose coupling: Coding against interfaces lets you change implementations without rewriting the code that depends on them.
The step-by-step Java Developer Roadmap is designed for professionals seeking to understand the full scope of the profession. Explore the skills, tools, salary potential, and career roadmap needed to build a successful career as a Java Developer.

Key Takeaways

  • The Java API is the set of ready-made classes, interfaces, and methods that comes with the JDK, organized into packages and modules.
  • Core packages such as java.lang, java.util, java.io, java.nio.file, java.time, and java.net.http cover most everyday programming tasks.
  • To use an API, import its classes and call their methods; add third-party APIs with Maven or Gradle.
  • You can create your own API as a Java interface or as a web API that serves requests over HTTP.
  • The Java API is part of the JDK, which also includes the compiler, runtime, and development tools.

Conclusion

The Java API is what turns Java from a language into a practical platform. Knowing its core packages, how to read its documentation, and how to design your own APIs around interfaces will help you work faster and write code that's easier to maintain. The best next step is to open the official documentation for a class you already use, such as ArrayList or LocalDate, and explore methods you haven't tried yet.

If you want to go further, Simplilearn's Java Certification Training covers core Java and its APIs in depth, and the Full Stack Developer program shows how to build and deploy complete web APIs with frameworks like Spring Boot. Have a question about working with Java APIs? Leave it in the comments below.

FAQs

1. Is the Java API free to use?

Yes. The Java API is part of the Java platform, and OpenJDK builds are free and open source. Some commercial JDK distributions have their own license terms for production use, so check the license of the specific build your organization installs.

2. How many classes are in the Java API?

In Java 21, the Java SE modules export about 180 packages, and more than 220 when you include JDK-specific modules. Together they hold thousands of classes and interfaces, and the number grows with each release. You won't need most of them. A handful of packages covers most day-to-day work.

3. What is the difference between java and javax packages?

Packages starting with java are the core Java SE API. Packages starting with javax began as standard extensions, and some, such as javax.swing and javax.crypto, are part of Java SE today. Many enterprise javax packages moved to the Jakarta EE project and were renamed to jakarta.

4. Does the Java API change between versions?

Yes, but carefully. Each release adds new classes and methods, such as the java.net.http client in Java 11 and virtual threads in Java 21. Old methods are marked deprecated, often for several releases, before any removal. The "Since" field in the documentation shows when each feature arrived.

5. Can I use the Java API without an IDE?

Yes. An IDE helps with auto-imports and code completion, but it isn't required. You can write code in any text editor, compile it with javac, and run it with java. For single-file programs, java FileName.java compiles and runs in one step.

6. What is an API key, and do Java APIs need one?

An API key is a secret token that identifies you to a web API, so the provider can control access and track usage. The standard Java API doesn't need one, because it runs inside your own program. You only need API keys when your Java code calls an external web service that requires them.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S is a Technical Content Strategist and Data Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.
  • *All trademarks are the property of their respective owners and their inclusion does not imply endorsement or affiliation.
  • Career Impact Results vary based on experience and numerous factors.