Sub topic 2
Building by Hand: javac, the Classpath, and JAR Files
Before you use Maven or Gradle, it helps to build a project once without them. The JDK (Java Development Kit, the set of tools that ships with Java) already has everything you need to compile, run, and package a program. Each step is a plain command. When you see those steps up close, it is easier to see what a build tool does for you later.
This chapter builds a small program by hand, packages it, and then adds a library to show where manual builds start to hurt.
The Program We Will Build
We start with one class. Save it at src/main/java/com/example/App.java. The folder path matches the package name com.example. The next chapter explains why projects use this layout.
package com.example;
public class App {
public static void main(String[] args) {
System.out.println(greeting("World"));
}
static String greeting(String name) {
return "Hello, " + name + "!";
}
}The main method prints a greeting. The greeting method is separate so that tests can call it later in the tutorial.
The Three JDK Tools
The JDK gives you three tools for this job:
| Tool | What it does | Input | Output |
|---|---|---|---|
| `javac` | Compiles source code into bytecode | `.java` files | `.class` files |
| `java` | Starts the JVM and runs a class | `.class` files or a `.jar` | A running program |
| `jar` | Packs files into one archive | A folder of `.class` files | A `.jar` file |
Bytecode is the compact instruction format that the JVM (Java Virtual Machine, the program that runs Java code) understands. A JAR file (Java ARchive) is a ZIP file that holds compiled classes plus a little extra information about them.
Step by Step: Compile, Run, Package
Run these commands from the folder that contains src:
mkdir -p out
javac -d out src/main/java/com/example/App.java
java -cp out com.example.App
jar --create --file app.jar --main-class com.example.App -C out .
java -jar app.jarBoth java commands print Hello, World!. Here is what each line does.
mkdir -p outmakes an output folder. Keeping compiled files apart from source files keeps the project tidy.javac -d out ...compiles the source. The-dflag sets the destination folder. javac creates subfolders that match the package, so the result isout/com/example/App.class.java -cp out com.example.Appruns the program. You give the fully qualified class name, which is the package plus the class name. You do not give a file path.jar --create ...packs everything inoutintoapp.jar. The-C out .part means "change intoout, then add everything there." The--main-classflag records which class to start.java -jar app.jarruns the JAR. Java reads the main class from inside the archive.
You can look inside the JAR:
jar --list --file app.jarThe output lists META-INF/MANIFEST.MF and com/example/App.class. The manifest is a small text file of settings. The --main-class flag added a Main-Class: com.example.App line to it.
The Classpath
The classpath is the list of places where the JVM and javac look for classes. Each entry is a folder or a JAR file. You set it with -cp (short for --class-path).
When Java needs com.example.App, it searches each classpath entry for com/example/App.class. If no entry has it, you get an error.
Try running from the wrong place, or leaving out -cp:
java com.example.AppWith no -cp, Java searches only the current folder. It cannot find the class there, so it prints:
Error: Could not find or load main class com.example.App
Caused by: java.lang.ClassNotFoundException: com.example.AppThis is the most common error in manual builds. It almost always means the classpath is wrong.
Adding a Library by Hand
Real programs use code written by other people, called libraries or dependencies. To see how that works by hand, we will make a tiny library ourselves and then use it. This example is separate from App. Create these two files:
// greeter/com/example/greet/Greeter.java
package com.example.greet;
public class Greeter {
public static String shout(String text) {
return text.toUpperCase() + "!";
}
}// app/com/example/Main.java
package com.example;
import com.example.greet.Greeter;
public class Main {
public static void main(String[] args) {
System.out.println(Greeter.shout("hello"));
}
}Now build the library, then build and run the app against it:
mkdir -p lib-out app-out
javac -d lib-out greeter/com/example/greet/Greeter.java
jar --create --file greeter.jar -C lib-out .
javac -cp greeter.jar -d app-out app/com/example/Main.java
java -cp app-out:greeter.jar com.example.MainThe program prints HELLO!. Notice that greeter.jar appears on the classpath twice. javac needs it to check that Greeter.shout exists. java needs it to actually run that code. If you leave it out of either command, the build or the program fails.
Where Manual Builds Break Down
One class and one library is easy to manage. Real projects are much bigger, and the manual approach gets harder quickly:
- Many source files. You must list every
.javafile, or write a script to find them. - Downloading libraries. You have to find each JAR online, pick a version, and save it somewhere.
- Libraries need libraries. A popular library such as Guava depends on other JARs. You have to find those too, and the ones they depend on.
- Long classpaths. Every JAR goes into every
javacandjavacommand, with the right separator for each operating system. - Tests. Running JUnit tests means compiling test code with extra JARs on the classpath and starting a test runner.
- Wasted work. A plain script recompiles everything every time, even files that did not change.
- Sharing. Each teammate's machine must have the same JARs in the same places.
| Task | By hand | With a build tool |
|---|---|---|
| Compile all sources | List files yourself | Found automatically from the layout |
| Get a library | Download JARs manually | Declare a name and version |
| Libraries of libraries | Track them yourself | Resolved automatically |
| Classpath | Typed into every command | Built for you |
| Run tests | Custom commands | One command, such as `mvn test` |
Maven and Gradle take care of every row in that table. The coming chapters show how, starting with the folder layout both tools expect.
Exercise
You run javac -d build src/main/java/com/example/App.java. What is the exact path of the compiled class file, and what command runs it?
Show answer
The file is build/com/example/App.class, because javac makes folders that match the package. Run it with java -cp build com.example.App.
Exercise
A teammate runs java -cp app-out com.example.Main on the Greeter example and gets NoClassDefFoundError: com/example/greet/Greeter. What is wrong, and how do you fix it on Linux?
Show answer
Main was found, but greeter.jar is missing from the classpath, so Java cannot load Greeter. Add it to the classpath: java -cp app-out:greeter.jar com.example.Main.
Exercise
Why does java -jar app.jar work without naming the class com.example.App?
Show answer
The --main-class flag wrote a Main-Class: com.example.App line into the JAR's META-INF/MANIFEST.MF file. java -jar reads that line to find the class to start.