LearnFrenzy
Sign in Take a free test

Project and Next Steps · Lesson 41 of 42

Project: Library Management System

6 min read Updated Nov 7, 2026 Saurabh Samir

Time to put the whole course together. In this project you'll build a console application that manages a small library: add books, register members, issue and return books, and print reports. It uses records, enums, classes with encapsulation, collections, streams, Optional and custom exceptions – exactly the skills interviewers ask about, in one program you can explain end to end.

What you will practise

  • Modelling data with records and enums
  • A service class that owns the business rules
  • Maps for fast lookup, streams for reports
  • Custom exceptions and a validated menu loop

The design

Three layers

  1. Main (console UI)reads choices, prints results, catches LibraryException
  2. Library (service)rules: a book can be issued once, a member has at most 3 books
  3. ModelBook (class with state), Member (record), Genre (enum)

Keeping the UI separate from the rules means you could later replace the console with a Spring Boot REST API without rewriting the Library class – that is the next lesson's goal.

The complete program

Save it as Main.java and run it with java Main.java.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Library lib = new Library();
        lib.addBook("B1", "Clean Code", "Robert C. Martin", Genre.TECH);
        lib.addBook("B2", "Wings of Fire", "A. P. J. Abdul Kalam", Genre.BIOGRAPHY);
        lib.addBook("B3", "Effective Java", "Joshua Bloch", Genre.TECH);
        lib.addMember(new Member("M1", "Asha"));
        lib.addMember(new Member("M2", "Ben"));

        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.print("\n1) List  2) Issue  3) Return  4) Report  5) Exit > ");
            if (!sc.hasNextLine()) break;
            String choice = sc.nextLine().trim();
            try {
                switch (choice) {
                    case "1" -> lib.allBooks().forEach(System.out::println);
                    case "2" -> {
                        System.out.print("Book id: ");
                        String bookId = sc.nextLine().trim();
                        System.out.print("Member id: ");
                        String memberId = sc.nextLine().trim();
                        lib.issue(bookId, memberId);
                        System.out.println("Issued.");
                    }
                    case "3" -> {
                        System.out.print("Book id: ");
                        lib.giveBack(sc.nextLine().trim());
                        System.out.println("Returned.");
                    }
                    case "4" -> lib.report().forEach((genre, count) -> System.out.println(genre + ": " + count + " available"));
                    case "5" -> { System.out.println("Goodbye!"); return; }
                    default -> System.out.println("Choose 1-5.");
                }
            } catch (LibraryException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
}

enum Genre { TECH, BIOGRAPHY, FICTION }

record Member(String id, String name) {}

class Book {
    private final String id, title, author;
    private final Genre genre;
    private String issuedTo;                 // null when available

    Book(String id, String title, String author, Genre genre) {
        this.id = id; this.title = title; this.author = author; this.genre = genre;
    }

    String id() { return id; }
    Genre genre() { return genre; }
    boolean isAvailable() { return issuedTo == null; }
    String issuedTo() { return issuedTo; }
    void issueTo(String memberId) { issuedTo = memberId; }
    void giveBack() { issuedTo = null; }

    @Override
    public String toString() {
        return String.format("%-3s %-16s %-22s %s", id, title, author, isAvailable() ? "available" : "issued to " + issuedTo);
    }
}

class LibraryException extends RuntimeException {
    LibraryException(String message) { super(message); }
}

class Library {
    private static final int MAX_BOOKS_PER_MEMBER = 3;
    private final Map<String, Book> books = new LinkedHashMap<>();
    private final Map<String, Member> members = new LinkedHashMap<>();

    void addBook(String id, String title, String author, Genre genre) {
        if (books.containsKey(id)) throw new LibraryException("Duplicate book id " + id);
        books.put(id, new Book(id, title, author, genre));
    }

    void addMember(Member m) { members.put(m.id(), m); }

    List<Book> allBooks() { return new ArrayList<>(books.values()); }

    private Book book(String id) {
        return Optional.ofNullable(books.get(id)).orElseThrow(() -> new LibraryException("No book with id " + id));
    }

    void issue(String bookId, String memberId) {
        Book b = book(bookId);
        if (!members.containsKey(memberId)) throw new LibraryException("No member with id " + memberId);
        if (!b.isAvailable()) throw new LibraryException(bookId + " is already issued to " + b.issuedTo());
        long held = books.values().stream().filter(x -> memberId.equals(x.issuedTo())).count();
        if (held >= MAX_BOOKS_PER_MEMBER) throw new LibraryException(memberId + " already has " + held + " books");
        b.issueTo(memberId);
    }

    void giveBack(String bookId) {
        Book b = book(bookId);
        if (b.isAvailable()) throw new LibraryException(bookId + " was not issued");
        b.giveBack();
    }

    Map<Genre, Long> report() {
        return books.values().stream().filter(Book::isAvailable)
            .sorted(Comparator.comparing(Book::genre))
            .collect(Collectors.groupingBy(Book::genre, LinkedHashMap::new, Collectors.counting()));
    }
}

A sample session

1) List  2) Issue  3) Return  4) Report  5) Exit > 2
Book id: B1
Member id: M1
Issued.

1) List  2) Issue  3) Return  4) Report  5) Exit > 2
Book id: B1
Member id: M2
Error: B1 is already issued to M1

1) List  2) Issue  3) Return  4) Report  5) Exit > 2
Book id: B9
Member id: M2
Error: No book with id B9

1) List  2) Issue  3) Return  4) Report  5) Exit > 1
B1  Clean Code       Robert C. Martin       issued to M1
B2  Wings of Fire    A. P. J. Abdul Kalam   available
B3  Effective Java   Joshua Bloch           available

1) List  2) Issue  3) Return  4) Report  5) Exit > 4
TECH: 1 available
BIOGRAPHY: 1 available

1) List  2) Issue  3) Return  4) Report  5) Exit > 3
Book id: B1
Returned.

1) List  2) Issue  3) Return  4) Report  5) Exit > 5
Goodbye!

What makes this good code

  • Rules live in one place. The console never changes a book directly; it asks Library, which enforces "issue once" and "max 3 books".
  • Encapsulation. Book's state is private and changes only through issueTo and giveBack.
  • The right types. An enum for genres, a record for members (pure data), a class for books (state that changes).
  • Fast lookups. LinkedHashMap finds a book by id in O(1) and keeps a stable display order.
  • Clear errors. One custom exception type; the UI catches it and shows the message, so bad input never crashes the program.

Extend it yourself

Challenges

  1. Add due dates: when a book is issued, store LocalDate.now().plusDays(14), and add a menu option that lists overdue books.

    Hint

    Add a LocalDate dueDate field to Book, set it in issueTo, clear it in giveBack, and filter with b.dueDate() != null && b.dueDate().isBefore(today).

  2. Save the library to books.csv on exit and load it on start.

    Hint

    Use Files.write(Path.of("books.csv"), lines) with one id,title,author,genre,issuedTo line per book, and Files.readAllLines plus split(",") and Genre.valueOf to load.

  3. Add a search option that finds books whose title contains a word, ignoring case.

    Hint

    books.values().stream().filter(b -> b.title().toLowerCase().contains(word.toLowerCase())).toList() – you'll need a title() getter.

Summary

  • Separate the UI from the service that owns the rules, and the rules from the data model.
  • Choose records, enums and classes deliberately; use maps for lookups and streams for reports.
  • Validate every input and report problems with a custom exception.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links