Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 07 / Topic 7 of 7

Putting it together: a bank account

Every tool from this part, in one class: a primary and a secondary constructor, init validation, a private-set balance, a custom-setter pin, a private transaction log, and a menu loop reusing Part 4's while (true) + when + break shape.

class BankAccount(val accountHolder: String, val accountNumber: String, openingBalance: Double) {

    var balance: Double = openingBalance
        private set

    private val transactionLog = mutableListOf<String>()

    init {
        require(accountHolder.isNotBlank()) { "accountHolder cannot be blank" }
        require(openingBalance >= 0.0) { "openingBalance cannot be negative, was $openingBalance" }
        transactionLog.add("Opened with ₹%.2f".format(openingBalance))
    }

    // secondary constructor: open a fresh account with zero balance, account number
    // assigned later -- delegates to the primary constructor via `this(...)`
    constructor(accountHolder: String) : this(accountHolder, "PENDING", 0.0)

    var pin: String = "0000"
        set(value) {
            require(value.length == 4 && value.all { it.isDigit() }) {
                "PIN must be exactly 4 digits, got \"$value\""
            }
            field = value
        }

    val balanceDisplay: String
        get() = "₹%.2f".format(balance)

    fun deposit(amount: Double): Boolean {
        if (amount <= 0.0) {
            println("Deposit amount must be positive.")
            return false
        }
        balance += amount
        transactionLog.add("Deposit ₹%.2f".format(amount))
        return true
    }

    fun withdraw(amount: Double): Boolean {
        if (amount <= 0.0) {
            println("Withdrawal amount must be positive.")
            return false
        }
        if (amount > balance) {
            println("Insufficient balance: tried to withdraw ₹%.2f, balance is ₹%.2f".format(amount, balance))
            return false
        }
        balance -= amount
        transactionLog.add("Withdraw ₹%.2f".format(amount))
        return true
    }

    fun miniStatement() {
        println("--- Mini statement for $accountHolder ($accountNumber) ---")
        for ((index, entry) in transactionLog.withIndex()) {
            println("${index + 1}. $entry")
        }
        println("Current balance: $balanceDisplay")
    }
}

fun main() {
    val account = BankAccount("Asha Kulkarni", "AC-10045", 2000.0)
    account.pin = "4821"

    while (true) {
        println()
        println("1. Check balance")
        println("2. Deposit")
        println("3. Withdraw")
        println("4. Mini statement")
        println("5. Change PIN")
        println("6. Exit")
        print("Choose an option: ")
        val choice = readlnOrNull()?.trim()

        when (choice) {
            "1" -> println("Balance: ${account.balanceDisplay}")
            "2" -> {
                print("Amount to deposit: ")
                val amount = readlnOrNull()?.trim()?.toDoubleOrNull()
                if (amount == null) {
                    println("Enter a valid amount.")
                } else if (account.deposit(amount)) {
                    println("Deposited ₹%.2f. New balance: ${account.balanceDisplay}".format(amount))
                }
            }
            "3" -> {
                print("Amount to withdraw: ")
                val amount = readlnOrNull()?.trim()?.toDoubleOrNull()
                if (amount == null) {
                    println("Enter a valid amount.")
                } else if (account.withdraw(amount)) {
                    println("Withdrew ₹%.2f. New balance: ${account.balanceDisplay}".format(amount))
                }
            }
            "4" -> account.miniStatement()
            "5" -> {
                print("New 4-digit PIN: ")
                val newPin = readlnOrNull()?.trim() ?: ""
                try {
                    account.pin = newPin
                    println("PIN updated.")
                } catch (e: IllegalArgumentException) {
                    println("Could not update PIN: ${e.message}")
                }
            }
            "6" -> {
                println("Thank you for banking with us.")
                break
            }
            else -> println("Invalid option, choose 1-6.")
        }
    }
}

A few design choices worth noticing:

  • balance is private set for the same reason catalog was typed Map in Part 6: nothing outside this class should change it directly, only through deposit/withdraw, and the type system enforces that rather than relying on a comment.
  • deposit/withdraw return Boolean instead of throwing, and print their own message on failure -- the menu loop just checks the result, the same early-return spirit as Part 5.
  • The secondary constructor exists purely so a reader opening a brand-new account doesn't have to type 0.0 and a placeholder account number every time; this program's main() doesn't happen to use it, but examples/03_secondary_constructors.kt exercises it directly.

Two runs, each piped through printf for a reproducible transcript:

$ kotlinc 07_bank_account.kt -include-runtime -d bank.jar
$ printf '1\n2\n500\n4\n3\n5000\n3\n300\n4\n5\n1234\n1\n6\n' | java -jar bank.jar

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Balance: ₹2000.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Amount to deposit: Deposited ₹500.00. New balance: ₹2500.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: --- Mini statement for Asha Kulkarni (AC-10045) ---
1. Opened with ₹2000.00
2. Deposit ₹500.00
Current balance: ₹2500.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Amount to withdraw: Insufficient balance: tried to withdraw ₹5000.00, balance is ₹2500.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Amount to withdraw: Withdrew ₹300.00. New balance: ₹2200.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: --- Mini statement for Asha Kulkarni (AC-10045) ---
1. Opened with ₹2000.00
2. Deposit ₹500.00
3. Withdraw ₹300.00
Current balance: ₹2200.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: New 4-digit PIN: PIN updated.

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Balance: ₹2200.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Thank you for banking with us.

A second run exercises an invalid deposit amount, a negative deposit, a negative withdrawal, and an invalid PIN before a valid one:

$ printf '2\nabc\n2\n-50\n3\n-10\n5\n12\n5\n9999\n1\n6\n' | java -jar bank.jar

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Amount to deposit: Enter a valid amount.

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Amount to deposit: Deposit amount must be positive.

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Amount to withdraw: Withdrawal amount must be positive.

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: New 4-digit PIN: Could not update PIN: PIN must be exactly 4 digits, got "12"

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: New 4-digit PIN: PIN updated.

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Balance: ₹2000.00

1. Check balance
2. Deposit
3. Withdraw
4. Mini statement
5. Change PIN
6. Exit
Choose an option: Thank you for banking with us.

Notice "abc" as a deposit amount and -50/-10 as deposit/withdrawal amounts are rejected by two different checks: toDoubleOrNull() catches the unparseable "abc" before deposit() is even called, while deposit/withdraw themselves catch the negative numbers that parsed fine but make no sense as a transaction.

Full program: examples/07_bank_account.kt.

Done here? The practice set for Part 7 — including the solutions — is on the part page.

Search the guide