Skip to content
Java project #12Intermediate

Bank Ledger with Custom Exceptions

Savings and current accounts, overdrafts, atomic transfers, monthly interest, freezing and statements — with every failure modelled as a checked custom exception and an audit check.

Estimated time
~5 hours to build
Files
6 files · 428 lines
Technologies
Java 21, Custom checked exceptions, Records, LinkedHashMap, Nested classes

Introduction

Banks never just change a balance; they record entries in a ledger and derive balances from them. This project follows that discipline and uses a small hierarchy of checked exceptions so the caller can react precisely to 'insufficient funds' versus 'account frozen' versus 'no such account'.

Problem statement

Implement a bank with savings accounts (minimum opening deposit ₹1,000, 4% annual interest credited monthly) and current accounts (minimum ₹5,000, ₹10,000 overdraft). Support deposits, withdrawals, transfers that never half-happen, interest runs, freezing and unfreezing, statements and a list of accounts. Record every movement as a numbered ledger entry and provide an audit that checks the ledger total equals the sum of balances. Report failures with specific messages, including the shortfall for declined debits.

Objectives

  • Design a hierarchy of checked custom exceptions
  • Keep money movements in an append-only ledger
  • Validate everything before changing state (atomic operations)
  • Use an enum to vary rules by account type

Features

  • Two account types with different rules
  • Overdraft-aware withdrawals and transfers
  • Interest, freezing, statements and audit
  • Declines that report the exact shortfall

Concepts demonstrated

  • Exception hierarchies
  • Ledger / audit trail
  • Atomicity
  • Encapsulation
  • Business rules

System architecture

BankException is a checked exception with three nested subclasses: InsufficientFunds (carrying the shortfall), AccountFrozen and NoSuchAccount. Bank stores accounts in insertion order and a list of Entry records; the private post method is the only place a balance changes, and it always writes an entry. transfer validates both accounts and the funds before posting the debit and the credit. audit compares the sum of ledger amounts with the sum of balances. Main catches InsufficientFunds before the general BankException to print the shortfall.

Folder structure

TextProject tree
bank-ledger/
├── README.md
├── src/Bank.java
├── src/BankException.java
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Bank.java

125 lines
Javasrc/Bank.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Double-entry style ledger: every movement of money is recorded as an immutable entry, and
* balances are always derived from entries. Transfers are all-or-nothing.
*/
public class Bank {
public enum Kind { SAVINGS, CURRENT }
public record Entry(int seq, String account, String description, long amount, long balanceAfter) { }
public static final class Account {
private final String number;
private final String owner;
private final Kind kind;
private long balance;
private boolean frozen;
Account(String number, String owner, Kind kind) {
this.number = number;
this.owner = owner;
this.kind = kind;
}
public String number() { return number; }
public String owner() { return owner; }
public Kind kind() { return kind; }
public long balance() { return balance; }
public boolean frozen() { return frozen; }
long overdraftLimit() { return kind == Kind.CURRENT ? 10_000 : 0; }
long available() { return balance + overdraftLimit(); }
}
private final Map<String, Account> accounts = new LinkedHashMap<>();
private final List<Entry> ledger = new ArrayList<>();
private int nextNumber = 1;
public Account open(String owner, Kind kind, long initialDeposit) throws BankException {
if (initialDeposit < (kind == Kind.SAVINGS ? 1_000 : 5_000))
throw new BankException(kind + " accounts need an opening deposit of at least Rs " + (kind == Kind.SAVINGS ? "1,000" : "5,000"));
Account a = new Account(String.format("AC%04d", nextNumber++), owner, kind);
accounts.put(a.number(), a);
post(a, "opening deposit", initialDeposit);
return a;
}
public Account get(String number) throws BankException {
Account a = accounts.get(number);
if (a == null) throw new BankException.NoSuchAccount(number);
return a;
}
public void deposit(String number, long amount) throws BankException {
Account a = active(number);
requirePositive(amount);
post(a, "deposit", amount);
}
public void withdraw(String number, long amount) throws BankException {
Account a = active(number);
requirePositive(amount);
if (amount > a.available()) throw new BankException.InsufficientFunds(number, amount, a.available());
post(a, "withdrawal", -amount);
}
/** Both sides are validated before either is posted, so a transfer never half-happens. */
public void transfer(String from, String to, long amount) throws BankException {
if (from.equals(to)) throw new BankException("cannot transfer to the same account");
Account src = active(from), dst = active(to);
requirePositive(amount);
if (amount > src.available()) throw new BankException.InsufficientFunds(from, amount, src.available());
post(src, "transfer to " + to, -amount);
post(dst, "transfer from " + from, amount);
}
/** Savings accounts earn 4% a year; one month of interest is credited, rounded to the rupee. */
public long applyMonthlyInterest() {
long total = 0;
for (Account a : accounts.values())
if (a.kind() == Kind.SAVINGS && !a.frozen() && a.balance() > 0) {
long interest = Math.round(a.balance() * 0.04 / 12);
if (interest > 0) {
post(a, "interest", interest);
total += interest;
}
}
return total;
}
public void setFrozen(String number, boolean frozen) throws BankException { get(number).frozen = frozen; }
public List<Entry> statement(String number) throws BankException {
get(number);
return ledger.stream().filter(e -> e.account().equals(number)).toList();
}
public Collection<Account> accounts() { return accounts.values(); }
/** The sum of all entries must equal the sum of all balances — a basic audit check. */
public boolean audit() {
long fromLedger = ledger.stream().mapToLong(Entry::amount).sum();
long fromBalances = accounts.values().stream().mapToLong(Account::balance).sum();
return fromLedger == fromBalances;
}
private Account active(String number) throws BankException {
Account a = get(number);
if (a.frozen()) throw new BankException.AccountFrozen(number);
return a;
}
private static void requirePositive(long amount) throws BankException {
if (amount <= 0) throw new BankException("amount must be positive");
}
private void post(Account a, String description, long amount) {
a.balance += amount;
ledger.add(new Entry(ledger.size() + 1, a.number(), description, amount, a.balance));
}
}

What each file does

src/BankException.java
The checked exception hierarchy used for every banking rule.
src/Bank.java
Accounts, the ledger, deposits, withdrawals, transfers, interest, freezing and the audit.
src/Main.java
Command parsing and specific handling of each exception type.

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
=== Bank Ledger ===
>
Opened AC0001 (SAVINGS) for Asha with Rs 25,000
>
Opened AC0002 (CURRENT) for Ravi with Rs 8,000
>
Error: SAVINGS accounts need an opening deposit of at least Rs 1,000
>
Error: account type must be savings or current
>
AC0001 balance: Rs 30,000
>
Declined: AC0001: requested Rs 40,000 but only Rs 30,000 is available (short by Rs 10,000)
>
AC0002 balance: Rs -7,000
>
Declined: AC0002: requested Rs 5,000 but only Rs 3,000 is available (short by Rs 2,000)
>
Transferred Rs 12,000 from AC0001 to AC0002
>
Error: cannot transfer to the same account
>
Error: no account AC0099
>
Error: amount must be positive
>
Error: 'ten' is not a whole number of rupees
>
AC0002 frozen
>
Error: AC0002 is frozen
>
Interest credited: Rs 60
>
AC0002 active again
>
Interest credited: Rs 60
>
Statement for AC0001 (Asha, SAVINGS)
1 opening deposit +25,000 25,000
3 deposit +5,000 30,000
5 transfer to AC0002 -12,000 18,000
7 interest +60 18,060
8 interest +60 18,120
>
Statement for AC0002 (Ravi, CURRENT)
2 opening deposit +8,000 8,000
4 withdrawal -15,000 -7,000
6 transfer from AC0001 +12,000 5,000
>
AC0001 Asha SAVINGS Rs 18,120
AC0002 Ravi CURRENT Rs 5,000
>
Audit passed: ledger matches balances
>
Input
open Asha savings 25000
open Ravi current 8000
open Meera savings 500
open John fixed 9000
deposit AC0001 5000
withdraw AC0001 40000
withdraw AC0002 15000
withdraw AC0002 5000
transfer AC0001 AC0002 12000
transfer AC0001 AC0001 10
transfer AC0001 AC0099 10
deposit AC0001 -5
deposit AC0001 ten
freeze AC0002
deposit AC0002 100
interest
unfreeze AC0002
interest
statement AC0001
statement AC0002
accounts
audit
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Ravi's current account goes to −7,000 using the overdraft; a further 5,000 is declined, short by 2,000.
  • Deposits to a frozen account are refused; interest skips current accounts.
  • The final audit confirms the ledger matches the balances.

Common errors

A transfer debits one account but the credit fails

Validate both sides first, then post both entries; never post before all checks pass.

unreported exception BankException; must be caught or declared

Checked exceptions must be handled or declared with throws — that is the point of making them checked.

Possible improvements

  • Add scheduled transfers and standing instructions
  • Charge a fee for using the overdraft
  • Export statements to CSV

Additional challenges

  1. 1Reverse a transaction by posting compensating entries.
  2. 2Add fixed deposits that pay interest at maturity.
  3. 3Make the bank thread-safe for concurrent transfers.

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