Skip to content
Tutorials Center
My learning

Topics

Lesson 183 of 201 ยท Projects

Project: ATM Simulation

Build a Java ATM simulator with a hashed PIN check and lockout, BigDecimal balances, per-transaction and daily withdrawal limits, note dispensing and a transaction log.

An ATM looks simple from the outside: insert a card, type a PIN, take cash. Underneath, it is a small state machine wrapped around a lot of rules. You can't see a balance until you've proven who you are. You can't withdraw more than your account holds, more than the machine allows per transaction, or more than your daily limit. The machine can only hand out the notes it actually contains, so some amounts that look fine are impossible. And everything that happens must be written to a log.

In this project you'll build that machine in two stages. First a card that checks a PIN without ever storing it, and locks after three mistakes. Then the full ATM, driven by commands you type into the Input box, with limits, note dispensing and a transaction log. You'll practice encapsulation, enums, records, custom exceptions, BigDecimal, maps and a little recursion.

This is a teaching model, not banking software. Real PIN verification happens inside tamper-resistant hardware, never in application code, and real money movement needs durable storage and audit trails. The goal here is to see how the rules fit together.

The flow of a session

An ATM is always in one of a few states, and the commands you may use depend on the state:

flowchart LR
    A["No card"] -->|"insert"| B["Card inserted"]
    B -->|"pin (correct)"| C["Authenticated"]
    B -->|"pin (wrong x3)"| D["Card locked"]
    C -->|"balance, withdraw, deposit, log"| C
    C -->|"eject"| A
    B -->|"eject"| A

Withdraw, deposit and balance only work in the Authenticated state; everything else is refused.

Coding the states explicitly, instead of scattering if (loggedIn) checks, makes the rules easy to read and hard to bypass.

Stage 1: a card that never stores the PIN

The first rule of PINs is that nothing stores them. A card keeps a hash: a one-way fingerprint of the PIN. When the user types a PIN, you hash it and compare fingerprints. If someone steals the data, they get fingerprints, not PINs.

Java Stage 1: PIN verification with a hash and lockout

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.

Look at the run: the first wrong PIN costs an attempt, the correct PIN 2580 works and resets the failure counter, then three wrong PINs in a row lock the card. After that even the correct PIN is refused with LOCKED.

Details worth noticing:

  • The card number is mixed into the hash (number + ":" + pin). Two customers who both chose 2580 get different fingerprints. That extra ingredient is called a salt. A real system uses a random salt per card and a deliberately slow algorithm such as PBKDF2, because there are only 10,000 four-digit PINs and plain SHA-256 can be brute-forced instantly. Treat this as a demonstration of the idea.
  • MessageDigest.isEqual compares in constant time. A normal array comparison stops at the first difference, and the time it takes can leak how many leading bytes were right. isEqual always looks at everything.
  • The lock check comes first. Once locked, the card doesn't even compute a hash, so a locked card can never be "guessed open".
  • A correct PIN resets failures. Otherwise three typos spread over a year would lock the card for good.

Stage 2: the complete ATM

Now the whole machine. These are the rules it enforces, in the order it checks them:

  1. You must be authenticated.
  2. The amount must be a whole number of currency units and a multiple of 20 (the smallest note).
  3. One transaction may not exceed 300.
  4. The day's total may not exceed 500.
  5. The amount may not exceed the account balance.
  6. The machine must be able to build the amount from the notes it holds.

Rule 6 is the interesting one. The ATM holds three 100 notes, four 50 notes and ten 20 notes. A greedy approach (take as many 100s as possible, then 50s, then 20s) fails on 260: it takes two 100s and one 50, is left with 10, and no note can make 10. The right answer is two 100s and three 20s. To find it, the dispenser tries the largest count of each note first and backtracks when the rest can't be completed. That is a few lines of recursion.

All six checks run before anything changes. If a plan for the notes exists, the machine commits the debit, the stock change and the log entry together.

Java Stage 2: the complete ATM

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 the output from top to bottom and match each line to a rule:

  • balance before inserting a card is refused by requireSession. The same one-line guard protects every private command.
  • pin 0000 costs an attempt; pin 2580 signs in.
  • withdraw 65 fails the multiple-of-20 rule, withdraw 400 fails the per-transaction limit.
  • withdraw 260 is the backtracking case: the answer is two 100 notes and three 20s.
  • After withdraw 240 the day's total is exactly 500, so withdraw 20 is refused with "you can still withdraw 0".
  • The deposit of 100.50 is stored with two decimals, and -5 is refused.
  • Bilal's card shows the lockout: the third wrong PIN locks it, and even the correct 1357 afterwards is refused.

Design notes

  • Validate, then mutate. withdraw finishes every check and builds the note plan before it touches the balance or the stock. A refused request changes nothing, so you never have to undo half an operation.
  • The log is part of the account. record is private and called only by debit and credit, so a log entry can't be forgotten or invented. log() returns List.copyOf, an unmodifiable snapshot.
  • LogEntry is a record. An immutable value with an automatic constructor and accessors is exactly right for a history line.
  • stock.get(note) is safe because denominations came from the same map's keys.
  • Exceptions are for refusals. One AtmException with a readable message lets main print every refusal in one place, which keeps the command code free of printing logic.

Ideas to extend it

  • Add a transfer command and a change-pin command (require the old PIN first).
  • Store the daily total with a date, so it resets at midnight. Use java.time and inject a Clock so tests can control time.
  • Add a refill 20 5 administrator command that raises the stock of a note.
  • Put a Swing front end on the same Atm class. That separation of model and screen is the point of keeping all printing in main.
  • Write tests for the limits, especially boundaries: exactly 300, exactly 500 for the day, and an amount that needs backtracking.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the card store a hash of the PIN instead of the PIN itself?

    A hash is one-way, so leaked data doesn't directly contain PINs. It does not make a four-digit PIN unguessable (there are only 10,000 of them), which is why real systems use slow algorithms and hardware security modules.
  2. 2. The machine holds 100, 50 and 20 notes. Why does a greedy dispenser fail on 260?

    Greedy commits to the biggest notes first and never reconsiders. The backtracking plan tries fewer 50s and finds two 100s plus three 20s.
  3. 3. Why does withdraw build the note plan before calling card.debit?

    Validating everything first and mutating last means a refused request leaves the balance, stock and log untouched.
  4. 4. What is the benefit of MessageDigest.isEqual over a loop that stops at the first differing byte?

    An early-exit loop takes longer the more leading bytes match, which can leak information. isEqual always examines every byte.

Summary

  • Model the ATM as explicit states, and guard every protected command with one requireSession check.
  • Store a salted hash of the PIN, compare in constant time, lock after three failures and reset the counter on success.
  • Use BigDecimal for money, compareTo for comparisons and remainder for "multiple of" rules.
  • Run every check before changing anything, so refused requests leave no trace.
  • Dispensing exact notes from limited stock is a small backtracking problem; greedy is not always enough.
  • Keep the transaction log inside the account, written only by the methods that change the balance.

Next: Project: Currency Converter, where you'll convert money with an exchange-rate table, rounding rules and locale-aware formatting.