Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JV
Java
0/14 completed
Beginner
Hello JavaVariables and typesControl flowMethodsArrays and strings
Intermediate
Classes and objectsInheritance and interfacesCollectionsExceptions
Advanced
GenericsLambdas and streamsRecords, enums and pattern matching
Pro
Concurrency and virtual threadsBuild tools, testing and real projects
Tracks / Java / Pro

Build tools, testing and real projects

Real Java projects aren't a single Main.java. They have dozens of classes in packages, depend on libraries, have automated tests, and are built into a deployable artifact. This last lesson shows how that works, and where to go next.

Packages

Packages group related classes and prevent name clashes. The package name matches the folder structure, and by convention starts with a reversed domain name:

src/main/java/com/learntocode/shop/
├── Main.java               package com.learntocode.shop;
├── model/
│   ├── Product.java        package com.learntocode.shop.model;
│   └── Order.java
└── service/
    └── OrderService.java   package com.learntocode.shop.service;
java
package com.learntocode.shop.service;

import com.learntocode.shop.model.Order;
import com.learntocode.shop.model.Product;
import java.util.List;

public class OrderService {
    public Order place(List<Product> items) {
        // ...
    }
}

Build tools: Maven and Gradle

A build tool downloads your dependencies, compiles the code, runs the tests and packages the result into a JAR file. Java has two dominant ones; both use the standard folder layout:

my-app/
├── pom.xml  (Maven)  or  build.gradle.kts  (Gradle)
└── src/
    ├── main/java/        your code
    ├── main/resources/   config files
    └── test/java/        your tests

Maven (pom.xml, declarative XML):

xml
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.learntocode</groupId>
  <artifactId>shop</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>25</maven.compiler.release>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>6.1.3</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
bash
mvn compile        # compile
mvn test           # compile and run the tests
mvn package        # build target/shop-1.0.0.jar

Gradle (build.gradle.kts, a Kotlin script, more flexible and often faster):

kotlin
plugins {
    application
}

java {
    toolchain { languageVersion = JavaLanguageVersion.of(25) }
}

repositories { mavenCentral() }

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:6.1.3")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

application { mainClass = "com.learntocode.shop.Main" }

tasks.withType<Test> { useJUnitPlatform() }
bash
./gradlew build    # compile, test and package
./gradlew run

Libraries come from Maven Central (search at central.sonatype.com). Both tools include a wrapper script (mvnw / gradlew), so everyone on the team uses the same version. Commit it.

Version numbers in these examples were current when written; always check for the latest release.

Testing with JUnit

JUnit (version 5 and the newer 6 share the same API) is the standard Java testing framework:

java
// src/main/java/com/learntocode/shop/PriceCalculator.java
package com.learntocode.shop;

public class PriceCalculator {
    public double withDiscount(double price, int percent) {
        if (percent < 0 || percent > 100) {
            throw new IllegalArgumentException("percent must be 0-100");
        }
        return Math.round(price * (100 - percent)) / 100.0;
    }
}
java
// src/test/java/com/learntocode/shop/PriceCalculatorTest.java
package com.learntocode.shop;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;

class PriceCalculatorTest {
    private final PriceCalculator calc = new PriceCalculator();

    @Test
    void appliesTenPercentDiscount() {
        assertEquals(90.0, calc.withDiscount(100, 10));
    }

    @ParameterizedTest
    @CsvSource({ "100, 0, 100.0", "80, 25, 60.0", "59.99, 50, 30.0" })
    void handlesManyCases(double price, int percent, double expected) {
        assertEquals(expected, calc.withDiscount(price, percent));
    }

    @Test
    void rejectsInvalidPercent() {
        var error = assertThrows(IllegalArgumentException.class, () -> calc.withDiscount(100, 150));
        assertEquals("percent must be 0-100", error.getMessage());
    }
}

Run them with mvn test or ./gradlew test, or click the green ▶ next to a test in IntelliJ.

Mockito replaces dependencies (databases, payment gateways, HTTP clients) with fakes in tests:

java
@Test
void sendsReceiptAfterPayment() {
    EmailService email = mock(EmailService.class);
    PaymentGateway gateway = mock(PaymentGateway.class);
    when(gateway.charge("4242", 50.0)).thenReturn(true);

    new CheckoutService(gateway, email).checkout("4242", 50.0, "asha@example.com");

    verify(email).sendReceipt("asha@example.com", 50.0);
}

Notice CheckoutService receives its dependencies through the constructor. That's dependency injection, and it's what makes code testable. Spring builds on exactly this idea.

Logging

Use a logging library instead of System.out.println. SLF4J is the standard facade, usually backed by Logback or Log4j 2:

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

log.info("Placing order {} for {}", orderId, customer);
log.warn("Stock low for {}: {} left", sku, stock);
log.error("Payment failed for order {}", orderId, exception);

Where Java goes next: Spring Boot

Most Java backend jobs use Spring Boot. It turns plain classes into a production web service with very little code:

java
@SpringBootApplication
public class ShopApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

record Product(long id, String name, double price) {}

@RestController
@RequestMapping("/api/products")
class ProductController {
    private final ProductService service;

    ProductController(ProductService service) {     // injected by Spring
        this.service = service;
    }

    @GetMapping
    List<Product> all() { return service.findAll(); }

    @GetMapping("/{id}")
    Product one(@PathVariable long id) { return service.findById(id); }
}

Start a project at start.spring.io, then add Spring Data JPA (databases), Spring Security, validation and Actuator (health checks and metrics). The Spring Boot track on this site goes deeper.

Other paths

Direction Learn
Backend services Spring Boot, Quarkus or Micronaut; SQL and PostgreSQL; Docker
Android apps Kotlin (runs on the JVM, interoperates with Java) and Jetpack Compose
Big data and streaming Apache Kafka, Spark and Flink, which are written in or for the JVM
Desktop and tools JavaFX; IntelliJ itself is a Java application

Java versions to know

A new Java version is released every six months; every two years one is a long-term support (LTS) release that companies standardise on:

Version Year Highlights
8 2014 Lambdas, streams, Optional (still in many legacy systems)
11 2018 var in lambdas, the HTTP client, java File.java
17 2021 Records, sealed classes, text blocks, switch expressions
21 2023 Virtual threads, pattern matching for switch, record patterns, sequenced collections
25 2025 Compact source files and instance main, scoped values, many performance improvements

🎓 Java track complete!

You've learned Java's syntax and types, control flow, methods, arrays and strings, object-oriented design with classes, inheritance and interfaces, the collections framework, exceptions, generics, lambdas and streams, modern records and pattern matching, concurrency with virtual threads, and how real projects are built and tested.

Capstone project: a library management system

Build it with Maven or Gradle and JUnit:

  1. Model: records for Book (isbn, title, author, year) and Member; a sealed LoanEvent interface with Borrowed, Returned and Overdue records.
  2. Service: a Library class with addBook, borrow(isbn, memberId), returnBook and search(String query), using Map and List collections and throwing custom exceptions (BookNotAvailableException).
  3. Reports with streams: the most borrowed authors, overdue loans grouped by member, and books per decade.
  4. Persistence: save and load the library to a JSON or CSV file with try-with-resources.
  5. Concurrency: process 1,000 simulated borrow requests on virtual threads without ever lending the same copy twice.
  6. Tests: JUnit tests for every service method, including the failure cases.
  7. Stretch goal: turn it into a Spring Boot REST API.
✎ Check your understanding

1.What does a build tool like Maven or Gradle do?

2.Where do JUnit test classes go in the standard project layout?

3.Why does passing dependencies into a constructor (dependency injection) help testing?

← Concurrency and virtual threads