Java Bank App
A Java bank app manages accounts that hold money: opening accounts, deposits, withdrawals, transfers, interest and statements. Money has strict rules, so this project teaches three things that matter in every financial system: exact decimal arithmetic with BigDecimal, refusing invalid operations without changing any data, and keeping balances correct when many threads use the same account at once.
It follows the Java Library System. You build the bank from small classes, test each rule, and finish with bank-app.jar, a command-driven console bank with savings and current accounts, transfers, monthly interest and printed statements. All examples were run on JDK 21.
Handle Money in Java With BigDecimal
As shown in the Java Calculator App, double cannot store values like 0.10 exactly. The bank stores every amount as a BigDecimal with exactly two decimal places (rupees and paise). One helper method validates every amount that enters the system.
/** Amounts must be positive and have at most two decimal places (rupees and paise). */
static BigDecimal validate(BigDecimal amount) {
if (amount == null || amount.signum() <= 0) {
throw new BankException("Amount must be positive");
}
if (amount.stripTrailingZeros().scale() > 2) {
throw new BankException("Amount cannot have more than 2 decimal places: " + amount);
}
return amount.setScale(2, RoundingMode.UNNECESSARY);
}
package com.gocourse.bank;
import java.math.BigDecimal;
public class MoneyDemo {
public static void main(String[] args) {
// equals() compares value AND scale; compareTo() compares only the value
BigDecimal a = new BigDecimal("100.5");
BigDecimal b = new BigDecimal("100.50");
System.out.println("equals: " + a.equals(b) + ", compareTo: " + a.compareTo(b));
String[] inputs = {"250", "99.9", "10.25", "0.005", "-50", "0"};
for (String text : inputs) {
try {
System.out.println(text + " -> " + Account.validate(new BigDecimal(text)));
} catch (BankException e) {
System.out.println(text + " -> rejected: " + e.getMessage());
}
}
}
}
equals: false, compareTo: 0
250 -> 250.00
99.9 -> 99.90
10.25 -> 10.25
0.005 -> rejected: Amount cannot have more than 2 decimal places: 0.005
-50 -> rejected: Amount must be positive
0 -> rejected: Amount must be positive
BigDecimal method | Use in the bank |
|---|---|
signum() | -1, 0 or 1: is the amount positive? |
scale() | Number of decimal places |
setScale(2, ...) | Always store two decimal places |
compareTo(other) | Compare values (< 0, 0, > 0) |
add, subtract, multiply, divide | Arithmetic; each returns a new object |
How it works:
equalstreats100.5and100.50as different because their scales differ. Always compare money withcompareTo, which compares only the value.stripTrailingZeros()turns10.50into10.5before the scale check, so10.50is accepted but0.005(three decimals) is rejected.RoundingMode.UNNECESSARYmeans "this must not need rounding". The earlier check guarantees it, and if a bug ever slipped through, Java would throw instead of silently losing paise.
Create the Account Class With Deposit and Withdraw
Each account type has its own rules, stored in an enum. A savings account must keep at least ₹1,000 and earns 3.5% a year; a current account can go down to zero and earns nothing.
package com.gocourse.bank;
import java.math.BigDecimal;
public enum AccountType {
SAVINGS(new BigDecimal("1000.00"), new BigDecimal("0.035")), // 3.5% a year
CURRENT(new BigDecimal("0.00"), BigDecimal.ZERO);
private final BigDecimal minimumBalance;
private final BigDecimal annualInterestRate;
AccountType(BigDecimal minimumBalance, BigDecimal annualInterestRate) {
this.minimumBalance = minimumBalance;
this.annualInterestRate = annualInterestRate;
}
public BigDecimal minimumBalance() { return minimumBalance; }
public BigDecimal annualInterestRate() { return annualInterestRate; }
}
package com.gocourse.bank;
/** A banking rule blocked the operation; the account is unchanged. */
public class BankException extends RuntimeException {
public BankException(String message) {
super(message);
}
}
package com.gocourse.bank;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/** One line of the passbook. Amount is positive for money in, negative for money out. */
public record Transaction(LocalDateTime time, String description, BigDecimal amount, BigDecimal balanceAfter) { }
package com.gocourse.bank;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/** A bank account. Every method that touches the balance is synchronized. */
public class Account {
private final String number;
private final String holder;
private final AccountType type;
private final Clock clock;
private final List<Transaction> history = new ArrayList<>();
private BigDecimal balance = new BigDecimal("0.00");
Account(String number, String holder, AccountType type, Clock clock) {
this.number = number;
this.holder = holder;
this.type = type;
this.clock = clock;
}
public synchronized void deposit(BigDecimal amount, String description) {
BigDecimal money = validate(amount);
balance = balance.add(money);
record(description, money);
}
public synchronized void withdraw(BigDecimal amount, String description) {
BigDecimal money = validate(amount);
BigDecimal newBalance = balance.subtract(money);
if (newBalance.compareTo(type.minimumBalance()) < 0) {
throw new BankException("Insufficient funds in " + number + ": balance " + balance
+ ", minimum " + type.minimumBalance() + ", requested " + money);
}
balance = newBalance;
record(description, money.negate());
}
/** Adds one month of interest: balance x yearly rate / 12, rounded to paise. */
public synchronized BigDecimal addMonthlyInterest() {
BigDecimal interest = balance.multiply(type.annualInterestRate())
.divide(BigDecimal.valueOf(12), 2, RoundingMode.HALF_EVEN);
if (interest.signum() > 0) {
balance = balance.add(interest);
record("Interest", interest);
}
return interest;
}
public synchronized BigDecimal balance() {
return balance;
}
public synchronized List<Transaction> history() {
return List.copyOf(history);
}
public String number() { return number; }
public String holder() { return holder; }
public AccountType type() { return type; }
private void record(String description, BigDecimal signedAmount) {
history.add(new Transaction(LocalDateTime.now(clock), description, signedAmount, balance));
}
/** Amounts must be positive and have at most two decimal places (rupees and paise). */
static BigDecimal validate(BigDecimal amount) {
if (amount == null || amount.signum() <= 0) {
throw new BankException("Amount must be positive");
}
if (amount.stripTrailingZeros().scale() > 2) {
throw new BankException("Amount cannot have more than 2 decimal places: " + amount);
}
return amount.setScale(2, RoundingMode.UNNECESSARY);
}
}
How it works:
withdrawcalculatesnewBalancefirst and checks it against the minimum. Only if the check passes does it changebalance. A refused withdrawal leaves the account exactly as it was.- Every successful change calls
record, which adds aTransactionwith the time, a signed amount and the balance after. This is the passbook. - The time comes from an injected
Clockinstead ofLocalDateTime.now(). Real code uses the system clock; demos and tests use a fixed clock so the output is repeatable. history()returnsList.copyOf(...), so nobody can add fake transactions from outside.- The constructor is package-private. Accounts can only be created through the
Bank, which assigns account numbers and checks the opening deposit.
Open Accounts and Move Money With the Bank Class
package com.gocourse.bank;
import java.math.BigDecimal;
import java.time.Clock;
import java.util.Collection;
import java.util.List;
import java.util.LinkedHashMap;
import java.util.Map;
/** Opens accounts and moves money between them. */
public class Bank {
private final Map<String, Account> accounts = new LinkedHashMap<>();
private final Clock clock;
private int nextNumber = 1001;
public Bank(Clock clock) {
this.clock = clock;
}
public synchronized Account open(String holder, AccountType type, BigDecimal openingDeposit) {
Account.validate(openingDeposit);
if (openingDeposit.compareTo(type.minimumBalance()) < 0) {
throw new BankException(type + " needs an opening deposit of at least " + type.minimumBalance());
}
Account account = new Account("GC" + nextNumber++, holder, type, clock);
account.deposit(openingDeposit, "Opening deposit");
accounts.put(account.number(), account);
return account;
}
public synchronized Account find(String number) {
Account account = accounts.get(number.toUpperCase());
if (account == null) throw new BankException("No account " + number);
return account;
}
public synchronized Collection<Account> accounts() {
return List.copyOf(accounts.values());
}
public void transfer(String fromNumber, String toNumber, BigDecimal amount) {
Account from = find(fromNumber);
Account to = find(toNumber);
if (from == to) throw new BankException("Cannot transfer to the same account");
// always lock the lower account number first, so two opposite transfers cannot deadlock
Account first = from.number().compareTo(to.number()) < 0 ? from : to;
Account second = first == from ? to : from;
synchronized (first) {
synchronized (second) {
from.withdraw(amount, "Transfer to " + to.number()); // throws if not enough money
to.deposit(amount, "Transfer from " + from.number());
}
}
}
}
Deposits, Withdrawals and a Passbook
package com.gocourse.bank;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
public class AccountDemo {
public static void main(String[] args) {
// a fixed clock makes every timestamp the same, so the output is repeatable
Clock clock = Clock.fixed(Instant.parse("2026-11-18T04:30:00Z"), ZoneId.of("Asia/Kolkata"));
Bank bank = new Bank(clock);
Account savings = bank.open("Anitha", AccountType.SAVINGS, new BigDecimal("5000"));
savings.deposit(new BigDecimal("2500.75"), "Salary");
savings.withdraw(new BigDecimal("1200"), "ATM withdrawal");
System.out.println(savings.number() + " balance: " + savings.balance());
try {
savings.withdraw(new BigDecimal("5500"), "Rent");
} catch (BankException e) {
System.out.println("Refused: " + e.getMessage());
}
System.out.println("Balance unchanged: " + savings.balance());
try {
bank.open("Vikram", AccountType.SAVINGS, new BigDecimal("500"));
} catch (BankException e) {
System.out.println("Refused: " + e.getMessage());
}
System.out.println("Passbook:");
for (Transaction t : savings.history()) {
System.out.printf(" %s %-16s %10s %10s%n", t.time(), t.description(), t.amount(), t.balanceAfter());
}
}
}
GC1001 balance: 6300.75
Refused: Insufficient funds in GC1001: balance 6300.75, minimum 1000.00, requested 5500.00
Balance unchanged: 6300.75
Refused: SAVINGS needs an opening deposit of at least 1000.00
Passbook:
2026-11-18T10:00 Opening deposit 5000.00 5000.00
2026-11-18T10:00 Salary 2500.75 7500.75
2026-11-18T10:00 ATM withdrawal -1200.00 6300.75
How it works:
Clock.fixed(...)freezes time at 04:30 UTC, which is 10:00 in India (Asia/Kolkata). Every transaction shows the same timestamp.- Withdrawing ₹5,500 would leave ₹800, below the ₹1,000 savings minimum, so it is refused and the balance stays at ₹6,300.75.
- The passbook shows withdrawals as negative amounts, so the running balance is easy to follow line by line.
Transfers That Never Lose Money
A transfer is two steps: take money from one account and add it to another. Both must happen, or neither.
package com.gocourse.bank;
import java.math.BigDecimal;
import java.time.Clock;
public class TransferDemo {
public static void main(String[] args) {
Bank bank = new Bank(Clock.systemDefaultZone());
Account anitha = bank.open("Anitha", AccountType.SAVINGS, new BigDecimal("5000"));
Account shop = bank.open("Ravi Stores", AccountType.CURRENT, new BigDecimal("200"));
bank.transfer("GC1001", "GC1002", new BigDecimal("1500"));
System.out.println("After transfer: " + anitha.balance() + " / " + shop.balance());
try {
bank.transfer("GC1001", "GC1002", new BigDecimal("3000")); // would leave 500 < 1000
} catch (BankException e) {
System.out.println("Refused: " + e.getMessage());
}
System.out.println("Unchanged: " + anitha.balance() + " / " + shop.balance());
bank.transfer("gc1002", "gc1001", new BigDecimal("1700")); // CURRENT may go down to 0
System.out.println("Shop emptied: " + anitha.balance() + " / " + shop.balance());
BigDecimal total = anitha.balance().add(shop.balance());
System.out.println("Money in the bank is still " + total);
}
}
After transfer: 3500.00 / 1700.00
Refused: Insufficient funds in GC1001: balance 3500.00, minimum 1000.00, requested 3000.00
Unchanged: 3500.00 / 1700.00
Shop emptied: 5200.00 / 0.00
Money in the bank is still 5200.00
How it works:
transfercallswithdrawfirst. If it throws, thedepositline never runs, so a failed transfer changes neither account.finduppercases the number, sogc1002works the same asGC1002.- The current account can be emptied to
0.00because its minimum balance is zero. - The total of both accounts is the same before and after every transfer. Checking this kind of invariant is a powerful way to test financial code.
Make the Java Bank App Thread-Safe
A real bank serves many customers at the same moment. Without protection, two threads can read the same old balance, both add to it, and one update is lost. The synchronized keyword, explained in Java Synchronization, lets only one thread at a time run a method on the same account.
package com.gocourse.bank;
import java.math.BigDecimal;
import java.time.Clock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrencyDemo {
public static void main(String[] args) {
Bank bank = new Bank(Clock.systemDefaultZone());
Account a = bank.open("Account A", AccountType.CURRENT, new BigDecimal("10000"));
Account b = bank.open("Account B", AccountType.CURRENT, new BigDecimal("10000"));
BigDecimal one = new BigDecimal("1.00");
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) {
pool.submit(() -> a.deposit(one, "Cashback")); // 1000 x 1.00 into A
pool.submit(() -> bank.transfer("GC1001", "GC1002", one)); // A -> B
pool.submit(() -> bank.transfer("GC1002", "GC1001", one)); // B -> A
}
} // close() waits for all 3000 tasks to finish
System.out.println("A: " + a.balance());
System.out.println("B: " + b.balance());
System.out.println("Total: " + a.balance().add(b.balance()));
System.out.println("Transactions on A: " + a.history().size());
}
}
A: 11000.00
B: 10000.00
Total: 21000.00
Transactions on A: 3001
How it works:
- The program starts 3,000 tasks on virtual threads: 1,000 deposits into A and 1,000 transfers in each direction. Try-with-resources closes the executor, which waits until every task is done.
- A ends with exactly 10,000 + 1,000 = 11,000, and the transfers cancel out. The output is the same on every run because no update is lost.
- A has 3,001 transactions: the opening deposit, 1,000 deposits and 2,000 transfer lines.
transfermust lock two accounts. If one thread locked A then B while another locked B then A, each could wait for the other forever, a deadlock. Locking the lower account number first gives every thread the same order, so a deadlock cannot happen.
Note:
synchronizedmethods lock onthis, and thesynchronized (first)blocks inBank.transferlock the same account objects. Because Java locks are re-entrant, a thread that already holds an account's lock can call its synchronizedwithdrawanddepositwithout blocking itself.
Calculate Monthly Interest Correctly
Savings interest is calculated monthly as balance x yearly rate / 12, rounded to paise. Banks use HALF_EVEN (banker's rounding), which rounds a tie such as 0.125 to the nearest even digit, so over many rounds the errors balance out instead of always going up.
package com.gocourse.bank;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Clock;
public class InterestDemo {
public static void main(String[] args) {
Bank bank = new Bank(Clock.systemDefaultZone());
Account savings = bank.open("Meera", AccountType.SAVINGS, new BigDecimal("125000.00"));
Account current = bank.open("Meera Traders", AccountType.CURRENT, new BigDecimal("80000.00"));
for (int month = 1; month <= 3; month++) {
BigDecimal interest = savings.addMonthlyInterest();
System.out.printf("Month %d: interest %7s, balance %s%n", month, interest, savings.balance());
}
System.out.println("Current account interest: " + current.addMonthlyInterest());
// the raw value before rounding, for comparison
BigDecimal raw = new BigDecimal("125000.00").multiply(new BigDecimal("0.035"))
.divide(BigDecimal.valueOf(12), 10, RoundingMode.HALF_EVEN);
System.out.println("Month 1 before rounding: " + raw);
}
}
Month 1: interest 364.58, balance 125364.58
Month 2: interest 365.65, balance 125730.23
Month 3: interest 366.71, balance 126096.94
Current account interest: 0.00
Month 1 before rounding: 364.5833333333
How it works:
divide(BigDecimal.valueOf(12), 2, RoundingMode.HALF_EVEN)divides and rounds to two decimals in one step. Without a scale,BigDecimalwould throw, because the exact result has endless digits.- Interest is added to the balance, so month 2 earns interest on month 1's interest. This is monthly compounding.
- The current account's rate is zero, so it earns
0.00andaddMonthlyInterestadds no transaction line.
Real-World Example: Run bank-app.jar From the Console
BankApp reads commands, calls the Bank, and turns every exception into a friendly message.
package com.gocourse.bank;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
/** Console bank: java -jar bank-app.jar [--fixed-time 2026-11-18T10:00] */
public class BankApp {
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("dd MMM HH:mm");
private final Bank bank;
BankApp(Bank bank) {
this.bank = bank;
}
public static void main(String[] args) {
Clock clock = Clock.systemDefaultZone();
if (args.length == 2 && args[0].equals("--fixed-time")) { // repeatable demos and tests
ZoneId zone = ZoneId.systemDefault();
clock = Clock.fixed(LocalDateTime.parse(args[1]).atZone(zone).toInstant(), zone);
}
new BankApp(new Bank(clock)).run();
}
void run() {
System.out.println("GOCOURSE Bank. Commands: open, deposit, withdraw, transfer, statement, accounts, interest, exit");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("bank> ");
if (!scanner.hasNextLine()) return;
String[] p = scanner.nextLine().strip().split("\\s+", 4);
try {
switch (p[0].toLowerCase()) {
case "" -> { }
case "open" -> { // open SAVINGS 5000 Anitha Raj
need(p, 4, "open <SAVINGS|CURRENT> <amount> <name>");
Account acc = bank.open(p[3], accountType(p[1]), money(p[2]));
System.out.println("Opened " + acc.number() + " for " + acc.holder() + ", balance " + acc.balance());
}
case "deposit" -> {
need(p, 3, "deposit <account> <amount>");
Account acc = bank.find(p[1]);
acc.deposit(money(p[2]), "Cash deposit");
System.out.println("New balance " + acc.balance());
}
case "withdraw" -> {
need(p, 3, "withdraw <account> <amount>");
Account acc = bank.find(p[1]);
acc.withdraw(money(p[2]), "Cash withdrawal");
System.out.println("New balance " + acc.balance());
}
case "transfer" -> {
need(p, 4, "transfer <from> <to> <amount>");
bank.transfer(p[1], p[2], money(p[3]));
System.out.println("Transferred " + money(p[3]) + " from " + p[1].toUpperCase()
+ " to " + p[2].toUpperCase());
}
case "statement" -> {
need(p, 2, "statement <account>");
printStatement(bank.find(p[1]));
}
case "accounts" -> bank.accounts().forEach(a -> System.out.printf(
"%s %-8s %-14s %12s%n", a.number(), a.type(), a.holder(), a.balance()));
case "interest" -> bank.accounts().forEach(a -> {
BigDecimal interest = a.addMonthlyInterest();
if (interest.signum() > 0) System.out.println(a.number() + " earned " + interest);
});
case "exit" -> {
System.out.println("Goodbye!");
return;
}
default -> System.out.println("Unknown command: " + p[0]);
}
} catch (NumberFormatException e) {
System.out.println("Error: not a valid amount");
} catch (BankException | IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
private static AccountType accountType(String text) {
try {
return AccountType.valueOf(text.toUpperCase());
} catch (IllegalArgumentException e) {
throw new BankException("Account type must be SAVINGS or CURRENT, not " + text);
}
}
private static BigDecimal money(String text) {
return new BigDecimal(text.replace(",", "")); // accept 1,500.00 as well as 1500
}
private static void need(String[] parts, int count, String usage) {
if (parts.length < count) throw new IllegalArgumentException("Usage: " + usage);
}
private static void printStatement(Account acc) {
System.out.println("Statement for " + acc.number() + " (" + acc.holder() + ", " + acc.type() + ")");
System.out.printf("%-12s %-22s %10s %10s%n", "Date", "Description", "Amount", "Balance");
for (Transaction t : acc.history()) {
System.out.printf("%-12s %-22s %10s %10s%n",
t.time().format(TIME), t.description(), t.amount(), t.balanceAfter());
}
}
}
bank-app/
└── src/
└── com/
└── gocourse/
└── bank/
├── Account.java
├── AccountType.java
├── Bank.java
├── BankApp.java
├── BankException.java
└── Transaction.java
cd bank-app
javac -d out src/com/gocourse/bank/*.java
jar --create --file bank-app.jar --main-class com.gocourse.bank.BankApp -C out .
java -jar bank-app.jar --fixed-time 2026-11-18T10:00
GOCOURSE Bank. Commands: open, deposit, withdraw, transfer, statement, accounts, interest, exit
bank> open SAVINGS 5000 Anitha Raj
Opened GC1001 for Anitha Raj, balance 5000.00
bank> open CURRENT 2,000 Ravi Stores
Opened GC1002 for Ravi Stores, balance 2000.00
bank> open SAVINGS 500 Vikram
Error: SAVINGS needs an opening deposit of at least 1000.00
bank> open FIXED 9000 Vikram
Error: Account type must be SAVINGS or CURRENT, not FIXED
bank> deposit gc1001 12500.50
New balance 17500.50
bank> withdraw GC1001 6000
New balance 11500.50
bank> withdraw GC1001 10.555
Error: Amount cannot have more than 2 decimal places: 10.555
bank> transfer GC1001 GC1002 3499.50
Transferred 3499.50 from GC1001 to GC1002
bank> transfer GC1001 GC1002 9000
Error: Insufficient funds in GC1001: balance 8001.00, minimum 1000.00, requested 9000.00
bank> transfer GC1002 GC1009 100
Error: No account GC1009
bank> deposit GC1002 abc
Error: not a valid amount
bank> interest
GC1001 earned 23.34
bank> accounts
GC1001 SAVINGS Anitha Raj 8024.34
GC1002 CURRENT Ravi Stores 5499.50
bank> statement GC1001
Statement for GC1001 (Anitha Raj, SAVINGS)
Date Description Amount Balance
18 Nov 10:00 Opening deposit 5000.00 5000.00
18 Nov 10:00 Cash deposit 12500.50 17500.50
18 Nov 10:00 Cash withdrawal -6000.00 11500.50
18 Nov 10:00 Transfer to GC1002 -3499.50 8001.00
18 Nov 10:00 Interest 23.34 8024.34
bank> exit
Goodbye!
How it works:
- Friendly input.
2,000is accepted becausemoneyremoves commas, andgc1001matchesGC1001. - Every rule enforced. A low opening deposit, an unknown account type, three-decimal amounts, insufficient funds, an unknown account and a non-number are all refused with a specific message, and no balance changes.
- Atomic transfer. ₹3,499.50 left GC1001 and arrived in GC1002 as a single operation. The ₹9,000 transfer failed before any money moved.
- Interest only where it applies. GC1001 earned
8001.00 x 0.035 / 12 = 23.34(rounded from 23.336...). The current account earned nothing, so it is not listed. - A complete statement. Every successful operation appears once, with a signed amount and the running balance, while refused operations leave no trace.
- Repeatable runs.
--fixed-timefreezes the clock, so the statement can be compared with an expected file in automated tests, just like--seedin the Java Number Guess Game.
The next project, the Java Todo App, applies the same command-driven design to tasks with priorities, due dates and a save file.