Skip to content
Tutorials Center
My learning

Topics

Lesson 174 of 201 ยท Projects

Project: Bank Account System

Build a Java bank account system in stages with encapsulation, BigDecimal money, custom exceptions, checking and savings subclasses and a transaction history.

A bank account is the classic object-oriented example for a good reason: it has state that must never become wrong. A balance that silently goes negative, a deposit of minus fifty dollars, or a history that someone can edit after the fact are exactly the bugs that objects, encapsulation and exceptions were invented to prevent. In this project you'll build a small banking system that gets those rules right.

You'll build it in five stages, from a single Account class to a Bank that opens checking and savings accounts, moves money between them, runs month-end processing and prints statements, all driven by commands in the Input box. Each stage is a complete program, so you can run it on its own and experiment.

The project practices classes and objects, encapsulation, inheritance, abstract classes, custom exceptions, records, enums and BigDecimal. In a real project each class would live in its own file inside a package; here everything sits in one file so it can run in the editor. The public class Main comes first because Java's source launcher runs the first class in the file.

The rules of our bank

Writing down the rules first tells you which classes you need and what each one must protect:

  • Every account has a number, an owner and a balance. Only deposits, withdrawals, transfers, fees and interest can change the balance.
  • Amounts are positive and have at most two decimal places. Nobody deposits $-20 or $0.001.
  • A checking account may go below zero up to an overdraft limit. It charges a monthly fee unless the balance is at least $500.
  • A savings account can never go below zero, earns monthly interest, and allows at most three withdrawals or outgoing transfers per month.
  • Every change is recorded in a transaction history that can be read but never edited.

Stage 1: one account that protects its balance

The first version is a single class. The key decision is that the balance is private: no code outside Account can assign it. The only way to change it is through deposit and withdraw, and those methods check every request.

Java Stage 1: an encapsulated account

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 two lines show why money is never a double: 0.10 + 0.20 prints 0.30000000000000004, because binary floating-point can't represent most decimal fractions exactly. Rounding errors like that add up over millions of transactions. BigDecimal stores decimal digits exactly, so 0.10 + 0.20 is 0.30. The price is verbosity: you call add and subtract instead of writing + and -, and you compare with compareTo, never equals, because new BigDecimal("2.0").equals(new BigDecimal("2.00")) is false (the scales differ). The BigDecimal lesson covers this in depth.

The design decisions in this class:

  • Fields that never change are final. An account's number and owner are fixed at creation. Marking them final documents that and lets the compiler enforce it.
  • There's a getter but no setter for the balance. Code outside the class can read the balance, but there's no setBalance, because "set the balance to any number" isn't an operation a bank has.
  • All checks live in one private method. validate rejects zero, negative amounts and fractions of a cent, then normalizes the amount to exactly two decimals with setScale(2), so 100 becomes 100.00. Both deposit and withdraw call it, so the rules can't drift apart.
  • A refused operation changes nothing. withdraw checks first and modifies the balance only after every check has passed. That ordering is easy to get wrong, and it's what keeps the balance at 69.75 after the two refused requests.

Stage 2: custom exceptions

Stage 1 signals problems with IllegalArgumentException and IllegalStateException. They work, but they have two weaknesses. A caller can't tell a banking problem apart from a bug elsewhere, since many things throw those exceptions. And the information is trapped in a message string: if a user interface wants to say "you're short by $400.00", it would have to parse text.

A small exception hierarchy fixes both:

Java Stage 2: a banking exception hierarchy

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.

BankException is the root of everything that can go wrong in the bank. Code that just wants to report any banking problem catches BankException; code that wants to react to one specific case, like offering an overdraft when funds are short, catches InsufficientFundsException first. The order of the catch blocks matters: the more specific type must come first, or the compiler reports that it's unreachable.

InsufficientFundsException carries its data in fields, not just in the message. getShortfall() computes 400.00 from real numbers, with no text parsing involved. The Custom Exceptions lesson explains this pattern.

Checked or unchecked?

BankException extends Exception, which makes it checked: every method that can throw it must declare throws, and every caller must handle it or pass it on. That's a deliberate choice. Running out of money isn't a bug; it's a normal outcome that every caller of withdraw must think about, and a checked exception makes the compiler remind them. Remove the try around withdraw and the program no longer compiles.

Many teams prefer unchecked exceptions (extending RuntimeException) for everything, because throws clauses spread through layers of code. Both styles are defensible; the Throwing Exceptions lesson discusses the trade-off. What matters is that the choice is made on purpose and applied consistently.

Stage 3: transaction history with records

A bank that only knows the current balance can't answer "where did my money go?" Every change should leave a permanent record. A record is perfect for that: a transaction is pure data, it never changes once it has happened, and records are immutable by design.

Java Stage 3: recording every transaction

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 statement lists three transactions, not four: the refused withdrawal threw before record was called, so it never happened as far as the history is concerned. That's the "check first, then change" rule from Stage 1 paying off again.

The pieces:

  • TransactionType is an enum with a field. Each constant knows whether it adds or removes money, so signedAmount() doesn't need a switch that someone must update for every new type. The Enums lesson covers constants with fields.
  • Transaction is a record with an extra method. Its balanceAfter component makes each line of the statement self-checking: you can verify any row from the one above it.
  • record(...) is private and called from inside deposit and withdraw. Nobody can add a transaction without the balance actually changing, and nobody can change the balance without a transaction.
  • getHistory() returns List.copyOf(history), an unmodifiable copy. Returning the internal ArrayList itself would let any caller clear() it or add fake entries, breaking encapsulation through the back door. This is the defensive-copy idea from Encapsulation and Immutable Classes.

main declares throws BankException here, so the demo deposits don't each need a try. That's acceptable in a quick demo where any failure is a bug; real programs handle the exception where they can do something useful.

Stage 4: checking and savings accounts

Now the two account types. They share almost everything (number, owner, balance, history, validation) and differ only in a few rules: how far the balance may drop, how many withdrawals are allowed, and what happens at the end of the month. That's the textbook case for an abstract base class with subclasses that override small, specific hooks.

Java Stage 4: an account hierarchy

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 checking account dips to -50.00 thanks to its $100 overdraft, then refuses the next $80 because only $50 of credit is left. The savings account allows three withdrawals and refuses the fourth. At month-end, checking pays a $3.00 fee (its balance is under $500) and savings earns 4.92 in interest: 3% a year on $1,970.00 is $59.10, and a twelfth of that is exactly $4.925. That is a tie, and the rounding mode decides it, as explained below.

This stage is where the object-oriented design really earns its keep:

withdraw is a template method. The base class defines the steps of a withdrawal, in an order that can't be changed: validate, ask the subclass whether it's allowed, change the balance, notify the subclass. The method is final, so no subclass can skip validation or forget to record the transaction. Subclasses only fill in the two hooks, checkWithdrawal and afterWithdrawal. This is the template method pattern: the invariants live in one place, the variations in small overrides.

Overrides can extend instead of replace. SavingsAccount.checkWithdrawal adds its monthly limit and then calls super.checkWithdrawal(amount) to keep the base rule against negative balances. CheckingAccount replaces the base rule completely, because its limit is different. The super keyword lesson covers both patterns.

credit and debit are protected final. Subclasses need them for fees and interest, so they're protected; they must always record a transaction, so they're final. Note that debit doesn't check the balance at all: the bank charges its fee even if that pushes the account further negative. Fees and interest are the bank's decisions, not the customer's requests, so they skip the customer-facing checks.

Polymorphism drives month-end. main loops over a List<Account> and calls monthEnd() on each element, without knowing or checking which kind it is. Each object runs its own version: that's dynamic dispatch. Adding a third account type later means writing one new class, with no if (account instanceof ...) chains to update.

Interest uses an explicit rounding mode. divide(BigDecimal.valueOf(12), 2, RoundingMode.HALF_EVEN) says exactly how many decimals to keep and how to round. Without a scale, BigDecimal.divide throws an ArithmeticException whenever the result has infinitely many digits, which dividing by 12 often produces. HALF_EVEN (banker's rounding) rounds ties toward the even digit, so $4.925 becomes 4.92, while HALF_UP would give 4.93. Across millions of accounts, always rounding ties up would hand out a systematic extra fraction of a cent; rounding to even balances out.

The constructors don't call any overridable methods. Calling kind() from the Account constructor would run the subclass's version before the subclass's fields are initialized, a classic trap described in Abstraction and Abstract Classes.

Stage 5: the bank and its commands

The last piece is a Bank that owns all accounts, opens new ones, finds them by number and transfers money between them. A small command interpreter reads one command per line from the Input box, so you can run whole scenarios without editing code.

Java Stage 5: the complete banking 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.

Every command is echoed with > so you can follow the story, and every failure prints a ! line instead of stopping the program. Try your own scenarios: overdraw Bilal's account, make four transfers out of savings in one month, or add a month-end between them.

Turning text into calls

main reads lines, splits each into words and hands them to execute, a switch with one arrow case per command. Each case checks its argument count with need, which throws a BankException with a usage hint. Without that check, withdraw 1001 would crash with an ArrayIndexOutOfBoundsException, an exception that tells the user nothing.

The single catch (BankException e) in main handles every expected problem: unknown commands, wrong argument counts, unknown accounts, bad amounts and refused withdrawals. That one catch is possible because all of them share the root type designed in Stage 2. Unexpected problems, which are bugs, are not caught, so they still crash loudly with a stack trace instead of hiding.

Money.parse translates NumberFormatException into InvalidAmountException, so the user sees 'abc' is not an amount instead of a Java message. Parsing and validating are separate on purpose: parse only turns text into a number, and validate applies the business rules, which also protects calls that never went through text.

The Bank class

Bank keeps accounts in a LinkedHashMap keyed by account number: lookups by number are fast, and iteration follows the order accounts were opened, which keeps the balances list stable. See LinkedHashMap.

  • open picks the subclass with a switch expression. The account number is consumed only after the account is created successfully, so a failed open doesn't leave a gap in the numbering.
  • find turns a missing key into an AccountNotFoundException instead of returning null. Callers can't forget the null check, because there's no null.
  • accounts() returns a copy, for the same reason getHistory() does.

Transfers

A transfer must be all or nothing: money leaves one account and arrives in the other, or neither happens. The transfer method does every check that can fail before moving any money: the same-account check, both lookups, amount validation, and then withdraw, which runs the source account's own rules (overdraft, savings limit). Only after withdraw succeeds does receive credit the target, and receive can't fail. So if anything goes wrong, nothing has changed.

That ordering is the honest best you can do in memory. Real banks also have to survive a crash between the two steps, which is why they use database transactions, as you'll see in the Advanced Java track. Notice also that transfers go through the same withdraw template method, so the savings account's monthly limit applies to them automatically: the transfer from 1002 uses one of its three monthly withdrawals.

The package-private overload withdraw(amount, type, note) and receive are available to Bank but not part of the public API. In a real project, Bank and Account would share a package, and other packages could use only deposit and the plain withdraw. The Access Modifiers lesson explains package-private access.

Formatting money

Money.format uses %,.2f, which adds thousands separators and always shows two decimals: 2,000.00. String.format and printf accept a BigDecimal for %f directly and format it exactly, without converting it to double. Locale-aware currency formatting with symbols is covered in Formatting Strings.

Ideas to extend it

  • Dates on transactions. Add a LocalDate date component to Transaction and a date YYYY-MM-DD command that sets the bank's current day. See Dates and Times.
  • A transaction limit. Refuse any single withdrawal above $1,000 with a new LimitExceededException, and decide where in the hierarchy it belongs.
  • Overdraft interest. Charge checking accounts 18% a year on negative balances at month-end, with the same rounding approach as savings interest.
  • A sealed hierarchy. Make Account sealed ... permits CheckingAccount, SavingsAccount, then write a switch over account types that the compiler checks for exhaustiveness. See Sealed Classes.
  • Close an account. Allow closing only at a zero balance, and make every later operation on it fail with a clear exception.
  • Undo-proof audit. Add a running total of all deposits minus all withdrawals across the bank, and verify at the end that it equals the sum of all balances.
  • Unit tests. Write JUnit tests for the overdraft and savings rules, as shown in Unit Testing with JUnit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does new BigDecimal("2.0").equals(new BigDecimal("2.00")) return, and what should money code use instead?

    BigDecimal.equals compares both the value and the scale, so 2.0 and 2.00 are not equal. compareTo compares only the value and returns 0 here.
  2. 2. In Stage 4, why is withdraw declared final in the Account class?

    withdraw is a template method. Making it final guarantees the steps (validate, check, debit, notify) always happen in order; subclasses change behavior through checkWithdrawal and afterWithdrawal.
  3. 3. A savings account has made three withdrawals this month. What happens when bank.transfer is called with it as the source?

    transfer goes through the same withdraw template method, so checkWithdrawal throws before any balance changes, and receive is never reached.
  4. 4. Why does getHistory() return List.copyOf(history) instead of history?

    Returning the internal mutable list leaks the object's state. An unmodifiable copy lets callers read the history but throws UnsupportedOperationException on any change.
  5. 5. Why is BankException a checked exception in this project?

    Insufficient funds or an unknown account isn't a bug; it's an expected result that every caller must deal with. A checked exception makes forgetting that a compile error. Unchecked would also be a valid design choice.

Summary

  • Money is a BigDecimal, never a double; compare with compareTo, set the scale explicitly and name a rounding mode when dividing.
  • Encapsulation keeps the balance private, changed only by methods that validate first and modify last, so a refused operation changes nothing.
  • A checked BankException hierarchy lets callers catch every banking problem at once or one specific case, and exception fields carry data like the shortfall.
  • Immutable Transaction records, created only inside the account and exposed as an unmodifiable copy, form a trustworthy history.
  • An abstract Account with a final template method and small hooks lets CheckingAccount and SavingsAccount change rules without breaking invariants; polymorphism runs month-end for any account type.
  • The Bank validates everything before moving money, so transfers are all or nothing, and a command interpreter turns Input-box lines into method calls with friendly errors.

Next: Project: Library Management System, where you'll manage books, members and loans with maps, lists and due dates.