These are the notes for Low-Level Design (LLD) episode 77: designing a hotel booking system in Java. We start from the hotel booking requirements, build Hotel, Room, RoomType, Guest and Reservation, make the classic mistake in the date-range overlap check for real (two guests in one room on one night), fix it with a one-line rule, add search by date and type, prove overbooking prevention with a 20-thread test, speed the free-room check up with a TreeMap availability calendar, and finish with booking states, a cancellation policy and invoices.
How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. The hotel, the guests (Asha, Ravi, Neha, Amit), the room numbers, the rates (4000 and 9000 rupees a night), the 10% tax and the cancellation policy are all made up for teaching. Nothing here describes any real hotel or booking website.
Earlier episodes this one builds on: the state machine (episode 37) and the movie seat holds, locks and races (episodes 74 and 75). A hotel room is like a cinema seat with one big difference: a seat is booked for one show, a room is booked for a range of dates.
1. The problem: the front desk register
| Real life | In the design |
|---|---|
| The register: one line per stay, "Room 101: Asha, 10th to 13th" | A Reservation (guest + room + check-in + check-out) |
| The hotel's rooms, each with a number, a kind and a price | Hotel has many Rooms; each Room has a RoomType and a rate |
| The person whose name is on the line | A Guest (name, phone) |
| "Any deluxe room for the 8th to the 15th?" | Search by date and type |
| The clerk runs a finger down the register | The date-range overlap check |
| Two families arrive at room 101 on the same night | Overbooking: the bug we must never have |
| The desk screen: rooms down the side, nights across the top | An availability calendar |
| "Booked", "in the room", "left", "cancelled", "never came" | Booking states |
| "Free cancellation until 2 days before" | A cancellation policy |
| The bill at checkout: nights, room service, tax | An invoice |
2. Hotel booking requirements and the words
The hotel booking requirements are the list of what the system must do. In an interview, say them out loud before drawing any class:
- A guest searches for free rooms by dates (check-in, check-out) and room type.
- The guest books one room; the system gives a reservation id.
- The guest may cancel; a cancellation policy decides the fee.
- The guest checks in, later checks out, and gets an invoice.
- A guest who never arrives is marked a no-show.
- Never give one room to two guests on the same night, even when many people book at the same moment (overbooking prevention).
Out of scope for this episode (say so in the interview): payments (episode 75 did a payment flow), reviews, loyalty points, many hotels in many cities, prices that change by season (see the follow-ups).
The core classes:
- Hotel: owns the rooms and the reservations. Example: a small hotel with rooms 101 and 102.
- Room: one room you can sleep in, with a number, a type and a rate per night. Example:
Room(101, DELUXE, 4000). - RoomType: an enum (a fixed list of named values) of the kinds of room:
STANDARD, DELUXE, SUITE. Using an enum instead of a string means a typo like"DELUX"can't compile. - Guest: the person staying: a name and a phone number. Example:
Guest("Asha", "98xxxxxx01"). - Reservation: one stay: a guest, a room, a check-in date and a check-out date. Example: Asha, room 101, 10 Dec to 13 Dec.
One rule decides everything that follows:
Dates are [check-in, check-out): the check-in day counts, the check-out day does not. Asha's stay 10 Dec to 13 Dec means the nights of the 10th, 11th and 12th (3 nights). She leaves on the morning of the 13th, so someone else can arrive that afternoon.
That square bracket [ means "included" and the round bracket ) means "not included". This style of range is called a half-open interval. With it, the number of nights is simply check-out − check-in (13 − 10 = 3).
Dates in Java: java.time.LocalDate is a date without a time (no hours, no time zone): LocalDate.of(2026, 12, 10) or LocalDate.parse("2026-12-10"). You compare two dates with isBefore, isAfter and isEqual (not < or ==, see the common mistakes), and move them with plusDays and minusDays.
3. Attempt 1: check only the new check-in day
The obvious check: "Is the new guest's check-in day inside someone else's stay?" If not, the room is free.
import java.time.LocalDate; import java.util.*;
record Stay(String guest, LocalDate in, LocalDate out) {} // check-in day, check-out day
public class Main {
static List<Stay> room101 = new ArrayList<>();
static boolean free(LocalDate in, LocalDate out) { // attempt: does the new check-in
for (Stay s : room101) // fall inside an existing stay?
if (!in.isBefore(s.in()) && in.isBefore(s.out())) return false;
return true; }
static void book(String guest, String from, String to) {
LocalDate in = LocalDate.parse(from), out = LocalDate.parse(to);
if (!free(in, out)) { System.out.println(guest + ": sorry, room 101 is taken"); return; }
room101.add(new Stay(guest, in, out));
System.out.println(guest + ": booked room 101, " + from + " to " + to); }
public static void main(String[] args) {
book("Asha", "2026-12-10", "2026-12-13");
book("Ravi", "2026-12-11", "2026-12-12"); // inside Asha's stay
book("Neha", "2026-12-08", "2026-12-15"); // starts BEFORE Asha, ends after
book("Amit", "2026-12-13", "2026-12-14"); // Asha checks out that morning
LocalDate night = LocalDate.parse("2026-12-11");
System.out.println("Night of " + night + ", room 101 has: " + room101.stream()
.filter(s -> !night.isBefore(s.in()) && night.isBefore(s.out())).map(Stay::guest).toList()); } }
Real output:
Asha: booked room 101, 2026-12-10 to 2026-12-13
Ravi: sorry, room 101 is taken
Neha: booked room 101, 2026-12-08 to 2026-12-15
Amit: sorry, room 101 is taken
Night of 2026-12-11, room 101 has: [Asha, Neha]
What happened, line by line:
- Asha books 10th to 13th: the room is empty, booked.
- Ravi wants 11th to 12th. His check-in (11th) is inside Asha's stay, so he's refused. Correct.
- Neha wants 8th to 15th. Her check-in (8th) is before Asha's stay starts, so it isn't "inside" it. The check passes and Neha is booked on top of Asha.
- Amit wants 13th to 14th. Asha has left by then, so he should get the room, but his 13th is inside Neha's wrong booking, so he's refused.
- On the night of the 11th, room 101 has
[Asha, Neha]: two families, one room. That is overbooking.
Why it failed
Two stays can touch in four ways. Draw the old stay (Asha, 10 to 13) as a bar and slide a new bar around it:
old (Asha): [10 ======== 13)
1. new inside: [11 = 12) Ravi -> overlaps
2. new covers old: [8 ==================== 15) Neha -> overlaps (start is OUTSIDE)
3. new hits the left: [9 ===== 11) overlaps
4. new hits the right: [12 ====== 14) overlaps
5. new starts at check-out: [13 = 14) Amit -> NO overlap
Attempt 1 only looks at the new start. Case 2 (and case 3) have the new start outside the old stay, so they slip through. Checking "start inside OR end inside" still misses case 2, because both of Neha's ends are outside Asha's stay.
4. The fix: the date-range overlap check
Two half-open ranges [aIn, aOut) and [bIn, bOut) overlap if and only if each one starts before the other one ends:
overlap = aIn < bOut && bIn < aOut
In Java, with LocalDate: aIn.isBefore(bOut) && bIn.isBefore(aOut).
Why it is right: two ranges do not overlap only when one ends before (or exactly when) the other starts: aOut <= bIn or bOut <= aIn. Flip that ("not this or that" = "not this and not that") and you get aOut > bIn && bOut > aIn, which is the same rule.
Try it on every case above (old = Asha, [10, 13)):
| New stay | newIn < oldOut? | oldIn < newOut? | Overlap? |
|---|---|---|---|
| Ravi 11-12 | 11 < 13 yes | 10 < 12 yes | yes |
| Neha 8-15 | 8 < 13 yes | 10 < 15 yes | yes (attempt 1 missed it) |
| 9-11 | 9 < 13 yes | 10 < 11 yes | yes |
| 12-14 | 12 < 13 yes | 10 < 14 yes | yes |
| Amit 13-14 | 13 < 13 no | 10 < 14 yes | no: free |
| 5-10 | 5 < 13 yes | 10 < 10 no | no: free |
Strictly less-than is what makes the check-out day free. Use <= and Amit is refused on the morning Asha leaves (see the common mistakes, with a real run).
5. Hotel, rooms, search by date and type, and overbooking prevention
Now the real classes. A Reservation gets an overlaps method holding the one-liner. The Hotel has:
isFree(room, in, out): no booking of that room overlaps the new dates.search(type, in, out): search by date and type: every room of that type that is free for those dates.book(...): check, then add, markedsynchronized.
Overbooking prevention: if two people book the same room at the same moment, each runs on its own thread (one line of work running inside the program). Without a lock, both can run isFree, both see "free", and both add a booking: a race condition (episode 75). The keyword synchronized on a method means only one thread at a time may run it on that object; the others wait. So "check, then add" becomes one step nobody can cut into.
import java.time.LocalDate; import java.util.*; import java.util.concurrent.*;
enum RoomType { STANDARD, DELUXE, SUITE } record Room(int number, RoomType type, int ratePerNight) {}
record Reservation(String id, String guest, Room room, LocalDate in, LocalDate out) {
boolean overlaps(LocalDate a, LocalDate b) { return a.isBefore(out) && in.isBefore(b); } } // [in,out)
class Hotel {
final List<Room> rooms = new ArrayList<>();
final List<Reservation> bookings = new ArrayList<>();
boolean isFree(Room r, LocalDate in, LocalDate out) {
return bookings.stream().noneMatch(b -> b.room() == r && b.overlaps(in, out)); }
List<Integer> search(RoomType t, LocalDate in, LocalDate out) { // search by date and type
return rooms.stream().filter(r -> r.type() == t && isFree(r, in, out)).map(Room::number).toList(); }
synchronized Reservation book(String guest, Room r, LocalDate in, LocalDate out) { // check + add: one step
if (!out.isAfter(in)) throw new IllegalArgumentException("check-out must be after check-in");
if (!isFree(r, in, out))
throw new IllegalStateException("room " + r.number() + " is taken " + in + " to " + out);
Reservation res = new Reservation("R" + (bookings.size() + 1), guest, r, in, out);
bookings.add(res); return res; } }
public class Main { public static void main(String[] args) throws Exception {
Hotel h = new Hotel(); LocalDate d10 = LocalDate.of(2026, 12, 10);
for (int n : new int[]{101, 102}) h.rooms.add(new Room(n, RoomType.DELUXE, 4000));
Room r101 = h.rooms.get(0); h.book("Asha", r101, d10, d10.plusDays(3));
System.out.println("DELUXE free 8th-15th: " + h.search(RoomType.DELUXE, d10.minusDays(2), d10.plusDays(5)));
System.out.println("DELUXE free 13th-14th: " + h.search(RoomType.DELUXE, d10.plusDays(3), d10.plusDays(4)));
ExecutorService pool = Executors.newFixedThreadPool(20); List<Future<?>> tries = new ArrayList<>();
for (int i = 0; i < 20; i++) // overbooking test: 20 threads, 1 room
tries.add(pool.submit(() -> h.book("guest", h.rooms.get(1), d10, d10.plusDays(1))));
int ok = 0; for (Future<?> f : tries) try { f.get(); ok++; } catch (ExecutionException e) {}
pool.shutdown(); System.out.println("20 guests tap room 102 at once -> bookings made: " + ok);
h.book("Neha", r101, d10.minusDays(2), d10.plusDays(5)); } }
Real output:
DELUXE free 8th-15th: [102]
DELUXE free 13th-14th: [101, 102]
20 guests tap room 102 at once -> bookings made: 1
Exception in thread "main" java.lang.IllegalStateException: room 101 is taken 2026-12-08 to 2026-12-15
at Hotel.book(Main.java:15)
at Main.main(Main.java:29)
DELUXE free 8th-15th: [102]: room 101 has Asha (10-13), which overlaps; 102 is empty.DELUXE free 13th-14th: [101, 102]: Asha checks out on the 13th, so 101 is free again that night.- 20 threads try to book room 102 for the night of the 10th at the same moment: exactly 1 booking. The other 19 get an
IllegalStateExceptioninside theirFuture, whichf.get()rethrows as anExecutionException(caught and not counted). - Neha's 8-15 on room 101 is refused with a clear message:
room 101 is taken 2026-12-08 to 2026-12-15. It is thrown frommainand not caught, so the program stops there with the stack trace. An IllegalStateException is Java's exception for "this call is not allowed in the current state" (here: the room is already taken). bookalso refuses impossible dates first:if (!out.isAfter(in))throws an IllegalArgumentException ("this argument is wrong") withcheck-out must be after check-in. A zero-night stay is refused too.
What happens without synchronized? Here is the same 20-thread test with the lock removed, a CountDownLatch to release all 20 threads at the same moment, and a Thread.yield() (a hint to let another thread run) between the check and the add to make the gap easy to hit:
import java.time.LocalDate; import java.util.*; import java.util.concurrent.*;
record Reservation(String guest, int room, LocalDate in, LocalDate out) {
boolean overlaps(LocalDate a, LocalDate b) { return a.isBefore(out) && in.isBefore(b); } }
class Hotel {
final List<Reservation> bookings = Collections.synchronizedList(new ArrayList<>());
boolean book(String guest, int room, LocalDate in, LocalDate out) { // NOT synchronized
boolean free = bookings.stream().noneMatch(b -> b.room() == room && b.overlaps(in, out));
if (!free) return false;
Thread.yield(); // a tiny gap between check and add
bookings.add(new Reservation(guest, room, in, out)); return true; } }
public class Main { public static void main(String[] args) throws Exception {
LocalDate d = LocalDate.of(2026, 12, 10);
Hotel h = new Hotel(); ExecutorService pool = Executors.newFixedThreadPool(20);
CountDownLatch go = new CountDownLatch(1); List<Future<Boolean>> tries = new ArrayList<>();
for (int i = 0; i < 20; i++) { String g = "guest" + i;
tries.add(pool.submit(() -> { go.await(); return h.book(g, 102, d, d.plusDays(1)); })); }
go.countDown(); int ok = 0; for (Future<Boolean> f : tries) if (f.get()) ok++;
pool.shutdown();
System.out.println("20 guests tap room 102 at once -> bookings made: " + ok); } }
Real output (one run):
20 guests tap room 102 at once -> bookings made: 7
Seven guests now hold room 102 for the same night. The number changes from run to run (other runs on the same machine printed 3, 5 and 6), because it depends on how the threads happen to be scheduled. It is never safe. Put back synchronized and it is always 1.
One caution about the episode program: search is not synchronized, and it reads the ArrayList that book writes. In the demo all searches run before the threads start, so it's fine; in a real service, reads must also be protected (the mini project synchronizes search too) or use a thread-safe structure.
6. Next problem: a big hotel is slow
isFree scans every booking in the hotel, every time. A 500-room hotel with two years of bookings has a long list, and search calls isFree once per room. The cost grows with the number of bookings: O(n) per room checked, where n is the number of bookings.
The fix: an availability calendar per room
An availability calendar is, for each room, the list of its stays sorted by date, so you can answer "is this room free on these dates?" and "who sleeps here on the night of the 11th?" quickly.
Java's TreeMap is a map that keeps its keys sorted (it is a red-black tree inside). Because it is sorted, it can find neighbours of a key quickly, in O(log n) time (for 1000 bookings, about 10 steps instead of 1000):
| Method | Returns | Used for |
|---|---|---|
lowerEntry(k) |
the entry with the greatest key strictly less than k |
"the last stay that starts before I leave" |
floorEntry(k) |
the entry with the greatest key less than or equal to k |
"the stay that started on or before this night" |
Key each room's calendar by check-in date. To check a new stay [in, out):
- Stays that start on or after
outcan't overlap (they start after you've left). - Among stays that start before
out, take the last one:lowerEntry(out). - Stays in one room never overlap each other, so when sorted by check-in they are also sorted by check-out. That last stay ends latest of all of them. If it ends by your check-in (
!last.out().isAfter(in)), every earlier one does too: the room is free.
One lookup instead of a scan.
import java.time.LocalDate; import java.util.*;
record Booking(String guest, LocalDate in, LocalDate out) {}
class RoomCalendar { // the availability calendar of ONE room
final TreeMap<LocalDate, Booking> byCheckIn = new TreeMap<>(); // sorted by check-in date
boolean isFree(LocalDate in, LocalDate out) {
Map.Entry<LocalDate, Booking> last = byCheckIn.lowerEntry(out); // last stay starting before 'out'
return last == null || !last.getValue().out().isAfter(in); } // ...must end by 'in'
boolean book(String guest, LocalDate in, LocalDate out) {
if (!isFree(in, out)) return false;
byCheckIn.put(in, new Booking(guest, in, out)); return true; }
String guestOn(LocalDate night) { // who sleeps here that night?
Map.Entry<LocalDate, Booking> e = byCheckIn.floorEntry(night);
return e != null && e.getValue().out().isAfter(night) ? e.getValue().guest() : null; } }
public class Main { public static void main(String[] args) {
Map<Integer, RoomCalendar> cal = new TreeMap<>(Map.of(101, new RoomCalendar(), 102, new RoomCalendar()));
LocalDate d = LocalDate.of(2026, 12, 10);
System.out.println("Asha 101 10-13: " + cal.get(101).book("Asha", d, d.plusDays(3)));
System.out.println("Neha 101 8-15: " + cal.get(101).book("Neha", d.minusDays(2), d.plusDays(5)));
System.out.println("Amit 101 13-14: " + cal.get(101).book("Amit", d.plusDays(3), d.plusDays(4)));
System.out.println("Ravi 102 11-15: " + cal.get(102).book("Ravi", d.plusDays(1), d.plusDays(5)));
System.out.print("night ");
for (int i = 0; i < 7; i++) System.out.print(d.plusDays(i).getDayOfMonth() + " ");
cal.forEach((room, c) -> {
System.out.print("\nroom " + room + " ");
for (int i = 0; i < 7; i++) { String g = c.guestOn(d.plusDays(i));
System.out.print((g == null ? "--" : g.substring(0, 2)) + " "); } });
System.out.println(); } }
Real output:
Asha 101 10-13: true
Neha 101 8-15: false
Amit 101 13-14: true
Ravi 102 11-15: true
night 10 11 12 13 14 15 16
room 101 As As As Am -- -- --
room 102 -- Ra Ra Ra Ra -- --
Asha true,Neha false(the stay starting before the 15th is Asha's, ending the 13th, which is after Neha's check-in, the 8th),Amit true(lowerEntry(14th)is Asha's stay, ending the 13th, which is not after Amit's 13th),Ravi trueon room 102.- The grid is the calendar a front desk screen shows: one row per room, one column per night. Room 101: Asha for 10, 11, 12, then Amit on the 13th (the day Asha leaves). Room 102: Ravi for the nights of the 11th to the 14th (he checks out on the 15th).
guestOn(night)usesfloorEntry(night): the stay that started on or before that night, if it hasn't ended yet (out().isAfter(night)).calis aTreeMap<Integer, RoomCalendar>too, soforEachprints rooms in number order. (Map.ofalone has no fixed order.)- Each printed cell ends in three spaces, so each line of the grid ends in spaces; that is the program's real output.
7. Booking states, the cancellation policy and invoices
A reservation goes through booking states:
RESERVED ──checkIn──▶ CHECKED_IN ──checkOut──▶ CHECKED_OUT (+ invoice)
├──cancel──▶ CANCELLED (fee by the cancellation policy)
└──guest never arrives──▶ NO_SHOW
Only some moves make sense, so we write it as a state machine (episode 37): a set of states plus the only legal moves (transitions) between them. A cancelled stay can never check in; a checked-out stay can never be cancelled. If the state were a free-form string, nothing would stop "CANCELLED" from becoming "CHECKED_IN".
A cancellation policy is the hotel's rule for what you pay if you cancel. Ours, made up for this example: cancel 2 or more days before check-in and it's free; later than that, you pay one night. ChronoUnit.DAYS.between(a, b) counts the days from date a to date b.
An invoice is the bill at check-out: nights × rate + extras + tax. Extras are things like room service. Our tax is a made-up flat 10%, computed with whole-number division (it rounds down).
import java.time.LocalDate; import static java.time.temporal.ChronoUnit.DAYS;
enum State { RESERVED, CHECKED_IN, CHECKED_OUT, CANCELLED, NO_SHOW }
record Guest(String name, String phone) {}
class Reservation {
final String id; final Guest guest; final int rate; final LocalDate in, out;
State state = State.RESERVED;
Reservation(String id, Guest g, int rate, LocalDate in, LocalDate out) {
this.id = id; guest = g; this.rate = rate; this.in = in; this.out = out; }
void move(State from, State to) { // only the allowed moves
if (state != from) throw new IllegalStateException(id + ": cannot go " + state + " -> " + to);
state = to; }
void checkIn() { move(State.RESERVED, State.CHECKED_IN); }
int cancel(LocalDate today) { // cancellation policy
move(State.RESERVED, State.CANCELLED);
return DAYS.between(today, in) >= 2 ? 0 : rate; } // free until 2 days before, else 1 night
String checkOut(int extras) { // the invoice
move(State.CHECKED_IN, State.CHECKED_OUT);
long nights = DAYS.between(in, out), room = nights * rate, tax = (room + extras) / 10; // made-up 10%
return "Invoice " + id + " for " + guest.name() + ": " + nights + " nights x " + rate + " = " + room
+ ", extras " + extras + ", tax " + tax + ", total " + (room + extras + tax); } }
public class Main { public static void main(String[] args) {
LocalDate d = LocalDate.of(2026, 12, 10);
Reservation r1 = new Reservation("R1", new Guest("Asha", "98xxxxxx01"), 4000, d, d.plusDays(3));
Reservation r2 = new Reservation("R2", new Guest("Ravi", "98xxxxxx02"), 4000, d, d.plusDays(2));
Reservation r3 = new Reservation("R3", new Guest("Neha", "98xxxxxx03"), 4000, d, d.plusDays(2));
r1.checkIn(); System.out.println(r1.checkOut(850)); // 850 rupees of room service
System.out.println("R2 cancels on Dec 5, fee: " + r2.cancel(d.minusDays(5)));
System.out.println("R3 cancels on Dec 9, fee: " + r3.cancel(d.minusDays(1)));
r3.checkIn(); } }
Real output:
Invoice R1 for Asha: 3 nights x 4000 = 12000, extras 850, tax 1285, total 14135
R2 cancels on Dec 5, fee: 0
R3 cancels on Dec 9, fee: 4000
Exception in thread "main" java.lang.IllegalStateException: R3: cannot go CANCELLED -> CHECKED_IN
at Reservation.move(Main.java:10)
at Reservation.checkIn(Main.java:12)
at Main.main(Main.java:29)
- Asha: 3 nights × 4000 = 12000, extras 850, tax (12000 + 850) / 10 = 1285, total 14135.
- Ravi cancels on Dec 5 for a Dec 10 check-in:
DAYS.betweenis 5, at least 2, so the fee is 0. - Neha cancels on Dec 9: 1 day before, so the fee is one night, 4000.
- Neha's cancelled reservation then tries
checkIn():move(RESERVED, CHECKED_IN)sees the state isCANCELLED, notRESERVED, and throwsR3: cannot go CANCELLED -> CHECKED_IN. movechecks before it changes anything, so a refused move leaves the reservation exactly as it was.- Guest is a record: a short Java class whose fields are fixed at creation, with the constructor, getters (
name()),equalsandtoStringwritten for you.
8. The class diagram
Hotel ─ has many ─▶ Room(number, RoomType, ratePerNight) RoomType: STANDARD · DELUXE · SUITE
Hotel.search(type, in, out) → free rooms Hotel.book(...) synchronized: check + add in one step
Reservation(id, Guest, Room, in, out) dates are [check-in, check-out): check-out day is free
overlap: a.in < b.out && b.in < a.out
RoomCalendar: TreeMap<check-in, Booking> → lowerEntry(out) → O(log n) free check
State: RESERVED ─checkIn─▶ CHECKED_IN ─checkOut─▶ CHECKED_OUT (+ invoice)
RESERVED ─cancel─▶ CANCELLED (fee by policy) · RESERVED ─no arrival─▶ NO_SHOW
Reading it: a Hotel has many Rooms; a Reservation joins one Guest to one Room for a date range; each room has one RoomCalendar; each reservation has one State. Relationships worth naming in an interview:
- Hotel → Room: composition (the rooms belong to the hotel).
- Reservation → Guest and Reservation → Room: association (the reservation points at them; the guest exists without it).
searchandbooklive in the Hotel (or aHotelService), not in Room, because they look at many rooms at once.
9. Interview follow-ups
| Question | Answer |
|---|---|
| Many servers behind a load balancer? | synchronized protects one JVM only. The database must refuse overlapping rows: lock the room's row while booking (SELECT ... FOR UPDATE), or store one row per room per night with a unique constraint on (room, night), so a second insert for the same night fails. |
| Book two rooms together (a family)? | All or nothing: check both under one lock, then add both; if either is taken, add neither. |
| Prices change by date (weekends, festivals)? | A PricingStrategy that prices each night separately and adds them up (practice question 3). |
| Pay later? | Hold the room with an expiry time, like the seat holds in episode 75; a job releases holds that expire unpaid. |
| No-shows? | A nightly job marks RESERVED stays whose check-in day has passed as NO_SHOW, charges by policy and frees the room (mini project). |
| "Any room of this type", not a specific room? | Search by type, then book the first free room of that type inside the same synchronized step (mini project). |
10. Common mistakes
| Mistake | What you see (real) | Fix |
|---|---|---|
| Only check whether the new start is inside a stay | Night of 2026-12-11, room 101 has: [Asha, Neha] |
aIn < bOut && bIn < aOut |
<= instead of < in the overlap check |
Amit 13-14 clashes with Asha 10-13? true |
Strict < with [in, out): with strict <: false |
| Check, then add, without a lock | 20 guests tap room 102 at once -> bookings made: 7 |
synchronized book: bookings made: 1 |
Comparing dates with < |
error: bad operand types for binary operator '<' |
in.isBefore(out) |
Comparing dates with == |
a == b ? false for two LocalDates of 2026-12-13 |
a.equals(b) or a.isEqual(b): true |
| Writing a date without leading zeros | DateTimeParseException: Text '2026-12-8' could not be parsed at index 8 |
"2026-12-08", or LocalDate.of(2026, 12, 8) |
| Scanning every booking for every room | search gets slower as bookings pile up | A TreeMap calendar per room, lowerEntry(out) |
| State as a free-form string | a cancelled stay checks in | A state machine: R3: cannot go CANCELLED -> CHECKED_IN |
| Allowing check-out on or before check-in | a 0-night or negative stay | check-out must be after check-in |
The programs behind the new rows (the others are in the sections above):
import java.time.LocalDate;
public class Main {
// WRONG: <= on both sides, so touching stays count as an overlap
static boolean overlaps(LocalDate aIn, LocalDate aOut, LocalDate bIn, LocalDate bOut) {
return !aIn.isAfter(bOut) && !bIn.isAfter(aOut); }
public static void main(String[] args) {
LocalDate ashaIn = LocalDate.parse("2026-12-10"), ashaOut = LocalDate.parse("2026-12-13");
LocalDate amitIn = LocalDate.parse("2026-12-13"), amitOut = LocalDate.parse("2026-12-14");
System.out.println("Amit 13-14 clashes with Asha 10-13? " + overlaps(amitIn, amitOut, ashaIn, ashaOut));
System.out.println("with strict <: " + (amitIn.isBefore(ashaOut) && ashaIn.isBefore(amitOut)));
} }
Amit 13-14 clashes with Asha 10-13? true
with strict <: false
import java.time.LocalDate;
public class Main { public static void main(String[] args) {
LocalDate in = LocalDate.parse("2026-12-08"), out = LocalDate.parse("2026-12-13");
System.out.println(in < out); } }
Main.java:4: error: bad operand types for binary operator '<'
System.out.println(in < out); } }
^
first type: LocalDate
second type: LocalDate
1 error
Two more, each a three-line main run the same way:
LocalDate a = LocalDate.of(2026, 12, 13), b = LocalDate.parse("2026-12-13");printeda == b ? false,a.equals(b) ? true,a.isEqual(b) ? true.==on objects asks "is this the same object in memory?", not "the same date?".LocalDate.parse("2026-12-8")threwException in thread "main" java.time.format.DateTimeParseException: Text '2026-12-8' could not be parsed at index 8.LocalDate.parseexpects the ISO formatyyyy-MM-dd; index 8 is where the two-digit day should start.
Mini project: a hotel booking service
One HotelService that puts everything together:
- Rooms of different RoomTypes, each with its own RoomCalendar (TreeMap by check-in).
search(type, in, out)andbook(guest, type, in, out): the guest asks for a type, andbookgives them the first free room of that type, in one synchronized step.- A state machine with all five states, a history per reservation,
cancelwith the made-up policy (and the room is freed),checkOutwith an invoice, and a nightlymarkNoShows. - A printed availability calendar, and a 10-thread test on the one suite.
import java.time.LocalDate; import java.util.*; import java.util.concurrent.*;
import static java.time.temporal.ChronoUnit.DAYS;
enum RoomType { STANDARD, DELUXE, SUITE }
record Room(int number, RoomType type, int ratePerNight) {}
record Guest(String name, String phone) {}
enum State { RESERVED, CHECKED_IN, CHECKED_OUT, CANCELLED, NO_SHOW;
boolean canGo(State to) { return switch (this) { // the only legal moves
case RESERVED -> to == CHECKED_IN || to == CANCELLED || to == NO_SHOW;
case CHECKED_IN -> to == CHECKED_OUT;
default -> false; }; } } // the rest are final
class Reservation {
final String id; final Guest guest; final Room room; final LocalDate in, out;
private State state = State.RESERVED;
final List<State> history = new ArrayList<>(List.of(State.RESERVED));
Reservation(String id, Guest guest, Room room, LocalDate in, LocalDate out) {
this.id = id; this.guest = guest; this.room = room; this.in = in; this.out = out; }
void moveTo(State to) {
if (!state.canGo(to)) throw new IllegalStateException(id + ": cannot go " + state + " -> " + to);
state = to; history.add(to); }
State state() { return state; }
long nights() { return DAYS.between(in, out); } }
class RoomCalendar { // one room, sorted by check-in
private final TreeMap<LocalDate, Reservation> byCheckIn = new TreeMap<>();
boolean isFree(LocalDate in, LocalDate out) {
Map.Entry<LocalDate, Reservation> last = byCheckIn.lowerEntry(out);
return last == null || !last.getValue().out.isAfter(in); }
void add(Reservation r) { byCheckIn.put(r.in, r); }
void remove(Reservation r) { byCheckIn.remove(r.in); }
Reservation on(LocalDate night) {
Map.Entry<LocalDate, Reservation> e = byCheckIn.floorEntry(night);
return e != null && e.getValue().out.isAfter(night) ? e.getValue() : null; } }
class HotelService {
private final Map<Integer, Room> rooms = new TreeMap<>();
private final Map<Integer, RoomCalendar> calendars = new HashMap<>();
private final Map<String, Reservation> reservations = new LinkedHashMap<>();
void addRoom(Room r) { rooms.put(r.number(), r); calendars.put(r.number(), new RoomCalendar()); }
Reservation get(String id) { return reservations.get(id); }
synchronized List<Integer> search(RoomType type, LocalDate in, LocalDate out) { // by date and type
return rooms.values().stream().filter(r -> r.type() == type && calendars.get(r.number()).isFree(in, out))
.map(Room::number).toList(); }
synchronized Reservation book(Guest g, RoomType type, LocalDate in, LocalDate out) { // check + add: one step
if (!out.isAfter(in)) throw new IllegalArgumentException("check-out must be after check-in");
List<Integer> free = search(type, in, out);
if (free.isEmpty()) throw new IllegalStateException("no " + type + " room free " + in + " to " + out);
Reservation r = new Reservation("R" + (reservations.size() + 1), g, rooms.get(free.get(0)), in, out);
calendars.get(r.room.number()).add(r); reservations.put(r.id, r); return r; }
synchronized int cancel(String id, LocalDate today) { // made-up policy
Reservation r = get(id); r.moveTo(State.CANCELLED); calendars.get(r.room.number()).remove(r);
return DAYS.between(today, r.in) >= 2 ? 0 : r.room.ratePerNight(); }
synchronized void checkIn(String id) { get(id).moveTo(State.CHECKED_IN); }
synchronized String checkOut(String id, int extras) { // the invoice
Reservation r = get(id); r.moveTo(State.CHECKED_OUT);
long room = r.nights() * r.room.ratePerNight(), tax = (room + extras) / 10; // made-up 10%
return "Invoice " + r.id + " | " + r.guest.name() + " | room " + r.room.number() + " | " + r.nights()
+ " nights x " + r.room.ratePerNight() + " = " + room + " | extras " + extras
+ " | tax " + tax + " | total " + (room + extras + tax); }
synchronized List<String> markNoShows(LocalDate today) { // a nightly job
List<String> marked = new ArrayList<>();
for (Reservation r : reservations.values())
if (r.state() == State.RESERVED && r.in.isBefore(today)) {
r.moveTo(State.NO_SHOW); calendars.get(r.room.number()).remove(r); marked.add(r.id); }
return marked; }
synchronized void printCalendar(LocalDate from, int days) {
StringBuilder head = new StringBuilder("night ");
for (int i = 0; i < days; i++) head.append(String.format("%-4d", from.plusDays(i).getDayOfMonth()));
System.out.println(head.toString().strip());
for (Room room : rooms.values()) {
StringBuilder row = new StringBuilder("room " + room.number() + " ");
for (int i = 0; i < days; i++) {
Reservation r = calendars.get(room.number()).on(from.plusDays(i));
row.append(String.format("%-4s", r == null ? "--" : r.guest.name().substring(0, 2))); }
System.out.println(row.toString().strip()); } } }
public class Main { public static void main(String[] args) throws Exception {
HotelService hotel = new HotelService(); LocalDate d = LocalDate.of(2026, 12, 10);
hotel.addRoom(new Room(101, RoomType.DELUXE, 4000)); hotel.addRoom(new Room(102, RoomType.DELUXE, 4000));
hotel.addRoom(new Room(201, RoomType.SUITE, 9000));
Guest asha = new Guest("Asha", "98xxxxxx01"), ravi = new Guest("Ravi", "98xxxxxx02"),
neha = new Guest("Neha", "98xxxxxx03"), amit = new Guest("Amit", "98xxxxxx04");
System.out.println("Asha -> room " + hotel.book(asha, RoomType.DELUXE, d, d.plusDays(3)).room.number());
System.out.println("Ravi -> room " + hotel.book(ravi, RoomType.DELUXE, d.plusDays(1), d.plusDays(5)).room.number());
try { hotel.book(neha, RoomType.DELUXE, d.minusDays(2), d.plusDays(5)); }
catch (IllegalStateException e) { System.out.println("Neha: " + e.getMessage()); }
System.out.println("Amit -> room " + hotel.book(amit, RoomType.DELUXE, d.plusDays(3), d.plusDays(4)).room.number());
try { hotel.book(neha, RoomType.SUITE, d.plusDays(5), d.plusDays(5)); }
catch (IllegalArgumentException e) { System.out.println("Neha: " + e.getMessage()); }
ExecutorService pool = Executors.newFixedThreadPool(10); // 10 guests, 1 suite, same moment
CountDownLatch go = new CountDownLatch(1); List<Future<Reservation>> tries = new ArrayList<>();
for (int i = 0; i < 10; i++) { Guest g = new Guest("Guest" + i, "-");
tries.add(pool.submit(() -> { go.await(); return hotel.book(g, RoomType.SUITE, d, d.plusDays(2)); })); }
go.countDown(); int ok = 0;
for (Future<Reservation> f : tries) try { f.get(); ok++; } catch (ExecutionException e) {}
pool.shutdown();
System.out.println("10 guests tap the one SUITE at once -> bookings made: " + ok);
hotel.printCalendar(d, 6);
System.out.println("Ravi (R2) cancels on Dec 10, fee: " + hotel.cancel("R2", d));
System.out.println("DELUXE free 11th-15th now: " + hotel.search(RoomType.DELUXE, d.plusDays(1), d.plusDays(5)));
hotel.checkIn("R1"); System.out.println(hotel.checkOut("R1", 850));
System.out.println("No-shows on Dec 14: " + hotel.markNoShows(d.plusDays(4)));
try { hotel.checkIn("R3"); } catch (IllegalStateException e) { System.out.println(e.getMessage()); }
for (String id : List.of("R1", "R2", "R3")) System.out.println(id + " history " + hotel.get(id).history);
} }
Real output:
Asha -> room 101
Ravi -> room 102
Neha: no DELUXE room free 2026-12-08 to 2026-12-15
Amit -> room 101
Neha: check-out must be after check-in
10 guests tap the one SUITE at once -> bookings made: 1
night 10 11 12 13 14 15
room 101 As As As Am -- --
room 102 -- Ra Ra Ra Ra --
room 201 Gu Gu -- -- -- --
Ravi (R2) cancels on Dec 10, fee: 4000
DELUXE free 11th-15th now: [102]
Invoice R1 | Asha | room 101 | 3 nights x 4000 = 12000 | extras 850 | tax 1285 | total 14135
No-shows on Dec 14: [R3, R4]
R3: cannot go NO_SHOW -> CHECKED_IN
R1 history [RESERVED, CHECKED_IN, CHECKED_OUT]
R2 history [RESERVED, CANCELLED]
R3 history [RESERVED, NO_SHOW]
What the run shows:
- Asha asks for a DELUXE room for 10-13 and gets 101; Ravi asks for DELUXE 11-15 and gets 102 (101 is busy on the 11th).
- Neha asks for DELUXE 8-15: both deluxe rooms overlap, so she gets
no DELUXE room free 2026-12-08 to 2026-12-15. - Amit asks for DELUXE 13-14 and gets 101, on the day Asha checks out.
- A stay from the 15th to the 15th is refused:
check-out must be after check-in. - 10 threads ask for the one SUITE (201) for 10-12 at the same moment: exactly 1 booking. Which guest wins changes from run to run; the calendar only shows
Gu(the first two letters of "Guest"), so the output is the same every time. - The calendar shows all three rooms night by night.
- Ravi cancels on Dec 10 for a Dec 11 check-in: 1 day before, so the fee is one night, 4000, and room 102 becomes free again for 11-15.
- Asha checks in and out with 850 of extras: total 14135, the same as in section 7.
- The no-show job on Dec 14 marks R3 (Amit, due on the 13th) and R4 (the suite guest, due on the 10th) as
NO_SHOW, and frees their rooms. Amit then can't check in:R3: cannot go NO_SHOW -> CHECKED_IN. - The histories show each reservation's path through the state machine.
Design choices worth saying in an interview: canGo is the single table of legal moves; RoomCalendar hides the TreeMap so nobody can add a stay without the free check; the whole service uses one lock (simple and correct; a big hotel could use one lock per room so bookings for different rooms don't wait for each other).
Practice
1. A room is booked 20 Dec to 23 Dec. Write the overlap condition for a new stay [in, out) using LocalDate methods, and say whether 23-26 is allowed.
Answer
in.isBefore(LocalDate.of(2026, 12, 23)) && LocalDate.of(2026, 12, 20).isBefore(out). For 23-26: is the 23rd before the 23rd? No, so there's no overlap: the stay is allowed. The new guest arrives on the old guest's check-out day.
2. Add NO_SHOW to the episode's STATES program.
Answer
NO_SHOW is already in the enum; add a method void noShow() { move(State.RESERVED, State.NO_SHOW); } and call it from a nightly job for every RESERVED stay whose check-in day has passed. The mini project's markNoShows does exactly this, and also frees the room in its calendar. Because the move goes through move, a checked-in guest can never be marked a no-show.
3. Weekend nights (Friday and Saturday) cost 20% more. Price Asha's stay of 10-13 Dec at 4000 a night.
Answer
Price each night separately, from check-in up to (not including) check-out:
import java.time.*;
public class Main {
static long price(int rate, LocalDate in, LocalDate out) { // weekend nights cost 20% more
long total = 0;
for (LocalDate n = in; n.isBefore(out); n = n.plusDays(1)) { // each night: in .. out-1
DayOfWeek w = n.getDayOfWeek();
total += (w == DayOfWeek.FRIDAY || w == DayOfWeek.SATURDAY) ? rate * 12 / 10 : rate; }
return total; }
public static void main(String[] args) {
LocalDate in = LocalDate.of(2026, 12, 10), out = LocalDate.of(2026, 12, 13);
for (LocalDate n = in; n.isBefore(out); n = n.plusDays(1)) System.out.println(n + " " + n.getDayOfWeek());
System.out.println("Asha 10th-13th at 4000: " + price(4000, in, out)); } }
Real output:
2026-12-10 THURSDAY
2026-12-11 FRIDAY
2026-12-12 SATURDAY
Asha 10th-13th at 4000: 13600
The 11th and 12th are Friday and Saturday: 4000 + 4800 + 4800 = 13600. In the design, this loop is one PricingStrategy; the invoice asks the strategy for the room total instead of computing nights × rate.
4. Book two rooms for one family, all or nothing.
Answer
Inside one synchronized method: run isFree for both rooms first; if either is taken, throw and add nothing; only if both are free, add both reservations. Checking and adding one room at a time could leave the family with one room and the second already gone. With per-room locks, always lock the rooms in the same order (for example by room number) so two families can't each hold one lock and wait for the other forever (a deadlock).
5. Why does RoomCalendar.isFree only look at one entry, lowerEntry(out)?
Answer
Stays starting on or after out can't overlap. Among stays starting before out, the stays in one room never overlap each other, so the one that starts last also ends last. If it ends by the new check-in, all the earlier ones do too.
Quick quiz
Room 204 is booked from Dec 20 to Dec 23 (check-out Dec 23). Which new stay can be booked? (A) Dec 22 to Dec 24 (B) Dec 18 to Dec 25 (C) Dec 23 to Dec 26 (D) Dec 19 to Dec 21
Answer
(C). Overlap if newIn < oldOut and oldIn < newOut. C: is Dec 23 < Dec 23? No, so no overlap: the guest arrives on the check-out day. A (22 < 23 and 20 < 24), B (18 < 23 and 20 < 25) and D (19 < 23 and 20 < 21) all overlap. B is exactly Neha's bug: it starts before and ends after.
Interview questions
- What are the requirements of a hotel booking system? Search by dates and type, book, cancel with a policy, check in, check out with an invoice, no-shows, and never overbook.
- Which classes do you start with? Hotel, Room, RoomType (enum), Guest, Reservation (with a State), and a RoomCalendar per room.
- How do you check whether two date ranges overlap?
aIn < bOut && bIn < aOut, with half-open ranges[in, out). - Why half-open
[in, out)? The check-out day is not a night, so a guest can arrive that day; and nights = out − in. - How do you prevent overbooking? Check and add in one atomic step:
synchronizedin one JVM; a row lock or a unique (room, night) constraint in the database across servers. - How do you make the availability check fast? A TreeMap per room keyed by check-in;
lowerEntry(out)gives the only stay that can clash: O(log n). - How do you search by date and type? Filter rooms by type, then keep those whose calendar is free for the dates.
- How do you model booking states? An enum state machine: RESERVED, CHECKED_IN, CHECKED_OUT, CANCELLED, NO_SHOW, with only the legal moves allowed.
- Where does the cancellation policy live? In one place (a method or a
CancellationPolicystrategy) that takes the reservation and the cancel date and returns the fee, so the hotel can change the rule without touching booking code. - What goes on an invoice? Nights × rate (or a per-night price from a pricing strategy), extras, tax, total; created when the guest checks out.
Glossary
| Term | Meaning, with an example |
|---|---|
| Hotel booking requirements | What the system must do: search, book, cancel, check in/out, bill, never overbook |
| Hotel | Owns the rooms and the reservations; search and book live here |
| Room | One room: number, type, rate per night: Room(101, DELUXE, 4000) |
| RoomType | An enum of room kinds: STANDARD, DELUXE, SUITE |
| Rate per night | The price of one night in that room: 4000 rupees |
| Guest | The person staying: Guest("Asha", "98xxxxxx01") |
| Reservation | One stay: guest + room + check-in + check-out: Asha, 101, 10-13 Dec |
| Check-in date | The first night of the stay; included in the range |
| Check-out date | The day the guest leaves; not a night, not included |
| Night | One sleep in the room; the stay 10-13 has the nights of the 10th, 11th and 12th |
Half-open interval [in, out) |
A range that includes its start but not its end |
| Date-range overlap check | Do two stays share a night? aIn < bOut && bIn < aOut |
| Overlap | Two stays in one room sharing at least one night: Asha 10-13 and Neha 8-15 |
| Search by date and type | Find all rooms of a type free for the dates: DELUXE free 8th-15th: [102] |
| Availability calendar | Per room, its stays sorted by date: answers "free?" and "who's here tonight?" |
| Overbooking | Giving one room to two guests on the same night |
| Overbooking prevention | Making check + add one step so that can't happen: bookings made: 1 |
| Booking states | The stages of a reservation: RESERVED, CHECKED_IN, CHECKED_OUT, CANCELLED, NO_SHOW |
| No-show | A guest with a reservation who never arrives |
| State machine | States plus the only legal moves between them; other moves are refused |
| Transition | One move from one state to another: RESERVED → CHECKED_IN |
| Cancellation policy | The rule for the cancel fee: free until 2 days before, else one night (made up) |
| Invoice | The bill at check-out: nights × rate + extras + tax |
| Extras | Charges beyond the room, like room service: 850 |
| Enum | A fixed list of named values: RoomType, State |
| Record | A short Java class with fixed fields and methods written for you: record Guest(String name, String phone) |
| LocalDate | Java's date without a time: LocalDate.of(2026, 12, 10) |
isBefore / isAfter / isEqual |
How you compare two LocalDates |
ChronoUnit.DAYS.between(a, b) |
Days from a to b: from Dec 10 to Dec 13 is 3 |
| ISO date format | yyyy-MM-dd, the format LocalDate.parse expects: 2026-12-08 |
| DateTimeParseException | Thrown when text isn't a valid date: '2026-12-8' could not be parsed |
| TreeMap | A map that keeps its keys sorted, so it finds neighbours fast |
lowerEntry(k) |
The entry with the greatest key strictly less than k |
floorEntry(k) |
The entry with the greatest key less than or equal to k |
| O(n) / O(log n) | How the work grows with n items: a full scan vs a few steps (about 10 for 1000) |
| Thread | One line of work running in a program; 20 guests booking at once = 20 threads |
| Race condition | A bug where the result depends on which thread runs first: 7 bookings for one room |
synchronized |
Only one thread at a time may run this method on this object |
| Lock | What synchronized takes: whoever holds it runs, others wait |
| Atomic | Can't be split: no other thread can act in the middle of it |
| ExecutorService / thread pool | A set of worker threads that run tasks you submit |
| Future | A handle to a task's result; get() waits for it and rethrows its exception |
| ExecutionException | What Future.get() throws when the task threw |
| CountDownLatch | A gate threads wait at until it is opened (countDown), so they start together |
| IllegalStateException | "Not allowed in the current state": room 101 is taken ... |
| IllegalArgumentException | "This argument is wrong": check-out must be after check-in |
| Composition | A part that belongs to its whole: rooms belong to the hotel |
| Association | One object refers to another that lives on its own: a reservation points at a guest |
| PricingStrategy | An interface that prices each night, so weekend or festival rates plug in |
| Deadlock | Two threads each holding a lock the other one needs, waiting forever |
| Unique constraint | A database rule that a value (like room + night) can appear only once |
Summary
- Hotel booking requirements: search by dates and type, book, cancel, check in, check out with an invoice, no-shows, and never overbook.
- Classes: Hotel has Rooms (number, RoomType, rate); a Reservation joins a Guest and a Room for
[check-in, check-out). - Checking only the new check-in put Asha and Neha in one room (
[Asha, Neha]): a covering stay slips through. - The date-range overlap check:
aIn < bOut && bIn < aOut, strictly less-than, so the check-out day is free. - Search by date and type filters rooms by type and the free check:
DELUXE free 8th-15th: [102]. - Overbooking prevention: check + add in one
synchronizedstep: 20 threads,bookings made: 1(without it, a real run made 7). - An availability calendar per room is a TreeMap by check-in:
lowerEntry(out)is one O(log n) lookup. - Booking states as a state machine (
cannot go CANCELLED -> CHECKED_IN), a made-up cancellation policy (fee 0 or one night), and an invoice (total 14135). - Next episode: design an inventory management system: products, SKUs, warehouses, stock in and out, reservations vs committed stock, and low-stock alerts.