×

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors that can cause a bank transaction to fail or be refused because there are many parties involved in its processing, including a merchant, bank, receiver, etc. It provides guidelines for connecting Java-based databases. It is employed in the creation of software required to access databases.

JDBC transactions provide us a feature that treats a whole SQL statement as a single unit, then executes it once, and if any statement fails, the transaction as a whole failure. Once all the instructions have been properly performed, we must manually set setAutoCommit(false); and then make changes to the database's commit() procedure.

JDBC Transaction is used in this Mini Banking Application to manage transactions and ensure consistency. A user can create an account, log in, view their balance, and transfer money to another customer using this application's menu-driven console interface.

  • Functionality: Assuring that module (both individually and as a system) perform as planned;
  • UX and usability: Not all banking professionals are adept at using computers. For branch customers, not everyone has strong web skills. Because of this, application interfaces need to be both aesthetically pleasing and user-friendly. The use of the product's graphic features shouldn't take too much time, and all the important services should be easily accessed from the homepage.
  • Performance: On mobile devices, there are severe issues that can negatively impact user retention rates, including slow page loading and low responsiveness. A tester must ensure that the product responds quickly and reliably across a range of browsers and operating systems.
  • Security: Most developed countries are increasing their oversight of web security. Because of this, companies face the risk of ignoring important security guidelines. If business owners disregard security instructions, they risk being fined or being sued. The purpose of security testing is to ensure that the application conforms to industry security standards and has additional security measures in place to protect users from hacker attacks.

Software Requirements

  • Eclipse: For the development and troubleshooting of (mostly) Java programs, an IDE (interactive development environment) named Eclipse was developed. A base workspace and an expandable plug-in system are two ways to alter the environment.
  • MySQL: MySQL is a relational database management system with many features (RDBMS). The most well-liked language for storing, retrieving, and processing data in a database, Structured Query Language (SQL), is used by the free, open-source relational database management system MySQL. The attributes of MySQL are speed, dependability, and flexibility.

Steps for Databases Setup

Step 1: In this step, we are creating database name as bank.

Step 2: Table name as customer.

// Create a database

CREATE DATABASE BANK;

// Create table
CREATE TABLE `customer` (


 `account_number` int NOT NULL AUTO_INCREMENT,


 `cuatomer_name` varchar(45) DEFAULT NULL,


 `balance` varchar(45) DEFAULT NULL,


 `pass_code` int DEFAULT NULL,


 PRIMARY KEY (`ac_no`),


 UNIQUE KEY `cname_UNIQUE` (`cname`)


) ;

Eclipse Project Setup

  • Create a project
  • Create a package and name it as banking

Step 1: Include JDBC Driver for MySQL

// register jdbc Driver 
String mysqlJDBCDriver = "com.mysql.cj.jdbc.Driver";
Class.forName(mysqlJDBCDriver);

Step 2: Create Connection Class using MySQL username and password

// Create Connection
String url = "jdbc:mysql://localhost:3306/mydata";
String user = "root";
String pass = "123";
con = DriverManager.getConnection(url, user, pass);

Java Program

package bank;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;


public class bm {
                              // bank method


    private static final int NULL = 0;


    static Connection net = connection.getConnection();
    static String sql = "";
    public static boolean
createAcc(String name,
                  int password) // generate acc function
    {
        try {
            // validation
            if (name == "" || password == NULL) {
System.out.println("fill all required fields");
                return false;
            }
            // query
            Statement sm = net.createStatement();
sql = "INSERT INTO customer(customer_name,balance,password) values('"
                  + name + "',1000," + password + ")";


            // Execution
            if (sm.executeUpdate(sql) == 1) {
System.out.println(name
                                   + ", login details");
                return true;
            }


        }
        catch (SQLIntegrityConstraintViolationException e) {
System.out.println("no username");
        }
        catch (Exception e) {
e.printStackTrace();
        }
        return false;
    }
    public static boolean
loginAcc(String name, int password) // login 
    {
        try {
            // validation
            if (name == "" || password == NULL) {
System.out.println("fill all required fields");
                return false;
            }
            // query
sql = "select * from customer where customer_name='"
                  + name + "' and password=" + password;
PreparedStatementsm
                = net.prepareStatement(sql);
ResultSetsr = sm.executeQuery();
            // Execution
BufferedReaderbr = new BufferedReader(
                new InputStreamReader(System.in));


            if (sr. next()) {




                int ch = 5;
                int amountt = 0;
                int senderAc = sr.getInt("acccount_no");
                ;
                int receiveAc;
                while (true) {
                    try {
System.out.println(
                            "Hello, "
                            + rs.getString("customer_name"));
System.out.println(
                            "1)Transfer Money");
System.out.println("2)View Balance");
System.out.println("5)LogOut");


System.out.print("choice menu");
ch = Integer.parseInt(
sc.readLine());
                        if (ch == 1) {
System.out.print(
                                "Receiver  Account No:");
receiveAc = Integer.parseInt(
sc.readLine());
System.out.print(
                                "Amount:");
                            amt = Integer.parseInt(
sc.readLine());


                            if (bm
.transferMoney(
senderAc, receiveAc,
                                        amt)) {
System.out.println(
                                    " money sent\n");
                            }
                            else {
System.out.println(
                                    "ERROR :  Failed\n");
                            }
                        }
                        else if (ch == 2) {


bm.getBalance(
senderAc);
                        }
                        else if (ch == 5) {
                            break;
                        }
                        else {
System.out.println(
                                "Error :invaild\n");
                        }
                    }
                    catch (Exception e) {
e.printStackTrace();
                    }
                }
            }
            else {
                return false;
            }
            return true;
        }
        catch (SQLIntegrityConstraintViolationException e) {
System.out.println("usename not found");
        }
        catch (Exception e) {
e.printStackTrace();
        }
        return false;
    }
    public static void
getBalance(int accountNo) // fetch balance method
    {
        try {


            // query
sql = "select * from customer where accont_no="
                  + accoountNo;
PreparedStatementsm
                = net.prepareStatement(sql);


ResultSetsr = sm.executeQuery(sql);
System.out.println(
                "-----------------------------------------------------------");
System.out.printf("%12s %10s %10s\n",
                              "Acc No", "Name",
                              "Balance");


            // Execution


            while (sr.next()) {
System.out.printf("%12d %10s %10d.00\n",
sr.getInt("account_no"),
sr.getString("customer_name"),
rs.getInt("balance"));
            }
System.out.println(
                "-----------------------------------------------------------\n");
        }
        catch (Exception e) {
e.printStackTrace();
        }
    }
    public static booleantransferMoney(int sender_ac,
                                        int reveiver_account,
                                        int amt)
        throws SQLException // transfer money method
    {
        // validation
        if (reveiver_account == NULL || amt == NULL) {
System.out.println("fill all required fields");
            return false;
        }
        try {
net.setAutoCommit(false);
sql = "select * from customer where account_no="
                  + sender_account;
PreparedStatementps
                = net.prepareStatement(sql);
ResultSetsr = ps.executeQuery();


            if (sr.next()) {
                if (sr.getInt("balance") < amount) {
System.out.println(
                        "Insufficient amount");
                    return false;
                }
            }


            Statement sm = net.createStatement();


net.setSavepoint();


sql = "update customer set balance=balance-"
                  + amount + " where account_no=" + sender_acccount;
            if (sm.executeUpdate(sql) == 1) {
System.out.println("money Debited!");
            }


            // credit
sql = "update customer set balance=balance+"
                  + amount + " where account_no=" + reveiver_account;
st.executeUpdate(sql);


con.commit();
            return true;
        }
        catch (Exception e) {
e.printStackTrace();
con.rollback();
        }


        return false;
    }
}


//connection.java
package bank;


import java.sql.Connection;
import java.sql.DriverManager;


public class con {
    static Connection net; 
    public static Connection getCon()
    {
        try {




            String mysqlJDBCDriver
                = "com.mysql.cj.jdbc.Driver"; 
            String url
                = "jdbc:mysql://localhost:3306/mydata";
            String user = "scott";        // username
            String pass = "tiger";  //mysql password
Class.forName(mysqlJDBCDriver);
net = DriverManager.getConnection(url, username,
                                              password);
        }
        catch (Exception e) {
System.out.println("network Failed");
        }


        return net;
    }
}
// java.connection
package bank;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class bm {
    public static void main(String args[]) 
        throws IOException
    {


BufferedReaderbr = new BufferedReader(
            new InputStreamReader(System.in));
        String name = "";
        int password;
        int account_no;
        int ch;


        while (true) {
System.out.println(
                "\n ->||    Welcome to Bank    ||<- \n");
System.out.println("1)generate Acc");
System.out.println("2)Login Acc");


            try {
System.out.print("\n    Enter Input:"); 
ch = Integer.parseInt(br.readLine());


                switch (ch) {
                case 1:
                    try {
System.out.print(
                            "Fill Unique UserName id:");
                        name = br.readLine();
System.out.print(
                            "Create Password:");
pass_code = Integer.parseInt(
br.readLine());


                        if (bm.createAccount(
                                name, password)) {
System.out.println(
                                "Account Created \n");
                        }
                        else {
System.out.println(
                                "ERROR: Acc failed\n");
                        }
                    }
                    catch (Exception e) {
System.out.println(
                            " ERROR: Enter Valid Data::Insertion Failed\n");
                    }
                    break;


                case 2:
                    try {
System.out.print(
                            "Enter UserName:");
                        name = br.readLine();
System.out.print(
                            "Enter Passcode:");
pass_code = Integer.parseInt(
br.readLine());


                        if (bm.loginAccount(
                                name, password)) {
System.out.println(
                                "Logout Successfully\n");
                        }
                        else {
System.out.println(
                                "ERROR: login Failed!\n");
                        }
                    }
                    catch (Exception e) {
System.out.println(
                            " ERROR: Enter Valid Data::Login Failed!\n");
                    }


                    break;


                default:
System.out.println("Invalid data\n");
                }


                if (ch == 5) {
System.out.println(
                        "Exited Successfully\n\n Thanks :)");
                    break;
                }
            }
            catch (Exception e) {
System.out.println("Enter Valid Entry!");
            }
        }
br.close();
    }
}

Output:

This class provides the customer a menu-driven interface through which they can create accounts, log in to existing accounts, transfer money, etc.

  ->||    Welcome to Bank    ||<- 


    1)generate Account
    2)Login Account


    Enter Input:2
UserName:scott
Password:tiger
View Balance:


UserName:scott
Password:tiger
Hello, scott
1)Transfer Money
2)View Balance
5)LogOut
Enter Choice:2
-----------------------------------------------------------
  Account No       Name    Balance
         112    scott          0.00
-----------------------------------------------------------
Transfer Money:


Hello, scott
1)Transfer Money
2)View Balance
5)LogOut
Enter Choice:1
Enter Receiver Account No:110
Enter Amount:5000
Insufficient amount
ERROR:  Failed
Logout:


Hello, scott
1)Transfer Money
2)View Balance
5)LogOut
Enter Choice:5
 Logout Successfully

Applications

  • Verify that a user may log in using valid login information. The application must provide a restoration method in the event that users forget to provide the information for one or both of the required fields.
  •  Assure that a user can carry out simple transactions. A banking app must handle both user-to-user and user-to-another account transactions between the user's own credit cards. The programme must provide a way to set up recurring payments in order to increase transaction convenience.
  • Transactions can be sent to numerous users. They shouldn't be able to do so unless they have enough money in their account.
  • After several failed attempts at login, the account is blocked. This is a safe method of preventing brute force attacks. In addition, a developer must plan for a method of quickly and securely unblocking a blocked account.
  •  The user may modify their password. A secure method for app users to change their login credentials must be tested. To ensure that the records in the database are as current as possible, the development team must build a secure method for editing any personal data.

Related Topics

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.