Kotlin Class: BankAccount class with deposit and withdrawal functions
Kotlin Class: Exercise-6 with Solution
Write a Kotlin program that creates a class 'BankAccount' with properties for account number, balance, and account holder name. Include deposit and withdrawal functions.
Sample Solution:
Kotlin Code:
class BankAccount(
val accountNumber: String,
var balance: Double,
val accountHolderName: String
) {
fun deposit(amount: Double) {
balance += amount
println("Deposit of $amount successful. New balance: $balance")
}
fun withdrawal(amount: Double) {
if (balance >= amount) {
balance -= amount
println("Withdrawal of $amount successful. New balance: $balance")
} else {
println("Insufficient balance ($balance). Withdrawal ($amount) failed.")
}
}
fun displayAccountDetails() {
println("Account Holder: $accountHolderName")
println("Account Number: $accountNumber")
println("Balance: $balance")
}
}
fun main() {
val account = BankAccount("SB-12340", 2000.0, "Lotte Nazir")
account.displayAccountDetails()
account.deposit(500.0)
account.withdrawal(400.0)
account.withdrawal(2500.0)
}
Sample Output:
Account Holder: Lotte Nazir Account Number: SB-12340 Balance: 2000.0 Deposit of 500.0 successful. New balance: 2500.0 Withdrawal of 400.0 successful. New balance: 2100.0 Insufficient balance (2100.0). Withdrawal (2500.0) failed.
Explanation:
In the above exercise -
In this program, we define a class "BankAccount" with three properties: accountNumber, balance, and accountHolderName. The class includes three functions: deposit, withdrawal, and displayAccountDetails.
The "deposit()" function takes an amount and adds it to the account's balance. It then prints a success message along with the new balance.
The "withdrawal()" function takes an amount as input and checks if the account has a sufficient balance. If it does, it subtracts the amount from the balance and prints a success message along with the new balance. Otherwise, it prints an insufficient balance message.
The "displayAccountDetails()" function prints the account holder's name, account number, and balance.
In the "main()" function, we create an instance of the "BankAccount" class named account with initial values for the properties. We then call various functions on the account object to show deposit and withdrawal operations. Finally, we call the "displayAccountDetails()" function to print the updated account information.
Kotlin Editor:
Previous: Book class with display function.
Next: Circle class with circumference calculation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/kotlin-exercises/class/kotlin-class-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics