Bank Account Operations in Java: Solution, Explanation & Practice
Create a full bank account class
Problem summary
Create a BankAccount class with deposit, withdraw, and balance check operations.
Starter code
// Create BankAccount with:
// - private double balance
// - void deposit(double amount)
// - boolean withdraw(double amount) - false if insufficient
// - double getBalance()
public class Main {
public static void main(String[] args) {
// Test case 1: start with 1000, deposit 500, withdraw 200
// Print: Balance: <result>
}
}Expected output and test cases
- 1000+500-200
Balance: 1300.0
- After failed withdraw
Balance: 500.0
- Multiple deposits
Balance: 2000.0
Hints
- Check balance before withdraw
- Return false if insufficient funds
- Deposit should always succeed
Validated solution
Reveal Java solution
class BankAccount {
private double balance;
BankAccount(double openingBalance) { if (openingBalance < 0) throw new IllegalArgumentException(); balance = openingBalance; }
void deposit(double amount) { if (amount <= 0) throw new IllegalArgumentException(); balance += amount; }
boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount; return true;
}
double balance() { return balance; }
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
account.deposit(500); account.withdraw(200);
System.out.println("Balance: " + account.balance());
}
}How to approach the problem
Encapsulation prevents callers from assigning arbitrary balances. Deposit and withdraw are state transitions with checks, so an invalid request fails without corrupting the account.
Approach
- Validate the opening balance.
- Expose behavior instead of a public balance field.
- Reject overdrafts before subtracting.
Time and space complexity
Time: O(1). Space: O(1).
Edge cases to test
- A failed withdrawal leaves the balance unchanged.
- Real money should use BigDecimal rather than double.
Common mistakes
- Subtracting first and checking for a negative balance afterward.
- Accepting zero or negative deposits.
Follow-up challenge
Add a transaction history and make withdrawals atomic under concurrent access.
Related OOP Basics exercises
- Practice BMI Calculator Class in Java
- Practice Student Grade Calculator in Java
- Practice Shopping Cart in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler