Tutorials / Java: From Zero to Advanced / Final project: a library manager

Final project: a library manager

17 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

The project

For the last lesson we build a small library manager. It keeps a catalogue of books, lets you search, borrow and return them, reports on the collection and saves the catalogue to a file that can be loaded again. It uses most of what you learned: a record with validation, an enum, collections, streams, Optional, a custom checked exception, and file handling with NIO.

The design

Before typing, I split the problem into parts that each have one job.

  • Book is a record. It holds the data, validates itself, and knows how to turn into and from one CSV line.
  • Genre is an enum for the fixed categories.
  • Library holds the books and the rules: no duplicate ids, a book can be borrowed once at a time. It also saves and loads.
  • Main runs a scripted scenario so that you can see every feature at work.

Because the logic sits in Library and not in main, it is easy to test, and you can put a console menu or a web API on top later without changing it.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {

    enum Genre { FICTION, SCIENCE, HISTORY, TECH }

    record Book(int id, String title, String author, int year, Genre genre) {
        Book {
            if (title == null || title.isBlank()) {
                throw new IllegalArgumentException("title is required");
            }
        }

        String toCsv() {
            return id + ";" + title + ";" + author + ";" + year + ";" + genre;
        }

        static Book fromCsv(String line) {
            String[] p = line.split(";");
            if (p.length != 5) {
                throw new IllegalArgumentException("Bad line: " + line);
            }
            return new Book(Integer.parseInt(p[0]), p[1], p[2], Integer.parseInt(p[3]), Genre.valueOf(p[4]));
        }
    }

    static class BookUnavailableException extends Exception {
        BookUnavailableException(String message) {
            super(message);
        }
    }

    static class Library {
        private final Map<Integer, Book> books = new TreeMap<>();
        private final Set<Integer> onLoan = new HashSet<>();

        void add(Book book) {
            if (books.putIfAbsent(book.id(), book) != null) {
                throw new IllegalArgumentException("Duplicate id " + book.id());
            }
        }

        Optional<Book> find(int id) {
            return Optional.ofNullable(books.get(id));
        }

        List<Book> search(String text) {
            String q = text.toLowerCase();
            return books.values().stream()
                    .filter(b -> b.title().toLowerCase().contains(q) || b.author().toLowerCase().contains(q))
                    .toList();
        }

        void checkout(int id) throws BookUnavailableException {
            Book book = find(id).orElseThrow(() -> new BookUnavailableException("No book with id " + id));
            if (!onLoan.add(id)) {
                throw new BookUnavailableException("'" + book.title() + "' is already on loan");
            }
        }

        List<Book> available() {
            return books.values().stream().filter(b -> !onLoan.contains(b.id())).toList();
        }

        Map<Genre, Long> countByGenre() {
            return books.values().stream()
                    .collect(Collectors.groupingBy(Book::genre, TreeMap::new, Collectors.counting()));
        }

        int size() {
            return books.size();
        }

        void save(Path file) throws IOException {
            Files.write(file, books.values().stream().map(Book::toCsv).toList());
        }

        static Library load(Path file) throws IOException {
            Library library = new Library();
            for (String line : Files.readAllLines(file)) {
                if (!line.isBlank()) {
                    library.add(Book.fromCsv(line));
                }
            }
            return library;
        }
    }

    public static void main(String[] args) throws IOException {
        Library library = new Library();
        library.add(new Book(1, "Clean Code", "Robert C. Martin", 2008, Genre.TECH));
        library.add(new Book(2, "Effective Java", "Joshua Bloch", 2018, Genre.TECH));
        library.add(new Book(3, "A Brief History of Time", "Stephen Hawking", 1988, Genre.SCIENCE));
        library.add(new Book(4, "Midnight's Children", "Salman Rushdie", 1981, Genre.FICTION));
        library.add(new Book(5, "The Silk Roads", "Peter Frankopan", 2015, Genre.HISTORY));

        System.out.println("Books: " + library.size());
        System.out.println("Search 'java': " + library.search("java").stream().map(Book::title).toList());
        System.out.println("By genre: " + library.countByGenre());

        try {
            library.add(new Book(2, "Duplicate", "Nobody", 2000, Genre.FICTION));
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        for (int id : new int[]{2, 2, 42}) {
            try {
                library.checkout(id);
                System.out.println("Checked out book " + id);
            } catch (BookUnavailableException e) {
                System.out.println("Cannot check out: " + e.getMessage());
            }
        }
        System.out.println("Available: " + library.available().stream().map(Book::title).toList());

        System.out.println(library.find(3).map(b -> b.title() + " (" + b.year() + ")").orElse("not found"));
        System.out.println(library.find(99).map(Book::title).orElse("book 99 not found"));

        Path file = Files.createTempFile("library", ".csv");
        library.save(file);
        Library reloaded = Library.load(file);
        System.out.println("Saved and reloaded " + reloaded.size() + " books from " + file.getFileName());
        Files.deleteIfExists(file);
    }
}

Walking through it

The Book record validates in its compact constructor, so an invalid book cannot exist. The CSV methods keep the file format in one place. I used a semicolon as the separator, because titles often contain commas. If your data can contain semicolons, you need quoting rules or a CSV library.

Library stores books in a TreeMap, so lookups by id are fast and iteration comes out in id order. putIfAbsent returns the existing value when the key is already there, and we use that to detect duplicates in one step. Loans are tracked in a set of ids, because a book is either on loan or not.

find returns an Optional, because a missing id is a normal outcome. checkout builds on it: orElseThrow turns "not found" into our checked BookUnavailableException. Then onLoan.add(id) returns false if the id was already in the set, which means the book is already out. One line does the check and the update. In main, borrowing book 2 twice and book 42 shows both failure paths.

The reports use streams. available filters by the loan set, and countByGenre groups and counts. The result is a TreeMap keyed by an enum, so the genres come out in the order they are declared.

Saving writes one CSV line per book with Files.write, which uses UTF-8. Loading reads the lines back and builds a new library. The scenario saves to a temporary file, loads it into a second Library, compares the sizes and deletes the file.

Testing and extending

To test Library, move the classes out of Main into their own files in a Maven or Gradle project, and write JUnit 5 tests. Good first tests: adding a duplicate id throws, checking out a book twice fails the second time, a returned book is available again, and save followed by load gives the same books.

Ideas for the next step:

  • Add a Scanner-based menu so that a person can use the program.
  • Put the library behind the HTTP server from the REST lesson, and then rebuild that layer with Spring Boot.

Common mistakes

  • Doing everything in main. Keep rules in classes that you can test.
  • Using a separator that appears in the data. Pick one that does not, or quote.

Try it yourself

  1. Add a method borrowedBooks() and a menu entry that lists books currently on loan.
  2. Write three JUnit tests for Library and run them with Maven.

That is the end of the course. You now have the working knowledge to read and write modern Java. The best next step is a project of your own, one that is small enough to finish.

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {

    enum Genre { FICTION, SCIENCE, HISTORY, TECH }

    record Book(int id, String title, String author, int year, Genre genre) {
        Book {
            if (title == null || title.isBlank()) {
                throw new IllegalArgumentException("title is required");
            }
        }

        String toCsv() {
            return id + ";" + title + ";" + author + ";" + year + ";" + genre;
        }

        static Book fromCsv(String line) {
            String[] p = line.split(";");
            if (p.length != 5) {
                throw new IllegalArgumentException("Bad line: " + line);
            }
            return new Book(Integer.parseInt(p[0]), p[1], p[2], Integer.parseInt(p[3]), Genre.valueOf(p[4]));
        }
    }

    static class BookUnavailableException extends Exception {
        BookUnavailableException(String message) {
            super(message);
        }
    }

    static class Library {
        private final Map<Integer, Book> books = new TreeMap<>();
        private final Set<Integer> onLoan = new HashSet<>();

        void add(Book book) {
            if (books.putIfAbsent(book.id(), book) != null) {
                throw new IllegalArgumentException("Duplicate id " + book.id());
            }
        }

        Optional<Book> find(int id) {
            return Optional.ofNullable(books.get(id));
        }

        List<Book> search(String text) {
            String q = text.toLowerCase();
            return books.values().stream()
                    .filter(b -> b.title().toLowerCase().contains(q) || b.author().toLowerCase().contains(q))
                    .toList();
        }

        void checkout(int id) throws BookUnavailableException {
            Book book = find(id).orElseThrow(() -> new BookUnavailableException("No book with id " + id));
            if (!onLoan.add(id)) {
                throw new BookUnavailableException("'" + book.title() + "' is already on loan");
            }
        }

        List<Book> available() {
            return books.values().stream().filter(b -> !onLoan.contains(b.id())).toList();
        }

        Map<Genre, Long> countByGenre() {
            return books.values().stream()
                    .collect(Collectors.groupingBy(Book::genre, TreeMap::new, Collectors.counting()));
        }

        int size() {
            return books.size();
        }

        void save(Path file) throws IOException {
            Files.write(file, books.values().stream().map(Book::toCsv).toList());
        }

        static Library load(Path file) throws IOException {
            Library library = new Library();
            for (String line : Files.readAllLines(file)) {
                if (!line.isBlank()) {
                    library.add(Book.fromCsv(line));
                }
            }
            return library;
        }
    }

    public static void main(String[] args) throws IOException {
        Library library = new Library();
        library.add(new Book(1, "Clean Code", "Robert C. Martin", 2008, Genre.TECH));
        library.add(new Book(2, "Effective Java", "Joshua Bloch", 2018, Genre.TECH));
        library.add(new Book(3, "A Brief History of Time", "Stephen Hawking", 1988, Genre.SCIENCE));
        library.add(new Book(4, "Midnight's Children", "Salman Rushdie", 1981, Genre.FICTION));
        library.add(new Book(5, "The Silk Roads", "Peter Frankopan", 2015, Genre.HISTORY));

        System.out.println("Books: " + library.size());
        System.out.println("Search 'java': " + library.search("java").stream().map(Book::title).toList());
        System.out.println("By genre: " + library.countByGenre());

        try {
            library.add(new Book(2, "Duplicate", "Nobody", 2000, Genre.FICTION));
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        for (int id : new int[]{2, 2, 42}) {
            try {
                library.checkout(id);
                System.out.println("Checked out book " + id);
            } catch (BookUnavailableException e) {
                System.out.println("Cannot check out: " + e.getMessage());
            }
        }
        System.out.println("Available: " + library.available().stream().map(Book::title).toList());

        System.out.println(library.find(3).map(b -> b.title() + " (" + b.year() + ")").orElse("not found"));
        System.out.println(library.find(99).map(Book::title).orElse("book 99 not found"));

        Path file = Files.createTempFile("library", ".csv");
        library.save(file);
        Library reloaded = Library.load(file);
        System.out.println("Saved and reloaded " + reloaded.size() + " books from " + file.getFileName());
        Files.deleteIfExists(file);
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account