Popular Java Libraries with Example

Popular Java Libraries with Example

By - Yash Wankhede8/22/2025

When people say “Java is everywhere,” they’re usually talking about the ecosystem—millions of developers, decades of production code, and, most importantly, a deep bench of libraries. A library is a reusable set of classes and methods that you plug into your app to avoid reinventing the wheel. Java’s standard library covers a lot, and the community fills in the rest. In this guide, you’ll learn how to think about libraries, what to pick for common jobs, and how to glue them together with small but realistic code samples. Popular Java Libraries with Example – Explore widely used Java libraries, their features, and code examples to simplify development and boost programming efficiency.

 

Libraries vs. Frameworks (and Why It Matters)

A library is something you call. A framework is something that calls you. With a library, you stay in control: you pick the methods and compose them to solve your problem. With a framework (like Spring Boot), you agree to its life cycle and conventions. Most Java projects blend the two: frameworks to shape the app, libraries to do specific tasks—parsing JSON, logging, testing, HTTP calls, and more.

 

Managing Libraries: JARs, Maven, and Gradle

Java packages libraries as JAR files. You rarely download these manually; instead, you declare them as dependencies in a build tool:

Gradle (Kotlin DSL)

dependencies {

    implementation("com.fasterxml.jackson.core:jackson-databind:2.17.1")

    implementation("com.squareup.okhttp3:okhttp:4.12.0")

    testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")

}

 

 

Maven (pom.xml)

<dependencies>

  <dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.17.1</version>

  </dependency>

  <dependency>

    <groupId>com.squareup.okhttp3</groupId>

    <artifactId>okhttp</artifactId>

    <version>4.12.0</version>

  </dependency>

  <dependency>

    <groupId>org.junit.jupiter</groupId>

    <artifactId>junit-jupiter</artifactId>

    <version>5.10.2</version>

    <scope>test</scope>

  </dependency>

</dependencies>

 

 

(Exact versions change—pin them intentionally.)

The Standard Library: Your First Stop

Before pulling a third-party dependency, ask: Can the JDK already do this? Java’s standard library is big, fast, and stable.

 

1) Collections and Streams

List, Set, Map are your bread and butter. Streams let you write concise data pipelines.

 

import java.util.*;

import java.util.stream.*;

 

public class TopWords {

    public static void main(String[] args) {

        List<String> words = List.of("java","code","java","library","stream","code","java");

        Map<String, Long> freq = words.stream()

            .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

 

        List<String> top = freq.entrySet().stream()

            .sorted(Map.Entry.<String, Long>comparingByValue().reversed())

            .limit(2)

            .map(Map.Entry::getKey)

            .toList();

 

        System.out.println(top); // e.g., [java, code]

    }

}

 

2) Concurrency

java.util.concurrent gives you thread pools, queues, locks, and CompletableFuture.

 

import java.util.concurrent.*;

 

public class AsyncSum {

    public static void main(String[] args) throws Exception {

        ExecutorService pool = Executors.newFixedThreadPool(2);

        CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 40, pool);

        CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 2, pool);

 

        int result = a.thenCombine(b, Integer::sum).get();

        System.out.println(result); // 42

        pool.shutdown();

    }

}

 

3) NIO and Files

java.nio.file makes file I/O simple and safe.

 

import java.nio.file.*;

import java.io.IOException;

 

public class ConfigLoader {

    public static void main(String[] args) throws IOException {

        Path p = Path.of("app.properties");

        if (Files.exists(p)) {

            Files.lines(p).forEach(System.out::println);

        } else {

            Files.writeString(p, "mode=dev\nthreads=4\n");

        }

    }

}

 

4) java.time (Dates and Times Done Right)

Replace old Date/Calendar with LocalDate, Instant, and Duration.

 

import java.time.*;

 

public class TimeWindow {

    public static void main(String[] args) {

        Instant start = Instant.now();

        Instant end = start.plus(Duration.ofMinutes(15));

        System.out.println("Window: " + start + " → " + end);

    }

}

 

5) HTTP Client (Since Java 11)

Built-in HTTP means you can often avoid extra dependencies.

 

import java.net.http.*;

import java.net.URI;

 

public class BuiltInHttp {

    public static void main(String[] args) throws Exception {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest req = HttpRequest.newBuilder(URI.create("https://httpbin.org/get")).build();

        HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());

        System.out.println(res.statusCode());

        System.out.println(res.body());

    }

}

 

When You Need More: Popular Third-Party Libraries

 

Some tasks are better served by the community. Here are sensible, well-supported choices and why you might pick them.

 

JSON: Jackson

 

Fast, widely adopted, and flexible.

 

import com.fasterxml.jackson.databind.ObjectMapper;

 

record User(String name, int age) {}

 

public class JsonDemo {

    public static void main(String[] args) throws Exception {

        ObjectMapper om = new ObjectMapper();

        String json = om.writeValueAsString(new User("Yash", 23));

        System.out.println(json);

 

        User u = om.readValue("{\"name\":\"Asha\",\"age\":21}", User.class);

        System.out.println(u.name() + " → " + u.age());

    }

}

HTTP: OkHttp

If you want a minimal, ergonomic HTTP client (e.g., more control, interceptors), OkHttp is a favorite.

 

import okhttp3.*;

public class OkHttpDemo {

    public static void main(String[] args) throws Exception {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()

                .url("https://httpbin.org/anything")

                .header("X-Client", "OkHttpDemo")

                .build();

 

        try (Response response = client.newCall(request).execute()) {

            System.out.println(response.code());

            System.out.println(response.body().string());

        }

    }

}

 

Utility Belt: Apache Commons & Guava

 

Apache Commons Lang/IO: Strings, I/O helpers, reflection utilities.

 

Guava: Caches (CacheBuilder), immutable collections, Optional before Java 8 (still useful for extras), preconditions.

 

// Guava example: tiny in-memory cache

import com.google.common.cache.*;

Explore Other Demanding Courses

No courses available for the selected domain.

public class MiniCache {

    public static void main(String[] args) {

        Cache<String, String> cache = CacheBuilder.newBuilder()

            .maximumSize(100)

            .build();

 

        cache.put("token", "abc123");

        System.out.println(cache.getIfPresent("token"));

    }

}

 

Logging: SLF4J + Logback

SLF4J gives you a logging API that decouples your app from the logging engine; Logback is a common backend.

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

public class CalculatorLogger {

    private static final Logger LOGGER = LoggerFactory.getLogger(CalculatorLogger.class);

 

    public static void main(String[] args) {

        LOGGER.info("Application started...");

 

        int x = 12;

        int y = 4;

 

        try {

            int result = divide(x, y);

            LOGGER.debug("Dividing {} by {} gives {}", x, y, result);

        } catch (ArithmeticException e) {

            LOGGER.error("Division failed due to {}", e.getMessage());

        }

 

        LOGGER.info("Application finished successfully.");

    }

 

    private static int divide(int a, int b) {

        if (b == 0) {

            throw new ArithmeticException("denominator cannot be zero");

        }

        return a / b;

    }

}

Testing: JUnit 5 (+ AssertJ / Mockito)

 

JUnit 5 is the modern unit testing standard. Add AssertJ for fluent assertions and Mockito for mocks.

 

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

 

class MathUtil {

    static int clamp(int value, int min, int max) {

        return Math.max(min, Math.min(max, value));

    }

}

public class MathUtilTest {

    @Test

    void clampsWithinBounds() {

        assertEquals(5, MathUtil.clamp(5, 1, 10));

        assertEquals(1, MathUtil.clamp(-5, 1, 10));

        assertEquals(10, MathUtil.clamp(99, 1, 10));

    }

}

 

Putting It All Together: A Tiny CLI That Fetches, Parses, and Logs

Here’s a compact example that uses OkHttp to fetch JSON, Jackson to parse it, and SLF4J for logging. You can run this as a plain Java class.

 

import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.ObjectMapper;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

public class UserFetcher {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserFetcher.class);

 

    public static void main(String[] args) {

        String apiUrl = "https://jsonplaceholder.typicode.com/users/1"; // sample public API

 

        OkHttpClient client = new OkHttpClient();

        ObjectMapper mapper = new ObjectMapper();

 

        try {

            Request request = new Request.Builder().url(apiUrl).build();

            LOGGER.info("Sending GET request to {}", apiUrl);

 

            try (Response response = client.newCall(request).execute()) {

                if (!response.isSuccessful()) {

                    LOGGER.warn("Request failed with status {}", response.code());

                    return;

                }

 

                String body = response.body().string();

                JsonNode jsonNode = mapper.readTree(body);

 

                String name = jsonNode.get("name").asText();

                String email = jsonNode.get("email").asText();

 

                LOGGER.info("Fetched user → Name: {}, Email: {}", name, email);

            }

 

        } catch (Exception e) {

            LOGGER.error("Error occurred while fetching user data", e);

        }

    }

}

This little program shows a realistic workflow:

Build a request.

Handle non-200 responses.

Parse JSON safely.

Log meaningful information.

Choosing Libraries Wisely

The hardest part isn’t coding—it’s choosing. Use this checklist:

Does the JDK do it already? Prefer standard library where possible.

Health of the project: Recent commits, regular releases, issue responsiveness.

Adoption: Is it widely used? More users often means more bug reports and fixes.

Licensing: Apache 2.0 and MIT are developer-friendly; read the license.

Binary size and dependencies: Avoid “dependency explosion” in modular apps.

Long-term support: Will you still trust it in three years?

Keeping Your Dependency Tree Clean

Pin versions deliberately. Avoid “latest” everything; upgrade on your schedule.

Use BOMs (Bill of Materials) where available to keep versions consistent.

Run dependency updates regularly but in small batches (so rollbacks are easy).

Scan for vulnerabilities using tools like OWASP Dependency-Check or your CI platform’s built-ins.

Remove unused libraries. If you only needed a single method once, consider copying a tiny utility instead of pulling a large dependency.

 

Final Thoughts

Java’s library ecosystem is a superpower. Start with the JDK; add focused, well-maintained libraries for JSON, HTTP, logging, and testing. Keep your dependency tree tidy, write a few glue classes, and you’ll ship reliable features faster. The examples above are intentionally small but idiomatic—steal the patterns, then scale them to your real application.

 

Do visit our channel to learn More: SevenMentor

 

Author:-

Yash Wankhede

Get Free Consultation

Loading...

Call the Trainer and Book your free demo Class..... Call now!!!

| SevenMentor Pvt Ltd.

© Copyright 2025 | SevenMentor Pvt Ltd.

Share on FacebookShare on TwitterVisit InstagramShare on LinkedIn