×

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

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 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.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.