1. Packages, Maven, and Project Layout

Java programs usually live inside packages, and Maven gives those packages a standard directory layout. This chapter explains the structure used by the code samples in this book.

1.1. Source directories

The main example project follows this layout.

source/code
|-- pom.xml
|-- src
    |-- main
    |   |-- java
    |       |-- com
    |           |-- oneoffcoder
    |               |-- java
    |-- test
        |-- java

Production code goes under src/main/java. Test code goes under src/test/java. Maven compiles both, but it treats them differently: application classes are packaged as the program, while test classes are used only while running tests.

1.2. Packages

A Java file declares its package at the top of the file.

package com.oneoffcoder.java.intro;

That package maps to the directory src/main/java/com/oneoffcoder/java/intro. If the package and directory do not agree, compilers and IDEs will usually report confusing errors.

1.3. Imports

Classes in java.lang are imported automatically. Other classes are imported explicitly.

import java.util.Optional;

Imports tell the compiler which type a short class name refers to. Without this import, the program would need the fully qualified name java.util.Optional.

1.4. Module imports

JDK 25 also supports module import declarations. They import the public API exported by a module.

import module java.base;

Module imports are useful for compact examples and exploratory code. In larger files, explicit imports are still easier to audit.

1.5. Maven project files

The pom.xml file declares the project metadata, compiler settings, plugins, and dependencies. The example project depends on OpenCSV for CSV examples and JUnit for test examples.

<dependencies>
  <dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.0</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

Maven downloads dependencies into a local cache and places them on the classpath when it compiles or tests the project. That is why chapters can use external libraries without manually downloading .jar files.

1.6. Common Maven commands

Use these commands from source/code.

mvn compile   # compile src/main/java
mvn test      # compile and run tests
mvn clean     # remove target/

The compiled output goes into target/classes and test output goes into target/test-classes. The target directory is generated and should not be edited by hand.