This project builds the core of a library management system in one Java file. Members borrow and return books, the system enforces the rules (a book can be borrowed by one person at a time, and each member may hold at most two books), late returns are fined per day, and reports list available and overdue books. Along the way it uses records, collections, Optional, custom exceptions, the date API and streams together.
In this project you will
- Model books, members and loans with records and a small class
- Store data in maps and lists chosen for the job
- Enforce business rules with a custom exception
- Calculate due dates and fines with
LocalDate - Produce reports with streams and
groupingBy
This project uses records, HashMap, Optional, exceptions, the date-time API and streams.
The Complete Program
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
// ----- Model -----
record Book(String isbn, String title, String author, String subject) {}
record Member(int id, String name) {}
static final class Loan {
final Book book;
final Member member;
final LocalDate borrowed;
LocalDate returned; // null while still on loan
Loan(Book book, Member member, LocalDate borrowed) {
this.book = book; this.member = member; this.borrowed = borrowed;
}
LocalDate due() { return borrowed.plusDays(14); }
}
static class LibraryException extends RuntimeException {
LibraryException(String message) { super(message); }
}
// ----- Service -----
static class Library {
static final int MAX_BOOKS = 2;
static final int FINE_PER_DAY = 5; // taka per late day
private final Map<String, Book> books = new LinkedHashMap<>();
private final Map<Integer, Member> members = new HashMap<>();
private final List<Loan> loans = new ArrayList<>();
void addBook(Book b) { books.put(b.isbn(), b); }
void addMember(Member m) { members.put(m.id(), m); }
private Optional<Loan> activeLoan(String isbn) {
return loans.stream().filter(l -> l.book.isbn().equals(isbn) && l.returned == null).findFirst();
}
void borrow(int memberId, String isbn, LocalDate day) {
Member m = Optional.ofNullable(members.get(memberId))
.orElseThrow(() -> new LibraryException("No member " + memberId));
Book b = Optional.ofNullable(books.get(isbn))
.orElseThrow(() -> new LibraryException("No book " + isbn));
if (activeLoan(isbn).isPresent())
throw new LibraryException("'" + b.title() + "' is already on loan");
long current = loans.stream().filter(l -> l.member.equals(m) && l.returned == null).count();
if (current >= MAX_BOOKS)
throw new LibraryException(m.name() + " already has " + MAX_BOOKS + " books");
loans.add(new Loan(b, m, day));
System.out.println(day + " " + m.name() + " borrows '" + b.title() + "', due " + day.plusDays(14));
}
int giveBack(String isbn, LocalDate day) {
Loan loan = activeLoan(isbn).orElseThrow(() -> new LibraryException("Book " + isbn + " is not on loan"));
loan.returned = day;
long late = Math.max(0, ChronoUnit.DAYS.between(loan.due(), day));
int fine = (int) late * FINE_PER_DAY;
System.out.println(day + " " + loan.member.name() + " returns '" + loan.book.title() + "'"
+ (late > 0 ? ", " + late + " days late, fine " + fine + " taka" : ", on time"));
return fine;
}
// ----- Reports -----
void report(LocalDate today) {
System.out.println("\nAvailable books:");
books.values().stream()
.filter(b -> activeLoan(b.isbn()).isEmpty())
.forEach(b -> System.out.println(" " + b.title() + " by " + b.author()));
System.out.println("Overdue on " + today + ":");
loans.stream()
.filter(l -> l.returned == null && l.due().isBefore(today))
.forEach(l -> System.out.println(" " + l.book.title() + " (" + l.member.name() + ", due " + l.due() + ")"));
Map<String, Long> bySubject = loans.stream()
.collect(Collectors.groupingBy(l -> l.book.subject(), TreeMap::new, Collectors.counting()));
System.out.println("Loans by subject: " + bySubject);
}
}
public static void main(String[] args) {
Library lib = new Library();
lib.addBook(new Book("111", "Learn Java", "R. Karim", "Programming"));
lib.addBook(new Book("222", "Data Structures", "S. Akter", "Programming"));
lib.addBook(new Book("333", "History of Bengal", "M. Hossain", "History"));
lib.addBook(new Book("444", "Physics Made Easy", "T. Rahman", "Science"));
lib.addMember(new Member(1, "Nusrat"));
lib.addMember(new Member(2, "Arif"));
LocalDate d = LocalDate.of(2026, 3, 1);
lib.borrow(1, "111", d);
lib.borrow(1, "333", d.plusDays(1));
lib.borrow(2, "222", d.plusDays(2));
String[][] badRequests = { {"2", "111"}, {"1", "444"}, {"3", "444"} };
for (String[] r : badRequests) {
try {
lib.borrow(Integer.parseInt(r[0]), r[1], d.plusDays(3));
} catch (LibraryException e) {
System.out.println(" Refused: " + e.getMessage());
}
}
int fines = 0;
fines += lib.giveBack("111", d.plusDays(10));
fines += lib.giveBack("333", d.plusDays(20));
System.out.println("Fines collected: " + fines + " taka");
lib.report(d.plusDays(25));
}
}
Output
2026-03-01 Nusrat borrows 'Learn Java', due 2026-03-15
2026-03-02 Nusrat borrows 'History of Bengal', due 2026-03-16
2026-03-03 Arif borrows 'Data Structures', due 2026-03-17
Refused: 'Learn Java' is already on loan
Refused: Nusrat already has 2 books
Refused: No member 3
2026-03-11 Nusrat returns 'Learn Java', on time
2026-03-21 Nusrat returns 'History of Bengal', 5 days late, fine 25 taka
Fines collected: 25 taka
Available books:
Learn Java by R. Karim
History of Bengal by M. Hossain
Physics Made Easy by T. Rahman
Overdue on 2026-03-26:
Data Structures (Arif, due 2026-03-17)
Loans by subject: {History=1, Programming=2}
How It Works
1. The model
Book and Member are records, because their data never changes. Loan is a small class instead, because its returned date is filled in later. due() calculates the due date (14 days after borrowing) rather than storing it, so it can never disagree with the borrow date.
2. Choosing collections
Books are kept in a LinkedHashMap keyed by ISBN: lookups are fast, and reports list books in the order they were added. Members live in a HashMap keyed by id. Loans form a List, because the history of every loan is kept, including returned ones.
3. Business rules
borrow checks four things in turn: the member exists, the book exists, the book is not already on loan, and the member has fewer than two books. Each failure throws a LibraryException with a clear message. Optional.ofNullable(...).orElseThrow(...) turns a missing map entry into an exception in one line.
The three bad requests in main each break one rule: Arif asks for a book already on loan, Nusrat asks for a third book, and member 3 does not exist. The program catches each exception and prints why the request was refused, then carries on.
4. Dates and fines
ChronoUnit.DAYS.between(due, returnDay) counts the days between the due date and the return date. Math.max(0, ...) turns early returns into 0 late days. Nusrat returns History of Bengal on March 21, five days after its due date of March 16, so she pays 5 × 5 = 25 taka.
5. Reports
- Available books are those with no active loan, found with a stream filter.
- Overdue loans are not yet returned and have a due date before “today” (March 26). Arif’s book was due on March 17.
Collectors.groupingBy(..., TreeMap::new, Collectors.counting())counts all loans, past and present, per subject, sorted by subject name.
Taking It Further
- Add a
Scannermenu so a librarian can type commands (see Scanner input). - Save books, members and loans to CSV files and load them at start-up (see file handling).
- Let a member reserve a book that is on loan, using a queue per book.
- Use
BigDecimalfor fines if the library adds VAT or discounts.
Common Mistakes in Projects Like This
- Storing derived values, such as the due date or “is overdue”, which then go out of date. Calculate them when needed.
- Returning null for “not found” and checking it everywhere.
Optionaland clear exceptions make the rules visible. - Putting all the code in
main. Keep the rules in a service class so they can be tested and reused by a menu, a web page or an app. - Using
LocalDate.now()inside the rules. Passing the date in, as this program does, makes the behaviour easy to test for any day.
Practice Exercises
Exercise 1. Add a method that returns how many books a member currently has on loan.
Show answer
long onLoan(int memberId) {
return loans.stream()
.filter(l -> l.member.id() == memberId && l.returned == null)
.count();
}
Exercise 2. Cap fines at 100 taka per loan.
Show answer
int fine = (int) Math.min(100, late * FINE_PER_DAY);
Frequently Asked Questions
Why is everything in one file?
So that the whole project can be copied and run in one go. In a real project, each record and class would go in its own file inside a package such as library.model and library.service.
How would I store the data in a database?
Create tables for books, members and loans, and use JDBC with prepared statements to read and write them. The service methods stay the same; only the storage code changes.
Summary
- Use records for fixed data and small classes for data that changes.
- Pick collections by how you look data up.
- Enforce rules in one service class with clear exceptions.
- Calculate dates and fines from stored facts; report with streams.
