Skip to content
Java project #07Beginner

Library Catalogue

Add, search, sort, borrow and return books in a catalogue built on a Book class, an ArrayList and Comparators, with validation and statistics.

Estimated time
~3 hours to build
Files
4 files · 336 lines
Technologies
Java 21, ArrayList, Comparator, Optional, Streams

Introduction

A catalogue is the simplest useful database: a list of records you can add to, search, sort and update. This project practises encapsulation (a Book controls its own borrowed state) and shows how Comparators make many sort orders trivial.

Problem statement

Implement a command-driven catalogue. add takes an ISBN in the form 978-0134685991, a title, an author and a year, separated by |, and rejects duplicates, malformed ISBNs and implausible years. Books can be borrowed and returned (refusing to borrow a borrowed book or return one that isn't out). Users can search titles and authors, list books by year range, list the catalogue sorted by title, author or year, and see statistics: counts, the oldest book, the most borrowed book and books per author.

Objectives

  • Encapsulate state changes in a class (borrow / giveBack)
  • Validate data in a constructor
  • Sort with Comparators and search with streams
  • Return Optional for 'may not exist' lookups

Features

  • ISBN, title, author and year validation
  • Borrow/return with state checks and borrow counts
  • Case-insensitive search and year-range queries
  • Three sort orders and catalogue statistics

Concepts demonstrated

  • Encapsulation
  • Constructor validation
  • Comparators
  • Optional
  • Stream filtering

System architecture

Book has private final identity fields and a private borrowed flag that only borrow and giveBack change; its constructor throws IllegalArgumentException for invalid data. The catalogue is a static List<Book>. find(isbn) returns an Optional<Book>. Commands are dispatched with a switch; list chooses a Comparator with a switch expression. Statistics use stream min, max, distinct and count.

Folder structure

TextProject tree
library-catalog/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

142 lines
Javasrc/Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Scanner;
/**
* Library Catalogue — add books, search by title/author/year range, sort the catalogue,
* mark books as borrowed or returned, and print statistics. Uses a Book class with
* encapsulated state, an ArrayList and Comparators.
*
* Commands:
* add ISBN | TITLE | AUTHOR | YEAR borrow ISBN return ISBN
* find TEXT years FROM TO list [title|author|year] stats quit
*/
public class Main {
static class Book {
private final String isbn, title, author;
private final int year;
private boolean borrowed;
private int timesBorrowed;
Book(String isbn, String title, String author, int year) {
if (!isbn.matches("\\d{3}-\\d{10}")) throw new IllegalArgumentException("ISBN must look like 978-0134685991");
if (title.isBlank() || author.isBlank()) throw new IllegalArgumentException("title and author are required");
if (year < 1450 || year > 2026) throw new IllegalArgumentException("year " + year + " is not plausible");
this.isbn = isbn;
this.title = title;
this.author = author;
this.year = year;
}
String isbn() { return isbn; }
String title() { return title; }
String author() { return author; }
int year() { return year; }
boolean isBorrowed() { return borrowed; }
int timesBorrowed() { return timesBorrowed; }
boolean borrow() {
if (borrowed) return false;
borrowed = true;
timesBorrowed++;
return true;
}
boolean giveBack() {
if (!borrowed) return false;
borrowed = false;
return true;
}
@Override public String toString() {
return String.format("%s %-34s %-20s %d %s", isbn, title, author, year, borrowed ? "[out]" : "");
}
}
static final List<Book> catalog = new ArrayList<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("=== Library Catalogue ===");
while (true) {
System.out.print("> ");
if (!in.hasNextLine()) break;
String line = in.nextLine().trim();
System.out.println();
if (line.isEmpty()) continue;
String cmd = line.split("\\s+")[0].toLowerCase(Locale.ROOT);
String rest = line.substring(cmd.length()).trim();
try {
switch (cmd) {
case "add" -> add(rest);
case "borrow", "return" -> {
Book b = find(rest).orElseThrow(() -> new IllegalArgumentException("no book with ISBN " + rest));
boolean ok = cmd.equals("borrow") ? b.borrow() : b.giveBack();
System.out.println(ok ? "\"" + b.title() + "\" " + (cmd.equals("borrow") ? "borrowed" : "returned")
: "\"" + b.title() + "\" is " + (b.isBorrowed() ? "already borrowed" : "not borrowed"));
}
case "find" -> print(catalog.stream().filter(b -> matches(b, rest)).toList());
case "years" -> {
String[] p = rest.split("\\s+");
int from = Integer.parseInt(p[0]), to = Integer.parseInt(p[1]);
print(catalog.stream().filter(b -> b.year() >= from && b.year() <= to).sorted(Comparator.comparingInt(Book::year)).toList());
}
case "list" -> {
Comparator<Book> order = switch (rest.isEmpty() ? "title" : rest) {
case "title" -> Comparator.comparing(Book::title, String.CASE_INSENSITIVE_ORDER);
case "author" -> Comparator.comparing(Book::author).thenComparing(Book::year);
case "year" -> Comparator.comparingInt(Book::year).reversed();
default -> throw new IllegalArgumentException("sort by title, author or year");
};
print(catalog.stream().sorted(order).toList());
}
case "stats" -> stats();
case "quit" -> { return; }
default -> System.out.println("Commands: add, borrow, return, find, years, list, stats, quit");
}
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.out.println("Error: expected numbers, e.g. years 2000 2020");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
static void add(String rest) {
String[] p = rest.split("\\|");
if (p.length != 4) throw new IllegalArgumentException("usage: add ISBN | TITLE | AUTHOR | YEAR");
String isbn = p[0].trim();
if (find(isbn).isPresent()) throw new IllegalArgumentException("ISBN " + isbn + " is already in the catalogue");
Book b = new Book(isbn, p[1].trim(), p[2].trim(), Integer.parseInt(p[3].trim()));
catalog.add(b);
System.out.println("Added \"" + b.title() + "\"");
}
static Optional<Book> find(String isbn) {
return catalog.stream().filter(b -> b.isbn().equals(isbn.trim())).findFirst();
}
static boolean matches(Book b, String text) {
String t = text.toLowerCase(Locale.ROOT);
return b.title().toLowerCase(Locale.ROOT).contains(t) || b.author().toLowerCase(Locale.ROOT).contains(t);
}
static void print(List<Book> books) {
if (books.isEmpty()) System.out.println(" (no books)");
books.forEach(b -> System.out.println(" " + b));
}
static void stats() {
long out = catalog.stream().filter(Book::isBorrowed).count();
System.out.println("Books: " + catalog.size() + ", borrowed now: " + out + ", available: " + (catalog.size() - out));
catalog.stream().min(Comparator.comparingInt(Book::year)).ifPresent(b -> System.out.println("Oldest: " + b.title() + " (" + b.year() + ")"));
catalog.stream().max(Comparator.comparingInt(Book::timesBorrowed)).filter(b -> b.timesBorrowed() > 0)
.ifPresent(b -> System.out.println("Most borrowed: " + b.title() + " (" + b.timesBorrowed() + " times)"));
catalog.stream().map(Book::author).distinct().sorted()
.forEach(a -> System.out.println(" " + a + ": " + catalog.stream().filter(b -> b.author().equals(a)).count() + " book(s)"));
}
}

What each file does

src/Main.java
The Book class, the command loop, add/find/search helpers and statistics.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Library Catalogue ===
>
Added "Effective Java"
>
Added "Head First Java"
>
Added "Java Concurrency in Practice"
>
Added "Clean Code"
>
Added "Design Patterns"
>
Error: ISBN 978-0134685991 is already in the catalogue
>
Error: ISBN must look like 978-0134685991
>
Error: year 2099 is not plausible
>
"Effective Java" borrowed
>
"Effective Java" is already borrowed
>
"Head First Java" is not borrowed
>
"Java Concurrency in Practice" borrowed
>
"Effective Java" returned
>
"Effective Java" borrowed
>
978-0134685991 Effective Java Joshua Bloch 2018 [out]
978-0596009205 Head First Java Kathy Sierra 2005
978-0321349606 Java Concurrency in Practice Brian Goetz 2006 [out]
>
978-0596009205 Head First Java Kathy Sierra 2005
978-0321349606 Java Concurrency in Practice Brian Goetz 2006 [out]
978-0132350884 Clean Code Robert Martin 2008
>
978-0134685991 Effective Java Joshua Bloch 2018 [out]
978-0132350884 Clean Code Robert Martin 2008
978-0321349606 Java Concurrency in Practice Brian Goetz 2006 [out]
978-0596009205 Head First Java Kathy Sierra 2005
978-0201633610 Design Patterns Erich Gamma 1994
>
978-0321349606 Java Concurrency in Practice Brian Goetz 2006 [out]
978-0201633610 Design Patterns Erich Gamma 1994
978-0134685991 Effective Java Joshua Bloch 2018 [out]
978-0596009205 Head First Java Kathy Sierra 2005
978-0132350884 Clean Code Robert Martin 2008
>
Error: sort by title, author or year
>
Books: 5, borrowed now: 2, available: 3
Oldest: Design Patterns (1994)
Most borrowed: Effective Java (2 times)
Brian Goetz: 1 book(s)
Erich Gamma: 1 book(s)
Joshua Bloch: 1 book(s)
Kathy Sierra: 1 book(s)
Robert Martin: 1 book(s)
>
Input
add 978-0134685991 | Effective Java | Joshua Bloch | 2018
add 978-0596009205 | Head First Java | Kathy Sierra | 2005
add 978-0321349606 | Java Concurrency in Practice | Brian Goetz | 2006
add 978-0132350884 | Clean Code | Robert Martin | 2008
add 978-0201633610 | Design Patterns | Erich Gamma | 1994
add 978-0134685991 | Duplicate | Someone | 2020
add 12345 | Bad ISBN | Nobody | 2020
add 978-1111111111 | Future Book | Nobody | 2099
borrow 978-0134685991
borrow 978-0134685991
return 978-0596009205
borrow 978-0321349606
return 978-0134685991
borrow 978-0134685991
find java
years 2000 2010
list year
list author
list price
stats
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • A duplicate ISBN, a short ISBN and the year 2099 are rejected.
  • Borrowing Effective Java twice is refused the second time; after returning, it can be borrowed again (2 times in total).
  • list year shows newest first; list price is reported as an invalid sort order.

Common errors

Search misses 'Java' in 'Head First Java'

Compare lower-cased strings with contains, not equals.

Sorting by title puts lower-case titles last

Use String.CASE_INSENSITIVE_ORDER.

Possible improvements

  • Save the catalogue to a CSV file and load it at start-up
  • Track who borrowed each book and the due date
  • Support several copies of the same title

Additional challenges

  1. 1Add a remove ISBN command that refuses borrowed books.
  2. 2Search by ISBN prefix.
  3. 3Print the catalogue grouped by decade.

Built and tested it yourself? Mark it to update your dashboard.