-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPersonalFinanceManager.java
More file actions
524 lines (439 loc) · 17 KB
/
PersonalFinanceManager.java
File metadata and controls
524 lines (439 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
// ==================== UNIT 1: OOP FUNDAMENTALS & JAVA BASICS ====================
/**
* Abstract class demonstrating Abstraction
* Represents a bank account with basic operations
*/
abstract class Account {
private String accountId;
private String accountHolder;
protected double balance;
private static int accountCounter = 0; // Static member
/**
* Constructor for Account
* @param accountHolder Name of the account holder
* @param initialBalance Initial balance amount
*/
public Account(String accountHolder, double initialBalance) {
this.accountId = "ACC" + (++accountCounter);
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
// Encapsulation - Getters and Setters
public String getAccountId() {
return accountId;
}
public String getAccountHolder() {
return accountHolder;
}
public double getBalance() {
return balance;
}
// Abstract method - must be implemented by subclasses
public abstract void displayAccountType();
// Method with access specifier
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds! Balance: $" + balance);
}
balance -= amount;
System.out.println("Withdrawn: $" + amount);
}
// Static method
public static int getTotalAccounts() {
return accountCounter;
}
}
// ==================== UNIT 2: INHERITANCE & INTERFACES ====================
// Subclass demonstrating Inheritance
class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(String accountHolder, double initialBalance, double interestRate) {
super(accountHolder, initialBalance); // Call to super class constructor
this.interestRate = interestRate;
}
@Override
public void displayAccountType() {
System.out.println("Account Type: Savings Account");
}
public void applyInterest() {
double interest = balance * interestRate / 100;
balance += interest;
System.out.println("Interest applied: $" + interest);
}
}
// Another subclass
class CurrentAccount extends Account {
private double overdraftLimit;
public CurrentAccount(String accountHolder, double initialBalance, double overdraftLimit) {
super(accountHolder, initialBalance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void displayAccountType() {
System.out.println("Account Type: Current Account");
}
@Override
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance + overdraftLimit) {
throw new InsufficientFundsException("Exceeds overdraft limit!");
}
balance -= amount;
System.out.println("Withdrawn: $" + amount);
}
}
// Interface definition
interface Transactionable {
void recordTransaction(Transaction transaction);
void displayTransactionHistory();
}
// Interface implementation
class TransactionManager implements Transactionable {
private ArrayList<Transaction> transactions;
public TransactionManager() {
transactions = new ArrayList<>();
}
@Override
public void recordTransaction(Transaction transaction) {
transactions.add(transaction);
}
@Override
public void displayTransactionHistory() {
System.out.println("\n=== Transaction History ===");
for (Transaction t : transactions) {
System.out.println(t);
}
}
public ArrayList<Transaction> getTransactions() {
return transactions;
}
}
// Class using String operations
class Transaction {
private String type;
private double amount;
private String date;
private String description;
public Transaction(String type, double amount, String description) {
this.type = type;
this.amount = amount;
this.description = description;
this.date = LocalDate.now().toString();
}
@Override
public String toString() {
return String.format("%s | %s | $%.2f | %s", date, type, amount, description);
}
public String getType() {
return type;
}
public double getAmount() {
return amount;
}
}
// Inner class demonstration
class Budget {
private String category;
private double limit;
private double spent;
public Budget(String category, double limit) {
this.category = category;
this.limit = limit;
this.spent = 0;
}
public void addExpense(double amount) {
spent += amount;
}
public boolean isOverBudget() {
return spent > limit;
}
// Inner class
class BudgetAlert {
public void checkAndAlert() {
if (spent > limit * 0.9) {
System.out.println("WARNING: " + category + " budget at " +
String.format("%.1f%%", (spent/limit)*100));
}
}
}
public void displayBudget() {
System.out.printf("%s: $%.2f / $%.2f (%.1f%%)%n",
category, spent, limit, (spent/limit)*100);
BudgetAlert alert = new BudgetAlert();
alert.checkAndAlert();
}
public String getCategory() {
return category;
}
}
// ==================== UNIT 3: EXCEPTION HANDLING & I/O ====================
// Custom exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
// File I/O operations
class FileManager {
private static final String FILENAME = "financial_data.txt";
// Writing to file
public static void saveData(ArrayList<Transaction> transactions) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(FILENAME));
writer.write("=== Financial Data Report ===\n");
writer.write("Generated on: " + LocalDateTime.now() + "\n\n");
for (Transaction t : transactions) {
writer.write(t.toString() + "\n");
}
System.out.println("Data saved to " + FILENAME);
} catch (IOException e) {
System.err.println("Error saving data: " + e.getMessage());
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Reading from file
public static void loadData() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(FILENAME));
System.out.println("\n=== Loading Saved Data ===");
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("No saved data found. Starting fresh.");
} catch (IOException e) {
System.err.println("Error reading data: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
// ==================== UNIT 4: MULTITHREADING & GENERICS ====================
// Generic class
class DataAnalyzer<T extends Number> {
private ArrayList<T> data;
public DataAnalyzer() {
data = new ArrayList<>();
}
public void addData(T value) {
data.add(value);
}
// Generic method with bounded type
public double calculateAverage() {
if (data.isEmpty()) return 0.0;
double sum = 0;
for (T value : data) {
sum += value.doubleValue();
}
return sum / data.size();
}
public T getMax() {
if (data.isEmpty()) return null;
T max = data.get(0);
for (T value : data) {
if (value.doubleValue() > max.doubleValue()) {
max = value;
}
}
return max;
}
}
// Thread for automatic savings calculation
class SavingsCalculatorThread extends Thread {
private SavingsAccount account;
private volatile boolean running = true;
public SavingsCalculatorThread(SavingsAccount account) {
super("SavingsCalculator");
this.account = account;
setDaemon(true); // Daemon thread
}
@Override
public void run() {
System.out.println("Savings calculator thread started (Daemon)");
while (running) {
try {
Thread.sleep(5000); // Sleep for 5 seconds
synchronized (account) { // Thread synchronization
System.out.println("\n[Background] Checking savings...");
if (account.getBalance() > 0) {
account.applyInterest();
}
}
} catch (InterruptedException e) {
System.out.println("Savings calculator interrupted");
break;
}
}
}
public void stopCalculator() {
running = false;
this.interrupt();
}
}
// Thread for budget monitoring
class BudgetMonitorThread implements Runnable {
private ArrayList<Budget> budgets;
private volatile boolean running = true;
public BudgetMonitorThread(ArrayList<Budget> budgets) {
this.budgets = budgets;
}
@Override
public void run() {
System.out.println("Budget monitor thread started");
while (running) {
try {
Thread.sleep(3000);
synchronized (budgets) { // Thread synchronization
System.out.println("\n[Background] Monitoring budgets...");
for (Budget budget : budgets) {
if (budget.isOverBudget()) {
System.out.println("ALERT: " + budget.getCategory() +
" budget exceeded!");
}
}
}
} catch (InterruptedException e) {
System.out.println("Budget monitor interrupted");
break;
}
}
}
public void stopMonitoring() {
running = false;
}
}
// ==================== MAIN APPLICATION ====================
public class PersonalFinanceManager {
public static void main(String[] args) {
System.out.println("============================================");
System.out.println(" PERSONAL FINANCE MANAGER APPLICATION ");
System.out.println(" Demonstrating All OOP Concepts ");
System.out.println("============================================\n");
// Create accounts (Inheritance, Polymorphism)
SavingsAccount savings = new SavingsAccount("John Doe", 1000.0, 5.0);
CurrentAccount current = new CurrentAccount("Jane Smith", 500.0, 200.0);
// Display account types (Polymorphism)
savings.displayAccountType();
current.displayAccountType();
System.out.println("Total Accounts: " + Account.getTotalAccounts() + "\n");
// Transaction management (Interface implementation)
TransactionManager transactionManager = new TransactionManager();
// ArrayList usage
ArrayList<Budget> budgets = new ArrayList<>();
budgets.add(new Budget("Food", 500.0));
budgets.add(new Budget("Transport", 200.0));
budgets.add(new Budget("Entertainment", 150.0));
// Generic programming
DataAnalyzer<Double> expenseAnalyzer = new DataAnalyzer<>();
// Exception handling demonstration
try {
System.out.println("=== Transaction Processing ===");
// Deposit operation
savings.deposit(500.0);
transactionManager.recordTransaction(
new Transaction("DEPOSIT", 500.0, "Salary credit"));
expenseAnalyzer.addData(500.0);
// Withdrawal with exception handling
try {
savings.withdraw(200.0);
transactionManager.recordTransaction(
new Transaction("WITHDRAWAL", 200.0, "ATM withdrawal"));
budgets.get(0).addExpense(200.0); // Food expense
expenseAnalyzer.addData(200.0);
} catch (InsufficientFundsException e) {
System.err.println("Transaction failed: " + e.getMessage());
// Stack trace
e.printStackTrace();
}
// Another transaction
current.deposit(300.0);
transactionManager.recordTransaction(
new Transaction("DEPOSIT", 300.0, "Freelance payment"));
// Withdrawal from current account
current.withdraw(150.0);
transactionManager.recordTransaction(
new Transaction("WITHDRAWAL", 150.0, "Bill payment"));
budgets.get(1).addExpense(150.0); // Transport expense
expenseAnalyzer.addData(150.0);
// Add more expenses for budget testing
budgets.get(2).addExpense(140.0); // Entertainment
expenseAnalyzer.addData(140.0);
} catch (InsufficientFundsException e) {
System.err.println("Error: " + e.getMessage());
}
// Display transaction history
transactionManager.displayTransactionHistory();
// Display budgets (Inner class usage)
System.out.println("\n=== Budget Overview ===");
for (Budget budget : budgets) {
budget.displayBudget();
}
// Generic data analysis
System.out.println("\n=== Expense Analysis (Generic Programming) ===");
System.out.printf("Average transaction: $%.2f%n", expenseAnalyzer.calculateAverage());
System.out.printf("Largest transaction: $%.2f%n", expenseAnalyzer.getMax());
// File I/O operations
System.out.println("\n=== File Operations ===");
FileManager.saveData(transactionManager.getTransactions());
FileManager.loadData();
// Multithreading demonstration
System.out.println("\n=== Starting Background Threads ===");
// Create and start threads
SavingsCalculatorThread savingsThread = new SavingsCalculatorThread(savings);
BudgetMonitorThread budgetMonitor = new BudgetMonitorThread(budgets);
Thread monitorThread = new Thread(budgetMonitor, "BudgetMonitor");
savingsThread.start();
monitorThread.start();
// Let threads run for a while
try {
System.out.println("\nApplication running for 12 seconds...");
System.out.println("(Background threads are calculating interest and monitoring budgets)\n");
Thread.sleep(12000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Stop threads
savingsThread.stopCalculator();
budgetMonitor.stopMonitoring();
try {
savingsThread.join();
monitorThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Final account status
System.out.println("\n============================================");
System.out.println(" FINAL ACCOUNT STATUS ");
System.out.println("============================================");
System.out.printf("Savings Account Balance: $%.2f%n", savings.getBalance());
System.out.printf("Current Account Balance: $%.2f%n", current.getBalance());
System.out.println("\nApplication completed successfully!");
System.out.println("All OOP concepts demonstrated!");
}
}