Reading history

Java Project: Bank Account System

8 min read Updated 2 views

Build a bank account system in Java with an abstract class, custom exceptions, records, BigDecimal money, transfers, overdrafts and interest.

In this project you will build a small bank. It uses much of the Java series: an abstract class with two kinds of account, a custom exception, records, BigDecimal for money, an enum, a switch and stream collectors. The bank handles deposits, withdrawals, transfers, overdrafts and monthly interest. It refuses anything that breaks its rules.

In this project you will

  • Design a class hierarchy with an abstract base class
  • Enforce business rules with a custom exception
  • Record history with immutable records and an enum
  • Use BigDecimal for exact money calculations
  • Summarise the bank with streams and collectors

You should know abstract classes, BigDecimal, custom exceptions and collectors.

The Design

Account (abstract)number, owner, balance, historydeposit(), withdraw()abstract minimumBalance()SavingsAccountminimumBalance() = 500addMonthlyInterest()CurrentAccountminimumBalance() = -5000BankMap of accountsfind(), transfer()Transaction (record)seq, type, amount,balanceAfterhashasOpen triangle = “extends”; arrows = “holds”
  • Account (abstract) holds the number, owner, balance and history, and implements deposit and withdraw once for all account types.
  • SavingsAccount must keep at least 500 taka and earns monthly interest.
  • CurrentAccount allows an overdraft down to −5,000 taka.
  • Bank stores accounts in a map and performs transfers.
  • Transaction is a record, so history entries can never be edited after they are written.

The Complete Program

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.*;

public class Main {
    // ----- exceptions -----
    static class BankException extends Exception {
        BankException(String msg) { super(msg); }
    }

    // ----- transactions are immutable records -----
    enum Type { DEPOSIT, WITHDRAW, TRANSFER_IN, TRANSFER_OUT, INTEREST }
    record Transaction(int seq, Type type, BigDecimal amount, BigDecimal balanceAfter) {}

    // ----- abstract base class -----
    static abstract class Account {
        private static int nextSeq = 1;
        private final String number, owner;
        protected BigDecimal balance = BigDecimal.ZERO;
        private final List<Transaction> history = new ArrayList<>();

        Account(String number, String owner) { this.number = number; this.owner = owner; }
        String number() { return number; }
        String owner()  { return owner; }
        BigDecimal balance() { return balance; }
        List<Transaction> history() { return Collections.unmodifiableList(history); }

        abstract BigDecimal minimumBalance();
        abstract String kind();

        void deposit(BigDecimal amt) throws BankException { change(amt, Type.DEPOSIT); }

        void withdraw(BigDecimal amt) throws BankException {
            checkCanTakeOut(amt);
            change(amt.negate(), Type.WITHDRAW);
        }

        void checkCanTakeOut(BigDecimal amt) throws BankException {
            if (balance.subtract(amt).compareTo(minimumBalance()) < 0)
                throw new BankException(kind() + " " + number + ": cannot go below " + minimumBalance());
        }

        protected void change(BigDecimal amt, Type type) throws BankException {
            if (amt.signum() == 0) throw new BankException("Amount must not be zero");
            if (type == Type.DEPOSIT && amt.signum() < 0) throw new BankException("Deposit must be positive");
            balance = balance.add(amt);
            history.add(new Transaction(nextSeq++, type, amt.abs(), balance));
        }
    }

    static class SavingsAccount extends Account {
        private final BigDecimal rate;   // yearly rate, e.g. 0.06
        SavingsAccount(String n, String o, BigDecimal rate) { super(n, o); this.rate = rate; }
        BigDecimal minimumBalance() { return new BigDecimal("500"); }
        String kind() { return "Savings"; }
        void addMonthlyInterest() throws BankException {
            BigDecimal interest = balance.multiply(rate)
                .divide(new BigDecimal("12"), 2, RoundingMode.HALF_UP);
            change(interest, Type.INTEREST);
        }
    }

    static class CurrentAccount extends Account {
        CurrentAccount(String n, String o) { super(n, o); }
        BigDecimal minimumBalance() { return new BigDecimal("-5000"); }   // overdraft allowed
        String kind() { return "Current"; }
    }

    // ----- the bank -----
    static class Bank {
        private final Map<String, Account> accounts = new LinkedHashMap<>();
        void open(Account a) { accounts.put(a.number(), a); }

        Account find(String no) throws BankException {
            Account a = accounts.get(no);
            if (a == null) throw new BankException("No account " + no);
            return a;
        }

        void transfer(String from, String to, BigDecimal amt) throws BankException {
            Account a = find(from), b = find(to);
            a.checkCanTakeOut(amt);          // throws before anything changes if not allowed
            a.change(amt.negate(), Type.TRANSFER_OUT);
            b.change(amt, Type.TRANSFER_IN);
        }

        Collection<Account> all() { return accounts.values(); }
    }

    static BigDecimal tk(String s) { return new BigDecimal(s); }

    public static void main(String[] args) {
        Bank bank = new Bank();
        SavingsAccount s1 = new SavingsAccount("S-101", "Nusrat", tk("0.06"));
        CurrentAccount c1 = new CurrentAccount("C-201", "Karim Traders");
        bank.open(s1);
        bank.open(c1);

        String[][] actions = {
            {"deposit", "S-101", "20000"}, {"deposit", "C-201", "3000"},
            {"withdraw", "S-101", "19800"},              // would leave 200 < 500
            {"withdraw", "C-201", "7000"},               // overdraft to -4000 is allowed
            {"transfer", "S-101", "C-201", "5000"},
            {"withdraw", "C-201", "2000"},
            {"withdraw", "C-201", "4500"},               // would reach -5500, past the overdraft limit
            {"deposit", "X-999", "100"},                 // unknown account
            {"deposit", "S-101", "0"}};

        for (String[] act : actions) {
            try {
                switch (act[0]) {
                    case "deposit"  -> bank.find(act[1]).deposit(tk(act[2]));
                    case "withdraw" -> bank.find(act[1]).withdraw(tk(act[2]));
                    case "transfer" -> bank.transfer(act[1], act[2], tk(act[3]));
                }
                System.out.println("OK      " + String.join(" ", act));
            } catch (BankException e) {
                System.out.println("REFUSED " + String.join(" ", act) + " -> " + e.getMessage());
            }
        }

        try { s1.addMonthlyInterest(); } catch (BankException e) { System.out.println(e.getMessage()); }

        System.out.println();
        for (Account a : bank.all()) {
            System.out.printf("%-8s %-6s %-14s balance %10s%n", a.kind(), a.number(), a.owner(), a.balance());
            for (Transaction t : a.history())
                System.out.printf("   #%d %-12s %10s -> %10s%n", t.seq(), t.type(), t.amount(), t.balanceAfter());
        }

        BigDecimal total = bank.all().stream().map(Account::balance).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<Type, Long> counts = bank.all().stream().flatMap(a -> a.history().stream())
            .collect(Collectors.groupingBy(Transaction::type, () -> new EnumMap<>(Type.class), Collectors.counting()));
        System.out.println("\nTotal held by the bank: " + total);
        System.out.println("Transactions by type : " + counts);
    }
}

Output

OK      deposit S-101 20000
OK      deposit C-201 3000
REFUSED withdraw S-101 19800 -> Savings S-101: cannot go below 500
OK      withdraw C-201 7000
OK      transfer S-101 C-201 5000
OK      withdraw C-201 2000
REFUSED withdraw C-201 4500 -> Current C-201: cannot go below -5000
REFUSED deposit X-999 100 -> No account X-999
REFUSED deposit S-101 0 -> Amount must not be zero

Savings  S-101  Nusrat         balance   15075.00
   #1 DEPOSIT           20000 ->      20000
   #4 TRANSFER_OUT       5000 ->      15000
   #7 INTEREST          75.00 ->   15075.00
Current  C-201  Karim Traders  balance      -1000
   #2 DEPOSIT            3000 ->       3000
   #3 WITHDRAW           7000 ->      -4000
   #5 TRANSFER_IN        5000 ->       1000
   #6 WITHDRAW           2000 ->      -1000

Total held by the bank: 14075.00
Transactions by type : {DEPOSIT=2, WITHDRAW=2, TRANSFER_IN=1, TRANSFER_OUT=1, INTEREST=1}

How It Works

  • Polymorphism: withdraw is written once in Account. It calls minimumBalance(), and each subclass gives a different answer. So a savings account cannot drop below 500, while a current account may go below zero, down to −5,000.
  • Validate before changing: checkCanTakeOut runs before any balance changes, so a refused transfer leaves both accounts untouched.
  • Exceptions as rules: every refusal throws BankException. It is checked, so the compiler makes the caller handle it. The loop catches it, prints why, and goes on.
  • Money: BigDecimal avoids floating-point errors. Monthly interest at 6% a year on 15,000 is 15,000 × 0.06 ÷ 12 = 75.00, rounded HALF_UP to 2 decimal places.
  • History: each change adds a Transaction record with a number that counts up across the whole bank. This shows the order of events. Collections.unmodifiableList stops other code from editing the list.
  • Reports: reduce adds up all balances. groupingBy counts transactions by type, and the EnumMap keeps the types in enum order.

Ideas to Extend the Project

  • Add a FixedDepositAccount that refuses withdrawals before a maturity date, using the Date-Time API.
  • Make the bank thread-safe so two transfers can run at once, with ReentrantLock or synchronized, always locking accounts in the same order to avoid deadlock.
  • Save accounts and history to a file and load them again at start-up.
  • Add a monthly statement method that prints opening balance, each transaction and closing balance.

Common Mistakes

  1. Using double for money, which produces values like 0.30000000000000004.
  2. Changing one account before checking the other side of a transfer, which can leave money half-moved.
  3. Returning the real history list, letting outside code delete records.
  4. Comparing BigDecimal with equals; 75.0 and 75.00 are not “equal”. Use compareTo.

Practice Exercises

Exercise 1. In the program’s data, why was the withdrawal of 4,500 from C-201 refused?

Show answer

C-201 had −1,000. Taking 4,500 more would give −5,500, below the current account’s limit of −5,000.

Exercise 2. Add a method to Bank that returns all accounts with a negative balance.

Show answer
List<Account> overdrawn() {
    return accounts.values().stream()
        .filter(a -> a.balance().signum() < 0)
        .toList();
}
// With the sample data it returns only C-201 (balance -1000).

Frequently Asked Questions

Why is BankException checked rather than unchecked?

A refused withdrawal is a normal event that the caller should always handle, for example by showing a message. A checked exception makes the compiler enforce that. Bugs, such as a null account number, are better as unchecked exceptions.

Why use records for transactions instead of a normal class?

A record gives an immutable data class with a constructor, accessors, equals, hashCode and toString in one line. Immutability suits history, which should never change once written.

Summary

  • An abstract base class holds shared logic; subclasses supply the rules that differ.
  • Check every rule before changing state, and signal refusals with a custom exception.
  • Use BigDecimal for money and records for immutable history.
  • Streams and collectors turn the data into reports.

Next: Java Math Class and Random Numbers.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *