Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Fundamentals › Java

Libraries and dependencies

What is a library, and what happens when it is missing?

Why it exists — Writing common tasks such as turning JSON text into objects or running tests from scratch in every project takes time and also causes mistakes. A library provides the classes that do these tasks as a jar file, which you take in and use with import. The troublesome work of downloading jars by hand and writing them in -cp, and of also taking care of the jars that the library itself uses, is handled by a build tool such as Gradle or Maven.

Where it's used today — You see this when you write the coordinates of a library (group:name:version) with one implementation line in the dependencies section of build.gradle in a Spring Boot project. Gradle also downloads the libraries that the library itself uses and puts them on the class path. What is needed only for tests is written as testImplementation, so that it does not go onto the class path used when the program runs. If a NoClassDefFoundError occurs while the program runs, first check whether the jar that has that class is on the class path used when running.

A library is a set of classes that someone else has made, and you usually take it as a jar file (a file that bundles compiled class files into one). In this lab, App.java turns a Map into JSON text with the ObjectMapper class of a real library called Jackson. ObjectMapper is not a class that I made and not a class provided by Java (the JDK); it is a class that a jar file called jackson-databind has. So the javac that compiles and the java that runs have to find that jar on the class path (a list of places to look for class files, written after -cp in the command). Also, jackson-databind uses other jars called jackson-core and jackson-annotations, so those two jars, which do not appear in my code, have to be there too. In this lab you take the Jackson jars out of the -cp of the two commands one at a time, and the real compile and run happen, to show which error occurs at which step. In a real project, when you write one implementation line in build.gradle, Gradle downloads these jars and puts them on the class path (Gradle is not run in this lab; it was checked against the documentation).

Checked against real execution · Ran all 9 combinations on JDK 21 with the real Jackson jars (jackson-databind and jackson-core 3.1.5, jackson-annotations 2.21), using the javac and java commands exactly as shown on the screen, and checked against the results (20/20). The one implementation line in build.gradle and the transitive dependencies were checked against the official Gradle documentation, and Gradle was not run with Jackson (Gradle 8.14.3 was run offline with Gson, which was in the cache, and only confirmed that a transitive dependency appears in both class path lists)

Concepts in this lab

Libraries and JAR files
A library is a set of classes that someone else has made, which my code uses with import. In Java it is common to bundle compiled class files into one jar file and hand it out. For example, if you look at jackson-databind-3.1.5.jar of the JSON library Jackson with jar tf, you see a list of class files such as tools/jackson/databind/ObjectMapper.class. When you compile or run my code and need a class inside a jar, you have to write that jar on the class path. Being in the same folder as my source does not put the jar among the places to look. A class that you made yourself can also be used in the same way if you bundle it with the jar tool.
Jackson and ObjectMapper
Why it exists — JSON is the most common text format in which web APIs exchange data, so writing the code that converts between objects and JSON by hand in every project takes time and causes frequent mistakes. Jackson is a library that made this conversion well once so that everyone can take and use it.
Where it's used today — Spring MVC uses Jackson when it turns the JSON received with @RequestBody into an object, and when it turns the object returned by a @RestController into a JSON response. You also use ObjectMapper when you make or read JSON text directly in code.
Jackson is a library that turns Java objects into JSON text and JSON text into Java objects, and ObjectMapper is the central class of Jackson that does that work. If you create it with new ObjectMapper() and call writeValueAsString(object), JSON text comes back. Jackson is split into several jars, so jackson-databind, which has ObjectMapper, uses jackson-core (the base for reading and writing JSON) and jackson-annotations (annotations). From Jackson 3 on, the packages and the group of the coordinates start with tools.jackson (Jackson 2 used com.fasterxml.jackson). However, jackson-annotations keeps using the package com.fasterxml.jackson.annotation in Jackson 3 too.
Class path (-cp)
Why it exists — If the JVM searched every folder of the computer for classes, it would be slow, and when classes with the same name exist in several places, it could not decide which one to use. The class path lets a person decide where to look and in what order.
Where it's used today — Usually IntelliJ or Gradle gathers the dependency jars and builds the class path, so you rarely write it yourself. If an error says that a class could not be found at run time, first check whether the jar that has that class is on the class path.
The class path is the list of places where the compiler (javac) and the JVM (java) look for user class files. In the command you write it after -cp (or --class-path, -classpath), and each place in the list is a directory or a JAR file, separated by a semicolon (;) on Windows and a colon (:) on other systems. If you do not write -cp and there is no CLASSPATH environment variable, both javac and java use the current folder. javac and java each receive the class path of their own command separately, so the -cp you gave when compiling does not carry over by itself to the run. If you write only jars in -cp, the current folder is not among the places to look, so to use the class files in the current folder too, you have to write the dot (.) at the end of the list of jars, as in the ending ;.
NoClassDefFoundError
NoClassDefFoundError is an error thrown when the JVM or a class loader tries to load the definition of a class and cannot find that definition. The API documentation describes it as the case where the definition of the class being looked for existed when the currently running class was compiled but can no longer be found. It occurs if you put a library jar on the class path when compiling and leave it out when running. It occurs in the same way if a jar that my code does not use directly but that a library I use uses (a transitive dependency) is missing. For example, if you run without jackson-core, a NoClassDefFoundError: tools/jackson/core/TreeCodec occurs at the line new ObjectMapper(). It differs in timing from a compile error such as "package ... does not exist", which occurs when the jar is missing at compile time. The compiler reports a compile error before the program runs, and this error occurs while the program is running, at the place where that class becomes needed.
Dependencies and implementation
Why it exists — If everyone downloads and uses jar files on their own, team members easily end up using different versions, and it is also easy to miss the jars that a library uses. If you write the coordinates and version in build.gradle, the same library in the same version is downloaded whoever builds on whichever computer.
Where it's used today — A library that your code imports is written in implementation. A database driver that your code does not call directly and that is needed only at run time is written in runtimeOnly, and what is used only for tests is written in testImplementation.
A dependency is a library that my project uses. In Gradle you write it inside the dependencies block as group:name:version coordinates. For example, implementation 'tools.jackson.core:jackson-databind:3.1.5'. Among the places to write them, implementation is where you write a dependency that is needed both when compiling and when running the main source. According to the Gradle documentation, a dependency declared with implementation is included in both compileClasspath, used for compiling, and runtimeClasspath, used for running, and Gradle reads the information file that comes with each library (such as the POM) and also puts in the libraries that the library uses. That is, the job of downloading jars and writing -cp in the javac and java commands is done by the build tool with one line of configuration.
Transitive dependency
A transitive dependency is a library that comes in because a library I wrote directly in the build file (a direct dependency) needs it. The build tool reads the POM that comes with each library and follows what is needed one step after another, so writing one line brings in far more libraries than that. A transitive dependency runs inside my program in exactly the same way as a direct dependency, so its vulnerability becomes a vulnerability of my program. Its name is not visible in the build file, so you have to use a command that prints the dependency tree to check what came in and by which path.

Try these

Running with the default settings

  1. When you type the javac command in the terminal, the compiler (javac) reads App.java. java.util.Map on the first line is a class provided by Java (the JDK), so it is found without writing anything more. The second line, import tools.jackson.databind.ObjectMapper;, is different. ObjectMapper is not a class of the JDK but a class provided by a library called Jackson, and a jar file called jackson-databind-3.1.5.jar has tools/jackson/databind/ObjectMapper.class.
  2. The compiler has to know what kind of class ObjectMapper is before it can compile, so it looks for ObjectMapper.class on the class path. The class path is a list of places to look for class files, and you write it after -cp in the command (on Windows, the places are separated by a semicolon (;)). This command wrote three Jackson jars, so the places to look are jackson-databind, jackson-core, and jackson-annotations.
  3. It found ObjectMapper.class in the jackson-databind jar. But the declaration of ObjectMapper has the name TreeCodec of jackson-core written in it (public class ObjectMapper implements TreeCodec<JsonNode>, …). So to check the line mapper.writeValueAsString(…), the compiler has to find TreeCodec.class too.
  4. It found TreeCodec.class in the jackson-core jar. The compiler now knows all the classes it needs.
  5. The compile succeeds and App.class is created. The only new class file in the folder is App.class. The class files of Jackson were not copied into App.class, so when running, the JVM has to find them again in the jars.
  6. When you type the java command, the JVM (java) looks for the class App on the class path and starts main. The dot (.) at the end is the current folder, that is, the place where App.class is. The -cp that you wrote for javac does not carry over to the java command, so the jars to use when running have to be written again in this command. This command wrote three Jackson jars and the dot (.).
  7. The class ObjectMapper is first needed at the first line of main, new ObjectMapper(). The JVM looks for ObjectMapper.class on the class path.
  8. It found ObjectMapper.class in the jackson-databind jar. To load this class, TreeCodec of jackson-core, which is written in its declaration, is needed too, so the JVM looks for TreeCodec.class.
  9. It finds TreeCodec.class in jackson-core, and the annotation classes that ObjectMapper uses in jackson-annotations, and loads them. writeValueAsString turns Map.of("name", "kim") into the JSON text {"name":"kim"} and returns it, and println prints that text.
  10. The one line implementation 'tools.jackson.core:jackson-databind:3.1.5' in build.gradle at the bottom of the screen is a way to hand the work done by hand so far to Gradle, a build tool. These coordinates (group:name:version) are the same as those written in the pom.xml bundled in the jackson-databind jar, and that pom.xml lists jackson-core and jackson-annotations as the libraries that jackson-databind uses. According to the Gradle documentation, a dependency declared with implementation goes into both the class path for compiling (compileClasspath) and the class path for running (runtimeClasspath), and Gradle reads such information files and also finds the libraries that a library uses (transitive dependencies) and puts them in together. This lab did not run Gradle with Jackson.

Result of this run

Code

# App.java
import java.util.Map;
import tools.jackson.databind.ObjectMapper; // A class provided by the Jackson library (jackson-databind)

public class App {
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(Map.of("name", "kim")); // Turns the Map into JSON text
        System.out.println(json);
    }
}

# Terminal (in the folder where the three Jackson jars were downloaded)
javac -cp jackson-databind-3.1.5.jar;jackson-core-3.1.5.jar;jackson-annotations-2.21.jar App.java
java -cp jackson-databind-3.1.5.jar;jackson-core-3.1.5.jar;jackson-annotations-2.21.jar;. App

# build.gradle (if you use Gradle, this one line does the job of downloading the jars and writing them in -cp)
dependencies {
    implementation 'tools.jackson.core:jackson-databind:3.1.5'
}

Assumptions of this model

The compiler and runtime are JDK 21.0.12.1 (javac 21, java 21), and the library was the three Jackson jars that had already been downloaded (jackson-databind 3.1.5, jackson-core 3.1.5, jackson-annotations 2.21) (nothing was newly downloaded). From Jackson 3 on, the package names start with tools.jackson (Jackson 2 used com.fasterxml.jackson), and only jackson-annotations keeps using the package com.fasterxml.jackson.annotation. The coordinates tools.jackson.core:jackson-databind:3.1.5 on the screen were read from the pom.xml bundled in the jackson-databind jar. All 9 combinations (3 kinds of -cp for javac and 3 kinds of -cp for java) were checked. For each combination, the three jars and App.java were placed in a new folder and the terminal commands javac and java written on the screen were run exactly as written, and the code on the screen is the same, down to the letter, as the text that the comparison program made and kept from the actual file contents and the commands actually run. What was checked is whether the compile succeeded, the number of errors and the diagnostic codes (compiler.err.doesnt.exist, compiler.err.cant.resolve.location, and compiler.err.cant.access were rendered as the error descriptions on the screen) and the lines where the errors occurred, whether App.class was created, the exit code and output of the java command, the kind of the run error and the class it concerns, and its location (App.java:6). In the combinations where the compile failed, the java command was also actually run, and I confirmed that the error that the class App cannot be found occurs. The facts that the step sentences rely on were also checked by separate runs. These are that each jar has ObjectMapper.class, TreeCodec.class, and JsonSerializeAs.class (jar tf), that the declaration of ObjectMapper implements tools.jackson.core.TreeCodec (javap), that the pom.xml of jackson-databind lists jackson-annotations and jackson-core as dependencies that are not in the test scope, that the only class file created in the folder where the compile succeeded is App.class, and that if you write only the jars when running and leave out the dot (.), it cannot find App. I also checked separately that when only jackson-annotations is removed at run time, a NoClassDefFoundError (com/fasterxml/jackson/annotation/JsonSerializeAs) occurs at App.java:6, and the sentence "the annotation classes are loaded from jackson-annotations" on the screen relies on this result. For the greet.jar in the last sentence of the summary, I bundled lib.Greeter, a class made as an example, with javac and the jar tool, compiled with -cp greet.jar and ran with -cp greet.jar;., and confirmed that hello, kim is printed. The commands were run on Windows 11, and the semicolon (;) as the class path separator is for Windows (a colon on macOS and Linux). The CLASSPATH environment variable was cleared in the process that ran them, and in an environment where this variable is set, the result of a command without -cp can differ. The error sentences of the java launcher followed the language setting of Windows used for the check run (Korean), and the number and kinds of errors and the error sentences are not set by a specification but were observed on this JDK and this Jackson version. I opened the documentation and checked it. These are, in the javac tool documentation from Oracle (https://docs.oracle.com/en/java/javase/21/docs/specs/man/javac.html) and the java tool documentation (https://docs.oracle.com/en/java/javase/21/docs/specs/man/java.html), that -cp is a list of directories and JAR files in which to look for class files and that if it is not specified, it is the current folder; and in the NoClassDefFoundError API documentation (https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/NoClassDefFoundError.html), that it is thrown when a class definition that existed at compile time cannot be found at run time. For Gradle, I followed the Java Plugin documentation (https://docs.gradle.org/current/userguide/java_plugin.html) for that implementation is a dependency needed both for compiling and for running, and that compileClasspath and runtimeClasspath include implementation; the Graph Resolution documentation (https://docs.gradle.org/current/userguide/graph_resolution.html) for that Gradle reads the metadata of a module (such as the POM), adds its dependencies to the graph, and that this process puts the correct transitive dependencies into the build; and the Dependency Management basics documentation (https://docs.gradle.org/current/userguide/dependency_management_basics.html) for that Gradle downloads, caches, and unpacks dependencies. Gradle was not run with Jackson. This is because Jackson is not in the Gradle cache of this computer and nothing was downloaded. Instead, I ran Gradle 8.14.3 offline with Gson 2.11.0, which was in the cache, and confirmed that although only one implementation line was written, error_prone_annotations, which Gson uses, also appears in the dependency lists of compileClasspath and runtimeClasspath (that jar file was not in the cache, so I could not unpack it as far as the actual jar list). So which Gradle class paths jackson-core and jackson-annotations go into was not directly confirmed with Jackson but relies on the documentation and this check. Version conflicts, the order when the same class is in several places on the class path, and the module system are not covered. Dependencies and the supply chain are covered in the in-depth lab "Dependencies and the supply chain", and Spring Boot, which looks at the dependencies and creates the configuration automatically, is covered in the in-depth lab "Spring Boot auto-configuration".

Previous lab: File I/O · Next lab: Beans

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these