Java Library System
A Java library system tracks books, members and loans: who borrowed which book, when it is due and how much fine is owed. Unlike the single-class projects before it, it has several classes that work together, plus business rules that can say "no". This makes it an excellent practice project for object-oriented design, the java.time API, custom exceptions and stream reports.
It builds on the Java Student Manager. You model the library with records and an enum, calculate due dates and fines, enforce borrowing rules, and finish with library-system.jar, which replays a month of activity and prints an overdue and popularity report. All examples were run on JDK 21.
Design the Library System Classes
Before writing code, decide what each class is responsible for.
| Class | Type | Responsibility |
|---|---|---|
Book | record | ISBN, title, author of a catalogue entry |
MemberType | enum | Borrowing limits: how many books, for how many days |
Member | record | Id, name and type of a library member |
Loan | class | One book lent to one member; due date and fine |
LibraryException | exception | A library rule blocked the action |
Library | class | Catalogue, shelf copies, members, all loans, the rules |
Book and Member never change, so records fit them. A Loan changes when the book comes back, so it is a normal class with one mutable field.
Model Books and Members With Records and Enums
package com.gocourse.library;
/** A title in the catalogue. Several physical copies can share one ISBN. */
public record Book(String isbn, String title, String author) {
public Book {
if (isbn == null || !isbn.matches("\\d{13}")) {
throw new IllegalArgumentException("ISBN must be 13 digits: " + isbn);
}
if (title == null || title.isBlank()) throw new IllegalArgumentException("title is required");
}
}
package com.gocourse.library;
/** Borrowing rules differ for each kind of member. */
public enum MemberType {
STUDENT(3, 14),
FACULTY(10, 30);
private final int maxBooks;
private final int loanDays;
MemberType(int maxBooks, int loanDays) {
this.maxBooks = maxBooks;
this.loanDays = loanDays;
}
public int maxBooks() { return maxBooks; }
public int loanDays() { return loanDays; }
}
package com.gocourse.library;
public record Member(int id, String name, MemberType type) { }
A quick check of the model:
package com.gocourse.library;
public class ModelDemo {
public static void main(String[] args) {
Book cleanCode = new Book("9780132350884", "Clean Code", "Robert C. Martin");
Member priya = new Member(101, "Priya", MemberType.STUDENT);
Member drRao = new Member(201, "Dr. Rao", MemberType.FACULTY);
System.out.println(cleanCode);
for (Member m : new Member[] {priya, drRao}) {
System.out.printf("%-8s %-8s max %2d books, %2d days%n",
m.name(), m.type(), m.type().maxBooks(), m.type().loanDays());
}
try {
new Book("12345", "Bad Book", "Nobody");
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Book[isbn=9780132350884, title=Clean Code, author=Robert C. Martin]
Priya STUDENT max 3 books, 14 days
Dr. Rao FACULTY max 10 books, 30 days
Rejected: ISBN must be 13 digits: 12345
How it works:
isbn.matches(" 0 d{13}")uses a regular expression to require exactly 13 digits, the modern ISBN length. The invalid book never gets created.- The ISBN is stored as a
String, not along. It is an identifier, not a number you calculate with, and some identifiers start with0. MemberTypekeeps the rules in one place. Changing the student limit to 4 books means editing one line.
Calculate Due Dates and Fines With LocalDate
A loan's due date is the borrow date plus the member's loan days. The fine is a fixed amount for each day after the due date, using the Java LocalDate API.
package com.gocourse.library;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/** One book lent to one member. It stays in the history after it is returned. */
public class Loan {
public static final int FINE_PER_DAY = 5; // rupees per late day
private final Book book;
private final Member member;
private final LocalDate borrowedOn;
private final LocalDate dueOn;
private LocalDate returnedOn; // null while the book is still out
public Loan(Book book, Member member, LocalDate borrowedOn) {
this.book = book;
this.member = member;
this.borrowedOn = borrowedOn;
this.dueOn = borrowedOn.plusDays(member.type().loanDays());
}
public boolean isActive() { return returnedOn == null; }
public boolean isOverdue(LocalDate today) {
return isActive() && today.isAfter(dueOn);
}
/** Late days counted up to the return date, or up to today if still out. */
public long daysLate(LocalDate today) {
LocalDate end = isActive() ? today : returnedOn;
return Math.max(0, ChronoUnit.DAYS.between(dueOn, end));
}
public long fine(LocalDate today) {
return daysLate(today) * FINE_PER_DAY;
}
void markReturned(LocalDate date) {
if (!isActive()) throw new IllegalStateException("Already returned");
returnedOn = date;
}
public Book book() { return book; }
public Member member() { return member; }
public LocalDate borrowedOn() { return borrowedOn; }
public LocalDate dueOn() { return dueOn; }
}
package com.gocourse.library;
import java.time.LocalDate;
public class LoanDemo {
public static void main(String[] args) {
Book book = new Book("9780134685991", "Effective Java", "Joshua Bloch");
Member priya = new Member(101, "Priya", MemberType.STUDENT);
Loan loan = new Loan(book, priya, LocalDate.of(2026, 11, 1));
System.out.println("Borrowed " + loan.borrowedOn() + ", due " + loan.dueOn());
LocalDate[] checkDates = {
LocalDate.of(2026, 11, 10), // before the due date
LocalDate.of(2026, 11, 15), // on the due date
LocalDate.of(2026, 11, 19), // 4 days late
};
for (LocalDate day : checkDates) {
System.out.printf("%s overdue=%-5b late=%d fine=Rs.%d%n",
day, loan.isOverdue(day), loan.daysLate(day), loan.fine(day));
}
loan.markReturned(LocalDate.of(2026, 11, 19));
// after returning, the fine is frozen at the return date
System.out.println("Returned. Fine on 2026-12-31 is still Rs." + loan.fine(LocalDate.of(2026, 12, 31)));
}
}
Borrowed 2026-11-01, due 2026-11-15
2026-11-10 overdue=false late=0 fine=Rs.0
2026-11-15 overdue=false late=0 fine=Rs.0
2026-11-19 overdue=true late=4 fine=Rs.20
Returned. Fine on 2026-12-31 is still Rs.20
How it works:
plusDays(14)handles month lengths and leap years for you. Borrowing on 25 February still gives a correct date in March.ChronoUnit.DAYS.between(dueOn, end)counts whole days. Before the due date it is negative, soMath.max(0, ...)keeps it at zero.- Returning on the due date is not late, because
isAfteris strictly "after". - Once
returnedOnis set,daysLatemeasures up to the return date instead of today, so the fine stops growing. - Every method takes
todayas a parameter instead of callingLocalDate.now(). This makes the results repeatable: the same inputs always give the same fine.
Note:
markReturnedhas nopublicmodifier, so only classes in the same package (theLibrary) can call it. A caller outside the package cannot mark a loan returned without putting the copy back on the shelf.
Enforce Library Rules With a Custom Exception
When a rule blocks an action, the Library throws LibraryException with a message the user can understand. See Java Custom Exceptions for more on designing exception classes.
package com.gocourse.library;
/** Thrown when a library rule blocks an action, such as borrowing a book with no copies left. */
public class LibraryException extends RuntimeException {
public LibraryException(String message) {
super(message);
}
}
package com.gocourse.library;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** The library: catalogue, copies on the shelf, members and every loan ever made. */
public class Library {
private final Map<String, Book> catalogue = new LinkedHashMap<>();
private final Map<String, Integer> copiesOnShelf = new HashMap<>();
private final Map<Integer, Member> members = new HashMap<>();
private final List<Loan> loans = new ArrayList<>();
public void addBook(Book book, int copies) {
catalogue.putIfAbsent(book.isbn(), book);
copiesOnShelf.merge(book.isbn(), copies, Integer::sum); // adds to existing copies
}
public void addMember(Member member) {
members.put(member.id(), member);
}
public Loan borrow(int memberId, String isbn, LocalDate today) {
Member member = findMember(memberId);
Book book = findBook(isbn);
List<Loan> active = activeLoans(member);
if (active.stream().anyMatch(loan -> loan.isOverdue(today))) {
throw new LibraryException(member.name() + " has an overdue book. Return it first.");
}
if (active.size() >= member.type().maxBooks()) {
throw new LibraryException(member.name() + " already has " + active.size()
+ " books (limit " + member.type().maxBooks() + ")");
}
if (active.stream().anyMatch(loan -> loan.book().equals(book))) {
throw new LibraryException(member.name() + " already has '" + book.title() + "'");
}
if (copiesOnShelf.get(isbn) == 0) {
throw new LibraryException("No copies of '" + book.title() + "' on the shelf");
}
copiesOnShelf.merge(isbn, -1, Integer::sum);
Loan loan = new Loan(book, member, today);
loans.add(loan);
return loan;
}
/** Returns the book and gives back the fine in rupees (0 if on time). */
public long returnBook(int memberId, String isbn, LocalDate today) {
Member member = findMember(memberId);
Loan loan = activeLoans(member).stream()
.filter(l -> l.book().isbn().equals(isbn))
.findFirst()
.orElseThrow(() -> new LibraryException(member.name() + " did not borrow " + isbn));
loan.markReturned(today);
copiesOnShelf.merge(isbn, 1, Integer::sum);
return loan.fine(today);
}
public List<Book> search(String text) {
String needle = text.toLowerCase();
return catalogue.values().stream()
.filter(b -> b.title().toLowerCase().contains(needle)
|| b.author().toLowerCase().contains(needle))
.toList();
}
public int available(String isbn) {
return copiesOnShelf.getOrDefault(isbn, 0);
}
public List<Loan> overdueLoans(LocalDate today) {
return loans.stream()
.filter(loan -> loan.isOverdue(today))
.sorted(Comparator.comparing(Loan::dueOn))
.toList();
}
/** How many times each title has been borrowed, most popular first. */
public Map<String, Long> popularity() {
Map<String, Long> counts = loans.stream()
.collect(Collectors.groupingBy(loan -> loan.book().title(), Collectors.counting()));
return counts.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a, b) -> a, LinkedHashMap::new));
}
public List<Loan> activeLoans(Member member) {
return loans.stream().filter(l -> l.isActive() && l.member().equals(member)).toList();
}
public Member findMember(int id) {
Member member = members.get(id);
if (member == null) throw new LibraryException("No member with id " + id);
return member;
}
private Book findBook(String isbn) {
Book book = catalogue.get(isbn);
if (book == null) throw new LibraryException("No book with ISBN " + isbn);
return book;
}
}
How it works:
copiesOnShelf.merge(isbn, -1, Integer::sum)subtracts one copy, andmerge(isbn, 1, ...)adds it back. InaddBook,mergeadds new copies to any that already exist.borrowchecks the rules in order and throws on the first failure: overdue books, the member's limit, a duplicate title, then shelf stock. Nothing changes until all checks pass.- Loans are never deleted. A returned loan stays in
loanswith its return date, so the library keeps a full history for reports such aspopularity(). popularity()counts loans per title withgroupingBy(..., counting()), then sorts by count (highest first) and by title for ties.LinkedHashMap::newkeeps that sorted order in the result.
Test the Borrowing Rules
package com.gocourse.library;
import java.time.LocalDate;
public class BorrowRulesDemo {
static void attempt(String label, Runnable action) {
try {
action.run();
System.out.println("OK " + label);
} catch (LibraryException e) {
System.out.println("NO " + label + " -> " + e.getMessage());
}
}
public static void main(String[] args) {
Library library = new Library();
library.addBook(new Book("9780132350884", "Clean Code", "Robert C. Martin"), 1);
library.addBook(new Book("9780134685991", "Effective Java", "Joshua Bloch"), 2);
library.addBook(new Book("9781617294945", "Spring in Action", "Craig Walls"), 2);
library.addBook(new Book("9780596009205", "Head First Java", "Kathy Sierra"), 2);
library.addMember(new Member(101, "Priya", MemberType.STUDENT));
library.addMember(new Member(102, "Karan", MemberType.STUDENT));
LocalDate day1 = LocalDate.of(2026, 11, 1);
attempt("Priya borrows Clean Code", () -> library.borrow(101, "9780132350884", day1));
attempt("Karan borrows Clean Code", () -> library.borrow(102, "9780132350884", day1));
attempt("Priya borrows Effective Java", () -> library.borrow(101, "9780134685991", day1));
attempt("Priya borrows Effective Java again", () -> library.borrow(101, "9780134685991", day1));
attempt("Priya borrows Spring in Action", () -> library.borrow(101, "9781617294945", day1));
attempt("Priya borrows Head First Java", () -> library.borrow(101, "9780596009205", day1));
attempt("Karan borrows ISBN 9999999999999", () -> library.borrow(102, "9999999999999", day1));
LocalDate day20 = LocalDate.of(2026, 11, 20);
attempt("Priya returns Spring in Action (5 days late)", () -> {
long fine = library.returnBook(101, "9781617294945", day20);
System.out.println(" fine to pay: Rs." + fine);
});
attempt("Priya borrows Head First Java", () -> library.borrow(101, "9780596009205", day20));
System.out.println("Clean Code copies on shelf: " + library.available("9780132350884"));
}
}
OK Priya borrows Clean Code
NO Karan borrows Clean Code -> No copies of 'Clean Code' on the shelf
OK Priya borrows Effective Java
NO Priya borrows Effective Java again -> Priya already has 'Effective Java'
OK Priya borrows Spring in Action
NO Priya borrows Head First Java -> Priya already has 3 books (limit 3)
NO Karan borrows ISBN 9999999999999 -> No book with ISBN 9999999999999
fine to pay: Rs.25
OK Priya returns Spring in Action (5 days late)
NO Priya borrows Head First Java -> Priya has an overdue book. Return it first.
Clean Code copies on shelf: 0
How it works:
attempttakes the action as aRunnablelambda, runs it and printsOKor the rule that blocked it. This keeps the demo short and readable.- The only copy of Clean Code is with Priya, so Karan is refused.
- Priya's fourth book is refused by the
STUDENTlimit of 3. - On 20 November, Priya returns one book 5 days late (
5 x Rs.5 = Rs.25), but she still holds two other books that were due on 15 November. The overdue rule blocks her next loan until she returns them.
Real-World Example: Run a Month in the Java Library System
LibraryApp replays a list of events, like the entries in a library's daily register, and prints an end-of-month report.
package com.gocourse.library;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
/** Replays a month of library activity and prints the end-of-month report. */
public class LibraryApp {
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("dd MMM");
record Event(LocalDate date, String action, int memberId, String isbn) { }
public static void main(String[] args) {
Library library = new Library();
library.addBook(new Book("9780132350884", "Clean Code", "Robert C. Martin"), 2);
library.addBook(new Book("9780134685991", "Effective Java", "Joshua Bloch"), 1);
library.addBook(new Book("9780596009205", "Head First Java", "Kathy Sierra"), 3);
library.addBook(new Book("9781617294945", "Spring in Action", "Craig Walls"), 1);
library.addMember(new Member(101, "Priya", MemberType.STUDENT));
library.addMember(new Member(102, "Karan", MemberType.STUDENT));
library.addMember(new Member(201, "Dr. Rao", MemberType.FACULTY));
List<Event> month = List.of(
new Event(LocalDate.of(2026, 11, 2), "borrow", 101, "9780596009205"),
new Event(LocalDate.of(2026, 11, 2), "borrow", 201, "9780134685991"),
new Event(LocalDate.of(2026, 11, 3), "borrow", 102, "9780134685991"),
new Event(LocalDate.of(2026, 11, 3), "borrow", 102, "9780132350884"),
new Event(LocalDate.of(2026, 11, 5), "borrow", 201, "9781617294945"),
new Event(LocalDate.of(2026, 11, 14), "return", 101, "9780596009205"),
new Event(LocalDate.of(2026, 11, 14), "borrow", 101, "9780132350884"),
new Event(LocalDate.of(2026, 11, 20), "return", 102, "9780132350884"),
new Event(LocalDate.of(2026, 11, 21), "borrow", 102, "9780596009205"),
new Event(LocalDate.of(2026, 11, 22), "borrow", 102, "9780596009205"));
System.out.println("=== November activity ===");
for (Event e : month) {
String who = library.findMember(e.memberId()).name();
String prefix = e.date().format(DAY) + " " + who + " " + e.action() + "s " + e.isbn();
try {
if (e.action().equals("borrow")) {
Loan loan = library.borrow(e.memberId(), e.isbn(), e.date());
System.out.println(prefix + " -> due " + loan.dueOn().format(DAY));
} else {
long fine = library.returnBook(e.memberId(), e.isbn(), e.date());
System.out.println(prefix + (fine > 0 ? " -> fine Rs." + fine : " -> on time"));
}
} catch (LibraryException ex) {
System.out.println(prefix + " -> REFUSED: " + ex.getMessage());
}
}
LocalDate monthEnd = LocalDate.of(2026, 11, 30);
System.out.println("\n=== Overdue on " + monthEnd.format(DAY) + " ===");
long totalFines = 0;
for (Loan loan : library.overdueLoans(monthEnd)) {
System.out.printf("%-8s %-17s due %s %2d days late Rs.%d%n",
loan.member().name(), loan.book().title(), loan.dueOn().format(DAY),
loan.daysLate(monthEnd), loan.fine(monthEnd));
totalFines += loan.fine(monthEnd);
}
System.out.println("Fines owed so far: Rs." + totalFines);
System.out.println("\n=== Most borrowed ===");
library.popularity().forEach((title, count) -> System.out.println(count + " " + title));
System.out.println("\n=== Search 'java' ===");
for (Book b : library.search("java")) {
System.out.printf("%-17s by %-13s %d on shelf%n", b.title(), b.author(), library.available(b.isbn()));
}
}
}
library-system/
└── src/
└── com/
└── gocourse/
└── library/
├── Book.java
├── Library.java
├── LibraryApp.java
├── LibraryException.java
├── Loan.java
├── Member.java
└── MemberType.java
cd library-system
javac -d out src/com/gocourse/library/*.java
jar --create --file library-system.jar --main-class com.gocourse.library.LibraryApp -C out .
java -jar library-system.jar
=== November activity ===
02 Nov Priya borrows 9780596009205 -> due 16 Nov
02 Nov Dr. Rao borrows 9780134685991 -> due 02 Dec
03 Nov Karan borrows 9780134685991 -> REFUSED: No copies of 'Effective Java' on the shelf
03 Nov Karan borrows 9780132350884 -> due 17 Nov
05 Nov Dr. Rao borrows 9781617294945 -> due 05 Dec
14 Nov Priya returns 9780596009205 -> on time
14 Nov Priya borrows 9780132350884 -> due 28 Nov
20 Nov Karan returns 9780132350884 -> fine Rs.15
21 Nov Karan borrows 9780596009205 -> due 05 Dec
22 Nov Karan borrows 9780596009205 -> REFUSED: Karan already has 'Head First Java'
=== Overdue on 30 Nov ===
Priya Clean Code due 28 Nov 2 days late Rs.10
Fines owed so far: Rs.10
=== Most borrowed ===
2 Clean Code
2 Head First Java
1 Effective Java
1 Spring in Action
=== Search 'java' ===
Effective Java by Joshua Bloch 0 on shelf
Head First Java by Kathy Sierra 2 on shelf
How it works:
- Different rules per member. Dr. Rao is
FACULTY, so his loans are due after 30 days (2 December), while students get 14 days. - Shared stock. There is one copy of Effective Java. Once Dr. Rao borrowed it, Karan was refused the next day.
- Fines on return. Karan returned Clean Code on 20 November, 3 days after its 17 November due date, and paid
3 x Rs.5 = Rs.15. Because he returned it, he was allowed to borrow again on 21 November. - Overdue report. On 30 November, only Priya's copy of Clean Code (due 28 November) is overdue. Karan's fine was already settled at return, so the report lists only fines still growing.
- History-based reports. Clean Code and Head First Java were each borrowed twice. They tie on count, so they are ordered alphabetically.
- Readable dates.
DateTimeFormatter.ofPattern("dd MMM")prints02 Novinstead of2026-11-02, as covered in Java Date Formatting.
The next project, the Java Bank App, applies the same rule-checking approach to money, where exact decimal arithmetic and safe concurrent updates matter.