Capstone: a bank account
The object part ends with a bank: accounts with a balance in cents, a withdrawal that can be refused, a transfer that uses it, a statement and a total. It is the same kind of program as lesson 033 was for arrays and strings, and it uses every idea of the part: classes, constructors, private fields, methods that return a value, and a class that holds an array of other objects.
The model
Account has an owner and a balance in cents, and it offers a deposit, a withdrawal that answers whether it happened and a transfer that uses the withdrawal. Bank owns an array of accounts, opens them and produces the statement and the total.
The money is an int of cents for the reason lesson 009 gave: a double cannot hold 0.10 exactly, and a bank that loses a cent per operation is not a bank. The formatting to 80.00 happens once, in toString.
Accounts in cents
The file Bank.java holds both classes. The account methods are the ones of lesson 035 and 038: private state, a check before a change, and a boolean that reports an expected failure.
public class Bank {
private final Account[] accounts = new Account[10];
private int size;
Account open(String owner, int cents) {
Account account = new Account(owner, cents);
accounts[size++] = account;
return account;
}
int total() {
int total = 0;
for (int i = 0; i < size; i++) {
total += accounts[i].balance();
}
return total;
}
String statement() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++) {
builder.append(accounts[i]).append('\n');
}
return builder.toString();
}
public static void main(String[] args) {
Bank bank = new Bank();
Account ada = bank.open("Ada", 10000);
Account grace = bank.open("Grace", 5000);
ada.withdraw(2500);
grace.deposit(1000);
System.out.println("transfer: " + ada.transferTo(grace, 1500));
System.out.println("big transfer: " + ada.transferTo(grace, 999999));
System.out.print(bank.statement());
System.out.println("total: " + bank.total());
}
}
class Account {
private final String owner;
private int balance;
Account(String owner, int balance) {
this.owner = owner;
this.balance = balance;
}
void deposit(int amount) {
balance += amount;
}
boolean withdraw(int amount) {
if (amount > balance) {
return false;
}
balance -= amount;
return true;
}
boolean transferTo(Account other, int amount) {
if (!withdraw(amount)) {
return false;
}
other.deposit(amount);
return true;
}
int balance() {
return balance;
}
@Override
public String toString() {
return String.format("%-6s %d.%02d", owner, balance / 100, balance % 100);
}
}
javac -Xlint:all Bank.java
java Bank
transfer: true
big transfer: false
Ada 60.00
Grace 75.00
total: 13500
A transfer
The first transfer moves 1500 cents from Ada to Grace and answers true. The second asks for 999999 cents, the withdrawal fails, the method returns false before the deposit, and no account changes. That order is the whole safety of the operation: the money leaves one account only if it can, and it arrives in the other.
The transfer is not atomic against a failure between the two calls; a database transaction is what makes it atomic across a crash, and this program is one thread that cannot crash between two lines. Lesson 099 and the concurrency part return to the question at the level a program can answer.
The statement
String.format("%-6s %d.%02d", ...) pads the owner to six characters on the left-aligned side and writes the balance as dollars and cents. The two accounts print with the same columns because the format is one string in one method, which is the lesson of lesson 026 in a place where it matters.
The statement ends with a newline, so System.out.print is enough and the total line follows the last account without a blank line. A person reading the output can check the two balances and the total from the numbers on the page.
The totals
Ada starts at 10000, withdraws 2500 and transfers 1500: 10000 - 2500 - 1500 = 6000, which is 60.00. Grace starts at 5000, deposits 1000 and receives 1500: 7500, which is 75.00. The sum is 13500, and the program prints the cents of the first total, not a formatted amount, which is the one line of the output that does not match the statement.
The arithmetic is checked by hand on the page because a capstone that only looks plausible is not checked at all. Every number above comes from the run, and the two balances plus the total agree with the operations listed in main.
Exercises
- Add a method that returns the account with the largest balance and print its owner.
- Change the statement to show the balance in a column of ten characters.
- Make a transfer of the whole balance succeed and one of one cent more fail, and check the total after both.
- Add an interest(int percent) method and round the result to the nearest cent.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does the account store cents in an int?
Answer
An int is exact, while a double cannot hold 0.10 exactly
Money arithmetic must add up, and a binary double cannot represent most decimal amounts exactly.
-
What does
transferTodo when the withdrawal fails?Answer
It returns false before depositing anything
The deposit comes after the successful withdrawal, so a refusal leaves both accounts alone.
-
What does
%-6sdo in the statement format?Answer
Pads the name to six characters on the right
The minus flag left-aligns the field, so the padding goes after the text.
-
What does this program print?
public class Q1 { public static void main(String[] args) { A a = new A(100); a.deposit(50); a.withdraw(30); System.out.println(a.balance); } } class A { int balance; A(int balance) { this.balance = balance; } void deposit(int amount) { balance += amount; } void withdraw(int amount) { if (amount <= balance) { balance -= amount; } } }Answer
120
The balance is 100 plus 50 minus 30, which is 120.
-
What does this program print?
public class Q2 { public static void main(String[] args) { A a = new A(100); boolean ok = a.withdraw(150); System.out.println(ok + " " + a.balance); } } class A { int balance; A(int balance) { this.balance = balance; } boolean withdraw(int amount) { if (amount > balance) { return false; } balance -= amount; return true; } }Answer
false 100
The withdrawal is refused before the subtraction, so the balance stays at 100.
-
What does this program print?
public class Q3 { public static void main(String[] args) { A a = new A(1000); System.out.println(a + " " + a.balance()); } } class A { private final int balance; A(int balance) { this.balance = balance; } int balance() { return balance; } @Override public String toString() { return String.format("%d.%02d", balance / 100, balance % 100); } }Answer
10.00 1000
The override formats the cents, and the accessor returns the raw number of cents.
-
What does this program print?
public class Q4 { public static void main(String[] args) { A a = new A(1250); System.out.println(a); } } class A { private final int balance; A(int balance) { this.balance = balance; } @Override public String toString() { return String.format("%d.%02d", balance / 100, balance % 100); } }Answer
12.50
The division gives 12 and the remainder 50, formatted with two digits after the point.
-
What does this program print?
public class Q5 { public static void main(String[] args) { A a = new A(100); A b = new A(200); a.transferTo(b, 50); System.out.println(a.balance + " " + b.balance); } } class A { int balance; A(int balance) { this.balance = balance; } boolean withdraw(int amount) { if (amount > balance) { return false; } balance -= amount; return true; } void deposit(int amount) { balance += amount; } boolean transferTo(A other, int amount) { if (!withdraw(amount)) { return false; } other.deposit(amount); return true; } }Answer
50 250
Fifty cents leave the first account and arrive in the second.
-
Why does the statement build the lines with a StringBuilder?
Answer
A loop of concatenations would copy the whole text on every pass
The builder appends to one buffer, which is the pattern of lesson 025.
-
What does the total method do?
Answer
Adds the balances of the opened accounts
It loops to size, so only the accounts that were opened are counted.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev