Java project on banking

Banking Transaction System using Java

In order to understand one must have a strong grasp over Java OOPs, Java Multithreading & Java Interrupted-Exception. If not go through them as the title in itself is a sheer implementation of multithreading.

  1. Rookie approach
  2. Multithreading approach
  3. Synchronization invoking in multithreading approach

In order to understand, let us consider an illustration in order to implement the approach.

Illustration:

We will discuss the architecture of the banking transaction system using java. Throughout this editorial, I will hold your hands and take you through the entire transaction procedure and make it Easy-Pease for you to understand so that you can even explain it to your friends. For the sake of simplicity, we have considered a joint bank account having 5 owners(Arnab, Monodwip, Mukta, Rinkel, and Shubham) and the initial balance is a hundred dollars ($100). The transactions of the account are listed as follows:

Balance after withdrawal: 80

Balance after withdrawal: 40

Rinkel you can not withdraw 80

Balance after withdrawal: 35

Approach 1: Rookie approach

We have declared the “withdraw” and “deposit” method inside the class “Bank” and accessed them from the driver class “GFG” by creating an object “obj” of Bank class.

Java

C:\Users\USER\Desktop\LearnCoding\MultiThreading>javac GFG.java C:\Users\USER\Desktop\LearnCoding\MultiThreading>java GFG Arnab withdrawn 20 Balance after withdrawal: 80 //After 1 Second Monodwip withdrawn 40 Balance after withdrawal: 40 //After 1 Second Mukta deposited 35 Balance after deposit: 75 //After 1 Second Rinkel you can not withdraw 80 your balance is: 75 //After 1 Second Shubham withdrawn 40 Balance after withdrawal: 35

There are certain cons associated with the Rookie approach as depicted below:

No 2 people can make transactions at the same time, one needs to wait till the former finishes its transaction. If the number of people is large then we need to wait and wait until our turn comes. To demonstrate this problem, we made the thread sleep for 3 seconds during each transaction in the video provided below. In real life, it would take much time making this approach incapable of implementation in real transaction projects.

Method 2: Multithreading Approach

How multithreading can help?

Multithreading allows different threads to work at the same time without having any dependency on one-another. So large group of threads can perform an operation at the same time.

Java

Now there are certain problems with the multithreading approach as listed below:

When multiple threads try to do a particular operation at the same time then there exists a possibility of bad output, this is because all the threads are updating the same resource at a time. In the above output, we got balance in negative figures due to the same reason.

How to handle those cases where multiple people try to access the same operation at a time?

If multiple threads access a single resource at a time then there exists a possibility of bad output. This unwanted phenomenon is defined as data racing.

Suppose we have $100 in our joint bank account. To trick the banker, both of us can request $100 simultaneously at a time. The system will create an object, assign 2 threads and pass them to the withdrawal method. At the end of the process, both of us will have $100!

To handle this problem engineers came up with the synchronization concept.

Method 3: Incorporating synchronization with multithreading

Synchronization provides a lock to the object and declares a sensitive area (withdraw & deposit methods). An object can have multiple threads but the sensitive area can only be accessed by 1 thread at a time. The thread scheduler chooses the order of execution of the threads. As it is a random process the output is different for each interpretation.

Why should we use static synchronization?

Say we have 5 thread classes with 1 object each. Each object have multiple threads. Now the sensitive area will be accessed by 5 threads at a time! To handle this problem engineers came up with the idea of static synchronization. We provide a lock to the class. The class will select 1 object at a time. The object in turn will choose 1 thread and pass it through the sensitive area.

Does synchronized multithreaded execution slower than the normal execution without multithreading?

No. The amount of time one task spends waiting for another is considered as overhead. In synchronized multithreading, this overhead time can be used to do other productive work until the waiting thread gets the key from the thread scheduler to get inside the synchronized area. Thus the overhead would be minimal in the case of synchronized multithreaded execution, so we can expect it to be faster.

Источник

Кофе-брейк #201. Как создать консольное банковское приложение на Java

Java-университет

Кофе-брейк #201. Как создать консольное банковское приложение на Java - 1

Источник: MediumСегодня мы разработаем простое Java-приложение для банковской системы. Оно поможет нам лучше понять, как концепции ООП используются в программах на языке Java.Для начала нам понадобится среда Java, установленная на компьютере, желательно Java 11. Далее мы начнем с подробного описания функций консольного приложения. Функционал:

  1. Создание аккаунта;
  2. Вход, выход;
  3. Отображение последних 5 транзакций;
  4. Депозит денежных средств;
  5. Отображение текущей информации о пользователе.

Используемые концепции объектно-ориентированного программирования:

  1. Наследование;
  2. Полиморфизм;
  3. Инкапсуляция.

Разработка приложения

Создадим новый Java-проект в Eclipse или IntelliJ IDEA. Определим новый интерфейс с именем SavingsAccount .

 public interface SavingsAccount

Я реализовал интерфейс, в котором размещен метод deposit . Я вызываю этот метод каждый раз, когда добавляю деньги на текущий счет. Используемая здесь концепция ООП — полиморфизм (методы в интерфейсе не имеют тела). Реализацию этого метода можно найти в классе Customer , переопределив метод с тем же именем и параметрами. Так вы переопределяете метод из родительского интерфейса в дочернем классе. Затем нам понадобится клиент (customer), чтобы добавить деньги на текущий счет. Но сначала давайте определим наш класс Customer .

 public class Customer extends Person implements SavingsAccount < private String username; private String password; private double balance; private ArrayListtransactions = new ArrayList<>(5); public Customer(String firstName, String lastName, String address, String phone, String username, String password, double balance, ArrayList transactions, Date date) < super(firstName, lastName, address, phone); this.username = username; this.password = password; this.balance = balance; addTransaction(String.format("Initial deposit - " + NumberFormat.getCurrencyInstance().format(balance) + " as on " + "%1$tD" + " at " + "%1$tT.", date)); >private void addTransaction(String message) < transactions.add(0, message); if (transactions.size() >5) < transactions.remove(5); transactions.trimToSize(); >> //Getter Setter public ArrayList getTransactions() < return transactions; >@Override public void deposit(double amount, Date date) < balance += amount; addTransaction(String.format(NumberFormat.getCurrencyInstance().format(amount) + " credited to your account. Balance - " + NumberFormat.getCurrencyInstance().format(balance) + " as on " + "%1$tD" + " at " + "%1$tT.", date)); >@Override public String toString() < return "Customerнаследование, поскольку класс Customer получает свойства от класса Person. То есть, практически все атрибуты класса Person наследуются и видны отношения по родительско-дочернему принципу от Person к Customer. Сейчас нам нужен конструктор со всеми атрибутами двух классов и добавление ключевого слова суперконструктора для указания унаследованных атрибутов. Реализуя интерфейс SavingsAccount, мы должны переопределить метод deposit в классе Customer. Для этого мы напишем реализацию метода в этом классе. Кроме того, список транзакций инициализируется для отображения последних пяти транзакций. В конструкторе вызывается метод addTransaction, в котором отображается дата изменений и совершенных транзакций. 
 private void addTransaction(String message) < transactions.add(0, message); if (transactions.size() >5) < transactions.remove(5); transactions.trimToSize(); >> 
 public class Person < private String firstName; private String lastName; private String address; private String phone; public Person() <>public Person(String firstName, String lastName, String address, String phone) < this.firstName = firstName; this.lastName = lastName; this.address = address; this.phone = phone; >//Getters Setters @Override public String toString() < return "Person'; > @Override public boolean equals(Object o) < if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (getFirstName() != null ? !getFirstName().equals(person.getFirstName()) : person.getFirstName() != null) return false; if (getLastName() != null ? !getLastName().equals(person.getLastName()) : person.getLastName() != null) return false; if (getAddress() != null ? !getAddress().equals(person.getAddress()) : person.getAddress() != null) return false; return getPhone() != null ? getPhone().equals(person.getPhone()) : person.getPhone() == null; >@Override public int hashCode()

В классе Person мы использовали концепцию инкапсуляции , применяя модификатор доступа private для каждого атрибута. Инкапсуляция в Java может быть определена как механизм, с помощью которого методы, работающие с этими данными, объединяются в единое целое. По сути, данные из класса Person доступны только в этом классе, но никак не в других классах или пакетах. И наконец, наш основной класс, названный Bank . Это основной класс, откуда мы запускаем приложение и взаимодействуем с функциональностью всех классов.

 public class Bank < private static double amount = 0; MapcustomerMap; Bank() < customerMap = new HashMap(); > public static void main(String[] args) < Scanner sc = new Scanner(System.in); Customer customer; Bank bank = new Bank(); int choice; outer: while (true) < System.out.println("\n-------------------"); System.out.println("BANK OF JAVA"); System.out.println("-------------------\n"); System.out.println("1. Registrar cont."); System.out.println("2. Login."); System.out.println("3. Exit."); System.out.print("\nEnter your choice : "); choice = sc.nextInt(); sc.nextLine(); switch (choice) < case 1: System.out.print("Enter First Name : "); String firstName = sc.nextLine(); System.out.print("Enter Last Name : "); String lastName = sc.nextLine(); System.out.print("Enter Address : "); String address = sc.nextLine(); System.out.print("Enter contact number : "); String phone = sc.nextLine(); System.out.println("Set Username : "); String username = sc.next(); while (bank.customerMap.containsKey(username)) < System.out.println("Username already exists. Set again : "); username = sc.next(); >System.out.println("Set a password:"); String password = sc.next(); sc.nextLine(); customer = new Customer(firstName, lastName, address, phone, username, password, new Date()); bank.customerMap.put(username, customer); break; case 2: System.out.println("Enter username : "); username = sc.next(); sc.nextLine(); System.out.println("Enter password : "); password = sc.next(); sc.nextLine(); if (bank.customerMap.containsKey(username)) < customer = bank.customerMap.get(username); if (customer.getPassword().equals(password)) < while (true) < System.out.println("\n-------------------"); System.out.println("W E L C O M E"); System.out.println("-------------------\n"); System.out.println("1. Deposit."); System.out.println("2. Transfer."); System.out.println("3. Last 5 transactions."); System.out.println("4. User information."); System.out.println("5. Log out."); System.out.print("\nEnter your choice : "); choice = sc.nextInt(); sc.nextLine(); switch (choice) < case 1: System.out.print("Enter amount : "); while (!sc.hasNextDouble()) < System.out.println("Invalid amount. Enter again :"); sc.nextLine(); >amount = sc.nextDouble(); sc.nextLine(); customer.deposit(amount, new Date()); break; case 2: System.out.print("Enter beneficiary username : "); username = sc.next(); sc.nextLine(); System.out.println("Enter amount : "); while (!sc.hasNextDouble()) < System.out.println("Invalid amount. Enter again :"); sc.nextLine(); >amount = sc.nextDouble(); sc.nextLine(); if (amount > 300) < System.out.println("Transfer limit exceeded. Contact bank manager."); break; >if (bank.customerMap.containsKey(username)) < Customer payee = bank.customerMap.get(username); //Todo: check payee.deposit(amount, new Date()); customer.withdraw(amount, new Date()); >else < System.out.println("Username doesn't exist."); >break; case 3: for (String transactions : customer.getTransactions()) < System.out.println(transactions); >break; case 4: System.out.println("Titularul de cont cu numele: " + customer.getFirstName()); System.out.println("Titularul de cont cu prenumele : " + customer.getLastName()); System.out.println("Titularul de cont cu numele de utilizator : " + customer.getUsername()); System.out.println("Titularul de cont cu addresa : " + customer.getAddress()); System.out.println("Titularul de cont cu numarul de telefon : " + customer.getPhone()); break; case 5: continue outer; default: System.out.println("Wrong choice !"); > > > else < System.out.println("Wrong username/password."); >> else < System.out.println("Wrong username/password."); >break; case 3: System.out.println("\nThank you for choosing Bank Of Java."); System.exit(1); break; default: System.out.println("Wrong choice !"); >>>> 

Используя библиотеку java.util , мы вызываем Scanner для чтения данных с клавиатуры. Приводя объект Customer через его определение, известное как Bank , мы создаем новый объект типа Bank() . Через некоторое время выводим стартовое меню. При использовании nextLine считывается число, добавленное с клавиатуры. Ниже у нас есть новый конструктор, который сохраняет нашу map , данные клиента. Map.put используется для сохранения или обновления данных клиентов. customer = new Customer(firstName, lastName, address, phone, username, password, new Date());

 bank.customerMap.put(username, customer); 

При наличии соединения мы получаем новое меню с опциями. Тот же подход работает с использованием while и switch для вызова функционала приложения. Этап 1: Добавляем деньги на текущий счет. Этап 2: Отображаем последние 5 транзакций. Этап 3: Выводим данные клиента с карты в консоль. Этап 4: Закрываем меню. Исходный код программы можно найти здесь. Надеюсь, что этот пример поможет вам лучше познакомиться с использованием концепций ООП в Java.

Источник

Читайте также:  Скрипты php досок объявлений
Оцените статью