Packages, Modules & Libraries
Packages
A package is a namespace and a directory, named after your reversed domain:
java.lang (with String, Math, IO) is always imported.
Module imports (Java 25)
One import pulls in every exported package of a module:
In compact source files java.base is imported automatically.
The module system
module-info.java declares what a module needs and exposes:
Worth it for libraries and large applications; unnecessary for small programs.
Standard library map
| Package | Contents |
|---|---|
java.lang |
String, Math, Thread, IO |
java.util |
collections, Optional, Random |
java.util.stream |
streams and collectors |
java.time |
dates and times |
java.nio.file |
files and paths |
java.net.http |
HTTP client |
java.util.concurrent |
threads, executors, locks |
java.util.regex |
regular expressions |
java.math |
BigDecimal, BigInteger |
External libraries
By hand it is painful:
So every project uses a build tool.
Maven
Gradle
Tip
Maven is rigid but identical everywhere — a good default. Gradle is more flexible and faster on big projects, at the price of learning a small language.
Packaging
A trimmed runtime image with only the modules you need:
Libraries worth knowing
| Purpose | Library |
|---|---|
| JSON | Jackson, Gson |
| tests | JUnit 5, AssertJ, Mockito |
| logging | SLF4J + Logback |
| web | Spring Boot, Quarkus, Javalin, Helidon |
| database | JDBC, jOOQ, Hibernate |
| CLI parsing | picocli |
★ Exercises
- Create a Maven project and get a “hello world” running with
mvn package. - Move your chapter 7 solutions into a package and fix the imports.
- Add Jackson and round-trip a record to JSON and back.
- Write a
module-info.java. What happens if you leave out arequires? - Try
import module java.base;— which imports can you delete? - Build an executable JAR and run it with
java -jar.