Tools
Log in
English

Learn to codeJava

Java project structure

Based on Java 17

Pick an app type and Maven or Gradle, see the folder tree, get a starter zip.

Make a project skeleton

Choose what to build and a build tool; the folder tree, file notes and layer picture follow. Click a file to see its starter code, then download the zip and build it right away.

Build a
Build tool
Tests

Folder tree 7 files

  • src/
    • main/
      • java/com/example/hello/
        • service/
      • resources/
    • test/java/com/example/hello/service/

src/main/java/com/example/hello/App.java

The entry point. It reads the settings, passes the command-line argument to the service and prints the result. No rules live here.

package com.example.hello; import com.example.hello.service.GreetingService; import java.io.IOException;import java.io.InputStream;import java.util.Properties; public class App {    public static void main(String[] args) throws IOException {        Properties config = new Properties();        try (InputStream in = App.class.getResourceAsStream("/app.properties")) {            if (in != null) {                config.load(in);            }        }        GreetingService service = new GreetingService(config.getProperty("greeting", "Hello"));        String name = args.length > 0 ? args[0] : "world";        System.out.println(service.greet(name));    }}

Layers

Versions written in the files Java 17 · JUnit 5.11.3 · maven-surefire-plugin 3.5.2 · Gradle 8 or newer. Library files are not inside the zip. Your build tool downloads them on the first build.

Maven and Gradle standard folders

PathWhat goes there
src/main/javaThe program code. Folders follow the package name (com/example/hello/App.java).
src/main/resourcesFiles that are not code: settings, messages, images. They end up next to the class files after a build.
src/test/javaTest code. It never goes into the jar you ship.
src/test/resourcesSettings and data used only by tests.
pom.xml · build.gradleThe build file: Java version, libraries (dependencies), the class to run, the test tool.
target/ · build/Where build output appears (Maven uses target, Gradle uses build). Keep it out of git.

Both tools use the same layout, so moving from Maven to Gradle leaves your sources where they are.

Splitting into layers

Separate the part that takes requests, the part that decides rules and the part that stores data. In a web API, api (the controller) calls service, which calls repository, never the other way round.

With that split you can move storage from a file to a database without touching the service, and you can test service rules without a web server.

  • api reads the request and builds the response; it does no calculations.
  • service decides the rules and knows nothing about the web or the database.
  • repository saves and loads. As an interface, it lets you swap a memory version for a database one.

Naming packages

Package names start with a domain you own, written backwards: example.com becomes com.example, followed by the project name.

  • Use lowercase only. - is not allowed, so my-app becomes myapp or my_app.
  • No domain? Use an address you control, such as io.github.yourname.
  • Split by layer (api, service, repository) while small; once it grows, split by feature first (order, member) and by layer inside each.

Four common design patterns and dependency injection

Knowing when to use each matters more than the name. All of this code was run with javac and java 17.

Singleton · when there must be exactly one

For objects like settings that must exist once in the whole program. The constructor is private; you get the object only through get().

Used everywhere for convenience, it turns into a hidden global variable and makes testing hard. Use it only when one is truly required.

final class AppConfig {    private static final AppConfig INSTANCE = new AppConfig();    private final String mode;     private AppConfig() {        mode = "production";    }     static AppConfig get() {        return INSTANCE;    }     String mode() {        return mode;    }} public class Main {    public static void main(String[] args) {        AppConfig a = AppConfig.get();        AppConfig b = AppConfig.get();        System.out.println(a == b);        System.out.println(a.mode());    }}

Output

trueproduction

Factory · deciding what to create in one place

A method that looks at a condition, such as a file extension, and returns the right implementation. The caller only needs to know it gets a Parser.

interface Parser {    String parse(String line);} class CsvParser implements Parser {    public String parse(String line) {        return String.join(" | ", line.split(","));    }} class TsvParser implements Parser {    public String parse(String line) {        return String.join(" | ", line.split("\t"));    }} final class Parsers {    static Parser forFile(String fileName) {        if (fileName.endsWith(".csv")) {            return new CsvParser();        }        if (fileName.endsWith(".tsv")) {            return new TsvParser();        }        throw new IllegalArgumentException("Unknown file type: " + fileName);    }} public class Main {    public static void main(String[] args) {        Parser p = Parsers.forFile("users.csv");        System.out.println(p.parse("kim,25,seoul"));    }}

Output

kim | 25 | seoul

Strategy · swappable ways to calculate

Pull a calculation with several variants, like discounts, into an interface and choose one when creating the object. An interface with a single method also accepts a lambda (price -> price - 5000).

interface Discount {    int apply(int price);} class NoDiscount implements Discount {    public int apply(int price) {        return price;    }} class PercentOff implements Discount {    private final int percent;     PercentOff(int percent) {        this.percent = percent;    }     public int apply(int price) {        return price - price * percent / 100;    }} class Checkout {    private final Discount discount;     Checkout(Discount discount) {        this.discount = discount;    }     int total(int price) {        return discount.apply(price);    }} public class Main {    public static void main(String[] args) {        System.out.println(new Checkout(new NoDiscount()).total(20000));        System.out.println(new Checkout(new PercentOff(15)).total(20000));        System.out.println(new Checkout(price -> price - 5000).total(20000));    }}

Output

200001700015000

Observer · telling others when something happens

When an event such as a restock happens, every registered listener hears about it. The sender does not care whether a listener sends mail or writes a log.

import java.util.ArrayList;import java.util.List;import java.util.function.Consumer; class Store {    private final List<Consumer<String>> listeners = new ArrayList<>();     void onRestock(Consumer<String> listener) {        listeners.add(listener);    }     void restock(String item) {        for (Consumer<String> listener : listeners) {            listener.accept(item);        }    }} public class Main {    public static void main(String[] args) {        Store store = new Store();        store.onRestock(item -> System.out.println("Mail: " + item + " is back"));        store.onRestock(item -> System.out.println("Log: restocked " + item));        store.restock("keyboard");    }}

Output

Mail: keyboard is backLog: restocked keyboard

Dependency injection · receiving what you need through the constructor

GreetingService does not create its repository with new; it receives one in the constructor. The real program passes the memory repository, and a test passes a fake written as a lambda.

Frameworks such as Spring do the same job at scale: they find the right object and pass it to this constructor.

import java.util.Map; interface UserRepository {    String findName(int id);} class MemoryUserRepository implements UserRepository {    private final Map<Integer, String> rows = Map.of(1, "Mina", 2, "Joon");     public String findName(int id) {        return rows.getOrDefault(id, "guest");    }} class GreetingService {    private final UserRepository repo;     GreetingService(UserRepository repo) {        this.repo = repo;    }     String greet(int id) {        return "Hello, " + repo.findName(id);    }} public class Main {    public static void main(String[] args) {        GreetingService service = new GreetingService(new MemoryUserRepository());        System.out.println(service.greet(1));        System.out.println(service.greet(7));         GreetingService test = new GreetingService(id -> "Tester");        System.out.println(test.greet(99));    }}

Output

Hello, MinaHello, guestHello, Tester

Check yourself

Question 1

Where does test code go in a Maven or Gradle project?

Show the answer

Answer: 2. src/test/java Test code lives in src/test/java. It is compiled only for tests and never ends up in the jar you ship.

Question 2

What do you gain when GreetingService takes its repository in the constructor?

Show the answer

Answer: 2. Tests can pass in a fake repository Because the repository comes from outside, a test can pass a fake (a lambda) and check the service rules without any database.

Questions people ask

Should I pick Maven or Gradle?

Both use the same folder layout. Pick Maven if you like a fixed XML format, Gradle if you prefer short, code-like build files. Following what your team uses is fine.

How do I build the zip I downloaded?

Run mvn package for Maven or gradle build for Gradle inside the project folder. README.md in the zip lists the exact commands.

Why are the libraries not in the zip?

Your build tool downloads libraries such as JUnit on the first build. Their versions are written in the build file.