Skip to content
Tutorials Center
My learning

Topics

Lesson 175 of 201 ยท Projects

Project: Library Management System

Build a Java library system in stages - books, members and loans with records and maps, due dates and fines with java.time, search, reports and text commands.

A library looks simple from the front desk: people borrow books and bring them back. Behind the desk, it's a web of rules. A book can be on loan to only one person. Members have a borrowing limit. Loans have due dates, late returns cost money, renewals are limited, and someone who owes too much can't borrow more. Turning those rules into code that stays correct as features pile up is a great exercise in choosing data structures.

In this project you'll build a library management system in five stages: a catalog of books and members, loans with borrowing rules, due dates and fines with java.time, search and reports, and finally a command interpreter so you can run whole scenarios from the Input box. Every stage is a complete program you can run and modify.

You'll use records, HashMap and LinkedHashMap, ArrayList, dates and times, streams and collectors, Comparator and Optional. As in the other projects, all classes share one file so the editor can run it; in a real project each would get its own file.

The library's rules

  • Every book has a short code (like B101), a title, an author and a year. There's one copy of each code.
  • Members get a numeric ID when they join.
  • A loan lasts 14 days. A member may hold at most 3 books at once.
  • A loan may be renewed once, for 14 days from the renewal date, but only if it isn't overdue yet.
  • Late returns cost $0.25 per day, capped at $10.00 per book.
  • A member who has an overdue book, or owes $5.00 or more, can't borrow until that's sorted out.

Notice that every rule is about one of three things: books, members or loans. That's a strong hint about the classes we'll need.

Stage 1: the catalog and the members

Books and members are plain data: a book's code and title don't change, and neither do a member's ID and name. That makes both of them records. The Library class owns the collections and is the only place that adds to them.

Java Stage 1: books, members and lookups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first big decision is how to store things. We'll constantly look books up by code ("borrow B101") and members by ID, so both live in maps keyed by those values. A List<Book> would work too, but every lookup would scan the whole list; a map finds the entry directly. We choose LinkedHashMap rather than HashMap so that the catalog prints in the order books were added. A plain HashMap would print them in an order that looks random and can change as the map grows.

Other decisions worth noting:

  • putIfAbsent checks and inserts in one step. It adds the book only if the code is new and returns the existing book otherwise, so a non-null result means "duplicate". That's shorter than containsKey followed by put, and it can't get the two steps out of sync.
  • The compact constructor rejects blank fields, so an invalid Book can never exist. Validation inside the record means every code path that creates a book gets it for free; see Records.
  • Lookups throw instead of returning null. "No such book" is something the caller must react to, and a null would only blow up later with a less helpful NullPointerException.
  • join assigns IDs, so callers can't pick a duplicate. It also strips stray spaces from the name: notice that " Leo Brandt " prints as Leo Brandt.

Checked or unchecked, again

In the bank project we made exceptions checked. Here LibraryException extends RuntimeException, so it's unchecked: methods don't declare it and callers aren't forced to catch it. Both choices are legitimate, and seeing both is useful. Unchecked exceptions keep signatures short, which matters as more methods appear; the cost is that the compiler no longer reminds callers. Here, the command loop in Stage 5 catches LibraryException in one place, which is the common pattern for unchecked exceptions.

Stage 2: loans

A loan connects a book to a member. The library needs to answer two questions about loans all the time: "is this book on loan?" (when someone wants to borrow it) and "what does this member have?" (to enforce the limit). The first one is asked for a specific book, so active loans go in a map keyed by book code. The second can be answered by filtering that map's values.

Java Stage 2: borrowing and returning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output reads like a log of a busy morning at the desk: Leo can't take B101 while Maya has it, Maya hits her limit on the fourth book, and returning B104 fails because nobody borrowed it.

Why this design works:

  • One source of truth. Whether a book is available is derived from activeLoans: it's available exactly when it has no entry. We deliberately don't add a boolean onLoan field to Book. Two places storing the same fact can disagree, and the day they do, a book is "available" and "on loan" at the same time. Deriving facts from one structure rules that bug out.
  • Members' loans are computed, not stored. loansOf filters the active loans with a stream. A library has at most a few thousand active loans, so a scan is cheap, and again no second structure can fall out of step. If the library grew to millions of loans, you'd add a Map<Integer, List<Loan>> index and keep both maps updated in the same methods.
  • Records compare by value. loan.member().equals(member) works because Member is a record, so two Member objects with the same ID and name are equal. With a regular class you'd have to write equals yourself, as explained in The Object Class.
  • returnBook uses the result of remove. Map.remove returns the removed value, or null if there was none, so a single call both removes the loan and tells us whether one existed. Before that, findBook(code) makes sure a mistyped code gets the "no book" message rather than a misleading "not on loan".

The tryTo helper in main takes a description and a Runnable, a lambda that performs the action. That keeps the demo free of repeated try/catch blocks; it's a small taste of passing behavior as data, covered in Lambda Expressions.

Stage 3: due dates, renewals and fines

Now time enters the picture. A program that calls LocalDate.now() gives different results every day, which makes it impossible to test "what happens 17 days later?" So the library keeps its own clock: a today field that starts at a fixed date and moves forward only when we say so. This is a standard trick for any program with time-based rules, and it's why the output is the same every time you run it.

Java Stage 3: dates, renewals and fines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Follow the story in the output. Maya borrows on Monday 2 March and her book is due two weeks later. Ten days in, she renews it, which moves the due date to 14 days after the renewal; a second renewal is refused. On day 17, Leo returns his book three days late and pays $0.75. Maya now has an overdue book (B103, due 16 March), so she can't borrow. Sixty days later her fine for B103 has hit the $10.00 cap, and since that's more than $5.00 she's blocked even after returning it.

How java.time does the heavy lifting (see Dates and Times):

  • LocalDate is a date without a time or time zone, exactly what "due on 16 March" means. It's immutable: today.plusDays(14) returns a new date and leaves today alone, which is why we assign the result back in advance.
  • ChronoUnit.DAYS.between(dueOn, today) counts the days from the due date to today. It's negative while the loan isn't due yet, so Math.max(0, ...) turns "not late" into zero. Counting days by hand with month lengths and leap years is a famous source of bugs; never do it.
  • isAfter compares dates. A book due today isn't overdue yet; it becomes overdue tomorrow. Writing !today.isBefore(dueOn) would be off by one day, which is the kind of rule worth deciding (and testing) on purpose.
  • DateTimeFormatter.ofPattern("EEE d MMM yyyy", Locale.US) prints Mon 2 Mar 2026. The formatter is created once as a constant, because formatters are immutable and safe to share. Passing Locale.US fixes the language of day and month names, so the output doesn't change with the server's settings.

Other decisions:

  • Renewing replaces the record. A Loan is immutable, so renewedUntil builds a new loan with the new due date and a higher renewal count, and renew puts it back into the map under the same key. No other code can see a half-updated loan.
  • Fines are whole cents in an int. Fines are only ever multiples of 25 cents and capped at $10, so integer cents are exact and simpler than BigDecimal. money formats them, with %02d keeping the leading zero in $0.75. For arbitrary amounts, interest or currencies, prefer BigDecimal, as in the bank project.
  • unpaidFines.merge(id, fine, Integer::sum) adds the fine to whatever the member already owes, or inserts it if they owe nothing. It's the counting idiom from the HashMap lesson.
  • All policy numbers are named constants. LOAN_DAYS, MAX_FINE_CENTS and the others sit at the top of Library. When the library board changes the fine to 30 cents, you change one line. Magic numbers scattered through methods are how policies end up applied inconsistently.

Stage 4: search and reports

A library system is only as good as its answers. This stage adds three: a case-insensitive search by title or author, an overdue report sorted from most to least late, and a popularity report counting how often each book has been borrowed. It also records every loan ever made in a loanLog, since active loans alone can't tell you what was popular last month.

Java Stage 4: search, overdue list and popular books

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Searching

search lowercases both the query and each title and author before calling contains, so banerjee and SKY both match. toLowerCase(Locale.ROOT) is used instead of plain toLowerCase() because lowercasing depends on the language: on a computer set to Turkish, "TITLE".toLowerCase() produces a dotless ฤฑ, and searches quietly fail. Locale.ROOT gives the same result everywhere; the Internationalization lesson tells the whole story.

Results are sorted by title, so the order is predictable no matter how the catalog was filled.

Optional for "maybe a loan"

loanFor(book) returns an Optional<Loan>: a book either has an active loan or it doesn't, and the return type now says so. availability shows the payoff: map turns a loan into the text "on loan until ...", and orElse supplies "available" when there's no loan, with no null check in sight. borrow uses the same method with isPresent() and get(). The Optional lesson explains when Optional helps (return values like this) and when it doesn't (fields and parameters).

Sorting with comparators

The overdue report sorts by days overdue, descending, and breaks ties by title. Comparators chain exactly like that sentence:

Java
Comparator.comparing((Loan loan) -> loan.daysOverdue(today)).reversed()
        .thenComparing(loan -> loan.book().title())

The explicit (Loan loan) type in the first lambda isn't decoration. When a lambda is followed by .reversed(), Java can't infer its parameter type from the context, and without the type the code doesn't compile. The same issue explains Map.Entry.<Book, Long>comparingByValue() in mostBorrowed: the type arguments are spelled out because .reversed() follows. It's one of the few places where Java's type inference needs help, and you'll meet it in real code; see Sorting with Comparable and Comparator.

Counting with groupingBy

mostBorrowed uses Collectors.groupingBy(Loan::book, Collectors.counting()) to build a Map<Book, Long> from book to number of loans in the log. Records make this work out of the box: groupingBy uses a hash map, which relies on equals and hashCode, and records generate both. The map's entries are then sorted by count (highest first) and title, and limit(3) keeps the top three. Collecting Stream Results covers groupingBy with downstream collectors.

Stage 5: running the library from commands

The final stage replaces the hard-coded main with a command interpreter. Each line of the Input box is a command; the program echoes it after > and prints the result, or a line starting with ! if the library refuses. Lines starting with # are comments, so you can annotate scenarios.

Command Example
add-book CODE | TITLE | AUTHOR | YEAR add-book B101 | The Silent Orchard | Rhea Banerjee | 2019
join NAME join Maya Ortiz
borrow MEMBER CODE borrow 1 B101
return CODE, renew CODE return B101
advance DAYS advance 7
search TEXT, loans MEMBER search rhea
overdue, report report
Java Stage 5: the complete library system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read through the output from top to bottom; it tells a complete story. The duplicate code is rejected, Leo is turned away from B101 and takes B102 instead, Maya renews B101 before it falls due, Leo pays a small fine, and Maya's overdue book blocks her. After 20 more days both of her books are badly late: returning them adds $5.75 and $3.25 to her account, and with $9.00 owed she's blocked from borrowing even with nothing on loan. The mistyped borrow one B104 gets a friendly error instead of a stack trace.

Parsing commands with two separators

Most commands have short arguments separated by spaces, but titles and author names contain spaces themselves. Rather than inventing quoting rules, add-book uses | between fields. line.split("\\s+", 2) splits off only the command word, leaving the rest of the line intact; add-book then splits that rest with the regex \\s*\\|\\s*, which means "a pipe with any spaces around it". join and search take the whole rest of the line as their text, so join Maya Ortiz needs no separators at all.

The | must be escaped as \\| because a bare | means "or" in a regular expression; split("|") would split between every character. See Regular Expressions.

Where the rules live

Look at what execute does not contain: it doesn't check loan limits, dates or fines. It only translates text into method calls and results into text. Every rule lives in Library. That separation means you could replace the command interpreter with a web page or a desktop GUI tomorrow, and not a single library rule would need to move. Keeping user-interface code thin and business rules in one place is the most important architectural habit this project teaches.

number converts text to an int and translates NumberFormatException into a LibraryException, so every user mistake, from bad numbers to unknown codes, arrives at the single catch in main and prints as a ! line.

Edit the Input box and write your own scenarios. Can you make someone renew a book on its due date? (It works, because a book isn't overdue until the day after.) Can you get a member to exactly $5.00 in fines and check that they're blocked?

Ideas to extend it

  • Paying fines. Add pay MEMBER AMOUNT, refusing payments larger than what's owed.
  • Multiple copies. Let a title have several copies by separating a Title record (title, author, year) from Copy records with their own codes, and make search show "2 of 3 available".
  • Holds. Let a member reserve a book that's on loan; keep a queue per book (a Map<String, Deque<Member>>, see Queues and Deques) and refuse renewals while someone is waiting.
  • Closed on Sundays. If a due date falls on a Sunday, move it to Monday with getDayOfWeek() or a TemporalAdjuster.
  • Save and load. Write the catalog to a file in the same | format and read it back at startup, using Files.
  • Faster member lookups. Add a Map<Integer, List<Loan>> index for each member's loans and keep it in sync inside borrow and returnBook. Then think about why the single-source-of-truth design avoided this work until it was needed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the library store active loans in a map keyed by book code instead of adding an onLoan flag to Book?

    With a single source of truth, a book is available exactly when it has no active-loan entry. A separate flag could get out of sync with the loans. (Records are also immutable, which would make a flag awkward, but that's not the main reason.)
  2. 2. A book is due on Mon 16 Mar 2026 and today is Mon 16 Mar 2026. What do isOverdue(today) and daysOverdue(today) return?

    isOverdue uses today.isAfter(dueOn), which is false on the due date itself. DAYS.between gives 0, and Math.max(0, ...) keeps it at 0.
  3. 3. What does "a|b".split("|") return?

    An unescaped | is the regex alternation operator with two empty alternatives, so it matches the empty string between every character and splits the text into single characters. Escape it as \| to split on the pipe.
  4. 4. Why does the program keep its own today field instead of calling LocalDate.now()?

    A controllable clock lets you move time forward on purpose and get the same output on every run, which is essential for testing due dates and fines.
  5. 5. In Comparator.comparing((Loan loan) -> loan.daysOverdue(today)).reversed(), why is the lambda parameter's type written out?

    The target type isn't available to the comparing call when a method is chained after it, so inference falls back to Object. Writing (Loan loan) gives the compiler the type it needs.

Summary

  • Books, members and loans are records; the Library class owns the collections and enforces every rule, so the command interpreter stays thin.
  • Maps keyed by the values you look up (book code, member ID) give fast lookups; LinkedHashMap keeps a predictable order; putIfAbsent, remove, merge and getOrDefault each do a check and an update in one call.
  • Derive facts like availability from a single source of truth instead of storing them twice.
  • LocalDate, plusDays, isAfter and ChronoUnit.DAYS.between handle due dates and fines; a controllable clock makes time-based rules repeatable.
  • Immutable loans are replaced, not modified, when renewed.
  • Streams with Comparator chains, groupingBy and Optional produce search results and reports with very little code; Locale.ROOT keeps case-insensitive search reliable.

Next: Project: Inventory Manager, where you'll parse CSV-style data into records and build stream reports for a small shop.