Skip to content
Happy Programming Guide
Start learning
Java

Building a Complete Java Project

Take Java from a single file to a real project: Maven, package structure, dependency injection by hand, tests, configuration, logging and a runnable jar.

Colourful plastic building bricks on a table

A complete Java project is a single-file program that has grown a build tool, a package structure, tests and a way to be configured without editing code. This guide builds one from scratch with Maven — a small command-line tool that reads a CSV and prints a summary — so you can see each piece being added and why.

Starting the project#

Terminal
mvn archetype:generate \
  -DgroupId=com.example.expenses \
  -DartifactId=expense-summary \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DinteractiveMode=false
Output
expense-summary/
    pom.xml
    src/
        main/
            java/com/example/expenses/
                Main.java
                cli/Arguments.java
                parse/ExpenseParser.java
                report/SummaryReport.java
                model/Expense.java
            resources/
                application.properties
        test/
            java/com/example/expenses/
                parse/ExpenseParserTest.java
            resources/
                sample.csv
    target/            <- build output, never committed

The layout is not arbitrary — Maven relies on it. Anything under src/main/resources is packaged into the jar and readable from the classpath; anything under src/test is compiled but not shipped.

The build file#

XML
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>expense-summary</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.10.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>2.0.13</version>
    </dependency>
  </dependencies>
</project>

Setting project.build.sourceEncoding is worth doing on every project. Without it Maven uses the platform default, so a build on a colleague’s machine can produce different behaviour for non-ASCII text.

Packages by responsibility#

Output
// Avoid - groups by kind, so one feature is spread across every package
com.example.expenses.models
com.example.expenses.services
com.example.expenses.utils

// Prefer - groups by what it does
com.example.expenses.parse
com.example.expenses.report
com.example.expenses.cli

The second layout means a change to how reports are formatted touches one folder. The first means every change touches every folder.

The model#

JAVA
package com.example.expenses.model;

import java.math.BigDecimal;
import java.time.LocalDate;

public record Expense(LocalDate date, String category, BigDecimal amount) {

    public Expense {
        if (category == null || category.isBlank()) {
            throw new IllegalArgumentException("category is required");
        }
        if (amount == null || amount.signum() < 0) {
            throw new IllegalArgumentException("amount must not be negative");
        }
    }

    public String normalisedCategory() {
        return category.strip().toLowerCase();
    }
}

That compact constructor runs before the fields are assigned, so an invalid Expense cannot exist. Validating at construction rather than at use is what makes the rest of the code simpler.

Use BigDecimal for money, never double. Binary floating point cannot represent decimal fractions exactly, and the errors accumulate in totals.

Parsing#

JAVA
package com.example.expenses.parse;

import com.example.expenses.model.Expense;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.*;
import java.time.LocalDate;
import java.util.*;

public class ExpenseParser {

    public List<Expense> parse(Path path) throws IOException {
        List<Expense> expenses = new ArrayList<>();

        try (BufferedReader reader = Files.newBufferedReader(path)) {
            String header = reader.readLine();
            if (header == null) return expenses;

            String line;
            int lineNumber = 1;

            while ((line = reader.readLine()) != null) {
                lineNumber++;
                if (line.isBlank()) continue;

                String[] parts = line.split(",", -1);
                if (parts.length < 3) {
                    throw new ParseException("Line " + lineNumber + " has too few columns");
                }

                try {
                    expenses.add(new Expense(
                        LocalDate.parse(parts[0].strip()),
                        parts[1].strip(),
                        new BigDecimal(parts[2].strip())
                    ));
                } catch (RuntimeException e) {
                    throw new ParseException("Line " + lineNumber + ": " + e.getMessage(), e);
                }
            }
        }
        return expenses;
    }
}

The line number in the message is the difference between a useful error and a useless one. “Could not parse date” sends someone hunting through ten thousand rows; “Line 4,712: could not parse date” does not.

Reporting#

JAVA
package com.example.expenses.report;

import com.example.expenses.model.Expense;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class SummaryReport {

    public Map<String, BigDecimal> totalsByCategory(List<Expense> expenses) {
        return expenses.stream().collect(Collectors.groupingBy(
            Expense::normalisedCategory,
            TreeMap::new,
            Collectors.reducing(BigDecimal.ZERO, Expense::amount, BigDecimal::add)
        ));
    }

    public List<String> format(Map<String, BigDecimal> totals) {
        if (totals.isEmpty()) return List.of("No expenses found.");

        int width = totals.keySet().stream().mapToInt(String::length).max().orElse(8);

        List<String> lines = new ArrayList<>();
        totals.forEach((name, total) ->
            lines.add("%-" + width + "s  %10.2f".formatted(name, total)));

        lines.add("-".repeat(width + 12));
        lines.add(("%-" + width + "s  %10.2f")
            .formatted("total", totals.values().stream()
                                      .reduce(BigDecimal.ZERO, BigDecimal::add)));
        return lines;
    }
}

Neither method prints anything. That is deliberate — a method that returns lines can be tested in one assertion, while a method that prints can only be tested by capturing standard output.

Wiring it together#

JAVA
package com.example.expenses;

import com.example.expenses.parse.ExpenseParser;
import com.example.expenses.report.SummaryReport;
import java.nio.file.Path;

public class Main {

    private final ExpenseParser parser;
    private final SummaryReport report;

    Main(ExpenseParser parser, SummaryReport report) {
        this.parser = parser;
        this.report = report;
    }

    public static void main(String[] args) {
        System.exit(new Main(new ExpenseParser(), new SummaryReport()).run(args));
    }

    int run(String[] args) {
        if (args.length < 1) {
            System.err.println("Usage: expense-summary <file.csv>");
            return 2;
        }

        try {
            var expenses = parser.parse(Path.of(args[0]));
            report.format(report.totalsByCategory(expenses)).forEach(System.out::println);
            return 0;
        } catch (NoSuchFileException e) {
            System.err.println("No such file: " + e.getFile());
            return 2;
        } catch (Exception e) {
            System.err.println("Failed: " + e.getMessage());
            return 1;
        }
    }
}

That is dependency injection without a framework: Main receives its collaborators rather than constructing them, so a test can pass in fakes. The distinct exit codes let a shell script react differently to a missing file and a parse failure.

Tests#

JAVA
package com.example.expenses.parse;

import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;

class ExpenseParserTest {

    private final ExpenseParser parser = new ExpenseParser();

    @Test
    void readsAllRows() throws Exception {
        var path = Path.of(getClass().getResource("/sample.csv").toURI());

        assertEquals(3, parser.parse(path).size());
    }

    @Test
    void reportsTheLineNumberOnBadData() {
        var path = Path.of("src/test/resources/broken.csv");

        var error = assertThrows(ParseException.class, () -> parser.parse(path));
        assertTrue(error.getMessage().contains("Line 3"));
    }
}
Terminal
mvn test
mvn test -Dtest=ExpenseParserTest

Configuration and logging#

JAVA
import java.io.InputStream;
import java.util.Properties;

public final class Config {
    private static final Properties PROPERTIES = load();

    private static Properties load() {
        var props = new Properties();
        try (InputStream in = Config.class.getResourceAsStream("/application.properties")) {
            if (in != null) props.load(in);
        } catch (Exception ignored) { }
        return props;
    }

    public static String get(String key, String fallback) {
        return System.getenv(key.toUpperCase().replace('.', '_'))
            != null ? System.getenv(key.toUpperCase().replace('.', '_'))
                    : PROPERTIES.getProperty(key, fallback);
    }
}

Environment variables override the bundled file, which is the standard arrangement: sensible defaults in the jar, deployment-specific values supplied outside it.

JAVA
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger log = LoggerFactory.getLogger(ExpenseParser.class);

log.info("Parsed {} expenses from {}", expenses.size(), path);
log.warn("Skipping blank line {}", lineNumber);

Use the placeholder form rather than string concatenation. The message is only assembled if that level is enabled, which matters in a hot loop.

A runnable jar#

XML
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <version>3.5.2</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals><goal>shade</goal></goals>
      <configuration>
        <transformers>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>com.example.expenses.Main</mainClass>
          </transformer>
        </transformers>
      </configuration>
    </execution>
  </executions>
</plugin>
Terminal
mvn clean package
java -jar target/expense-summary-1.0.0.jar data/expenses.csv

The shade plugin bundles your dependencies into one jar, so there is nothing to install alongside it.

The README and gitignore#

Output
/target/
*.iml
.idea/
.vscode/

A README answers four questions in this order: what is this, how do I build it, how do I run it, how do I run the tests. Anything else is a bonus.

Questions people ask#

Maven or Gradle?

Maven for a first project — the XML is verbose and utterly predictable, and every tutorial assumes it. Gradle is more flexible and faster on large builds, at the cost of a more complex build script.

Do I need Spring for a project like this?

No. Spring earns its place when you have a web layer, a database and many components to wire. A command-line tool with three classes does not need a container.

Should I commit the target folder?

No. It is entirely reproducible from the source and the build file, and it is large.

How do I add a dependency?

Find it on Maven Central, copy the dependency block into pom.xml, and rebuild. Your IDE will offer to download it automatically.

Where to go next#

Java testing, the next thing this project needsRead next

Keep reading

Java

Java Design Patterns

The patterns still worth knowing in modern Java — builder, strategy, factory, observer, decorator and singleton — and which the language has…

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *