Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Mini Banking Application in Java
Next article icon

Mini Banking Application in Java

Last Updated : 15 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In any Bank Transaction, there are several parties involved to process transaction like a merchant, bank, receiver, etc. so there are several numbers reasons that transaction may get failed, declined, so to handle a transaction in Java, there is a JDBC (Java Database Connectivity) which provides us an API to connect, execute, fetch data from any databases. It provides the language Java database connectivity standards. It is used to write programs required to access databases.

Transactions in JDBC provide us a  feature that considers a complete SQL statement as one unit,  then executes once, and if any statement fails, the entire transaction fails. To use transaction, we have to set setAutoCommit(false); manually, and once all the statements are executed successfully, making changes in the database's commit() method will be required. 

In this Mini Banking Application, to handle a transaction, we are using JDBC Transaction to make transactions consistent.  This Application Provides Menu-Driven Console Interface to a User Using that User can perform functions like create Account, Login, View Balance And Transfer Money To The Other Customer.

Software Prerequisite:

  • MySQL
  • Eclipse

MySQL:

MySQL is a full-featured relational database management system (RDBMS). MySQL is a free, open-source relational database management system that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. MySQL is noted for its speed, reliability, and flexibility.

Eclipse:

Eclipse is an IDE (interactive development environment) written to develop and debug (primarily) Java code. It contains a base workspace and an extensible plug-in system for customizing the environment. 

Databases Setup:

Step 1: Create Database name bank

Step 2: Create Table name customer

// Create a database  CREATE DATABASE BANK;    // Create table CREATE TABLE `customer` (   `ac_no` int NOT NULL AUTO_INCREMENT,   `cname` 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 New Project
  • Create A package name banking

File Configuration

File configuration

Create a Connection class in the banking package

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);

>>connection.java

Java
package banking;  import java.sql.Connection; import java.sql.DriverManager; // Global connection Class public class connection {     static Connection con; // Global Connection Object     public static Connection getConnection()     {         try {                                     String mysqlJDBCDriver                 = "com.mysql.cj.jdbc.Driver"; //jdbc driver             String url                 = "jdbc:mysql://localhost:3306/mydata"; //mysql url             String user = "root";        //mysql username             String pass = "Pritesh4@";  //mysql passcode              Class.forName(mysqlJDBCDriver);             con = DriverManager.getConnection(url, user,                                               pass);         }         catch (Exception e) {             System.out.println("Connection Failed!");         }          return con;     } } 

Purpose: This class returns a Global Databases Connection using the object of connection all the commands will be executed.

Note: Create a Bank Management Class in the banking package

>> bankmanagment.java

Java
package banking;  import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import java.sql.Statement;  public class bankManagement { // these class provides all                               // bank method      private static final int NULL = 0;      static Connection con = connection.getConnection();     static String sql = "";     public static boolean     createAccount(String name,                   int passCode) // create account function     {         try {             // validation             if (name == "" || passCode == NULL) {                 System.out.println("All Field Required!");                 return false;             }             // query             Statement st = con.createStatement();             sql = "INSERT INTO customer(cname,balance,pass_code) values('"                   + name + "',1000," + passCode + ")";              // Execution             if (st.executeUpdate(sql) == 1) {                 System.out.println(name                                    + ", Now You Login!");                 return true;             }             // return         }         catch (SQLIntegrityConstraintViolationException e) {             System.out.println("Username Not Available!");         }         catch (Exception e) {             e.printStackTrace();         }         return false;     }     public static boolean     loginAccount(String name, int passCode) // login method     {         try {             // validation             if (name == "" || passCode == NULL) {                 System.out.println("All Field Required!");                 return false;             }             // query             sql = "select * from customer where cname='"                   + name + "' and pass_code=" + passCode;             PreparedStatement st                 = con.prepareStatement(sql);             ResultSet rs = st.executeQuery();             // Execution             BufferedReader sc = new BufferedReader(                 new InputStreamReader(System.in));              if (rs.next()) {                 // after login menu driven interface method                  int ch = 5;                 int amt = 0;                 int senderAc = rs.getInt("ac_no");                 ;                 int receiveAc;                 while (true) {                     try {                         System.out.println(                             "Hallo, "                             + rs.getString("cname"));                         System.out.println(                             "1)Transfer Money");                         System.out.println("2)View Balance");                         System.out.println("5)LogOut");                          System.out.print("Enter Choice:");                         ch = Integer.parseInt(                             sc.readLine());                         if (ch == 1) {                             System.out.print(                                 "Enter Receiver  A/c No:");                             receiveAc = Integer.parseInt(                                 sc.readLine());                             System.out.print(                                 "Enter Amount:");                             amt = Integer.parseInt(                                 sc.readLine());                              if (bankManagement                                     .transferMoney(                                         senderAc, receiveAc,                                         amt)) {                                 System.out.println(                                     "MSG : Money Sent Successfully!\n");                             }                             else {                                 System.out.println(                                     "ERR :  Failed!\n");                             }                         }                         else if (ch == 2) {                              bankManagement.getBalance(                                 senderAc);                         }                         else if (ch == 5) {                             break;                         }                         else {                             System.out.println(                                 "Err : Enter Valid input!\n");                         }                     }                     catch (Exception e) {                         e.printStackTrace();                     }                 }             }             else {                 return false;             }             // return             return true;         }         catch (SQLIntegrityConstraintViolationException e) {             System.out.println("Username Not Available!");         }         catch (Exception e) {             e.printStackTrace();         }         return false;     }     public static void     getBalance(int acNo) // fetch balance method     {         try {              // query             sql = "select * from customer where ac_no="                   + acNo;             PreparedStatement st                 = con.prepareStatement(sql);              ResultSet rs = st.executeQuery(sql);             System.out.println(                 "-----------------------------------------------------------");             System.out.printf("%12s %10s %10s\n",                               "Account No", "Name",                               "Balance");              // Execution              while (rs.next()) {                 System.out.printf("%12d %10s %10d.00\n",                                   rs.getInt("ac_no"),                                   rs.getString("cname"),                                   rs.getInt("balance"));             }             System.out.println(                 "-----------------------------------------------------------\n");         }         catch (Exception e) {             e.printStackTrace();         }     }     public static boolean transferMoney(int sender_ac,                                         int reveiver_ac,                                         int amount)         throws SQLException // transfer money method     {         // validation         if (reveiver_ac == NULL || amount == NULL) {             System.out.println("All Field Required!");             return false;         }         try {             con.setAutoCommit(false);             sql = "select * from customer where ac_no="                   + sender_ac;             PreparedStatement ps                 = con.prepareStatement(sql);             ResultSet rs = ps.executeQuery();              if (rs.next()) {                 if (rs.getInt("balance") < amount) {                     System.out.println(                         "Insufficient Balance!");                     return false;                 }             }              Statement st = con.createStatement();              // debit             con.setSavepoint();              sql = "update customer set balance=balance-"                   + amount + " where ac_no=" + sender_ac;             if (st.executeUpdate(sql) == 1) {                 System.out.println("Amount Debited!");             }              // credit             sql = "update customer set balance=balance+"                   + amount + " where ac_no=" + reveiver_ac;             st.executeUpdate(sql);              con.commit();             return true;         }         catch (Exception e) {             e.printStackTrace();             con.rollback();         }         // return         return false;     } } 

Purpose: This class will provide all the methods of Bank Management like transferring money, viewing balance, creating an account, and log in.

Note: Create a User Menu Class (bank.java)  in the banking package.

>>bank.java

Java
 package banking;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;  public class bank {     public static void main(String args[]) //main class of bank         throws IOException     {          BufferedReader sc = new BufferedReader(             new InputStreamReader(System.in));         String name = "";         int pass_code;         int ac_no;         int ch;          while (true) {             System.out.println(                 "\n ->||    Welcome to InBank    ||<- \n");             System.out.println("1)Create Account");             System.out.println("2)Login Account");              try {                 System.out.print("\n    Enter Input:"); //user input                  ch = Integer.parseInt(sc.readLine());                  switch (ch) {                 case 1:                     try {                         System.out.print(                             "Enter Unique UserName:");                         name = sc.readLine();                         System.out.print(                             "Enter New Password:");                         pass_code = Integer.parseInt(                             sc.readLine());                          if (bankManagement.createAccount(                                 name, pass_code)) {                             System.out.println(                                 "MSG : Account Created Successfully!\n");                         }                         else {                             System.out.println(                                 "ERR : Account Creation Failed!\n");                         }                     }                     catch (Exception e) {                         System.out.println(                             " ERR : Enter Valid Data::Insertion Failed!\n");                     }                     break;                  case 2:                     try {                         System.out.print(                             "Enter  UserName:");                         name = sc.readLine();                         System.out.print(                             "Enter  Password:");                         pass_code = Integer.parseInt(                             sc.readLine());                          if (bankManagement.loginAccount(                                 name, pass_code)) {                             System.out.println(                                 "MSG : Logout Successfully!\n");                         }                         else {                             System.out.println(                                 "ERR : login Failed!\n");                         }                     }                     catch (Exception e) {                         System.out.println(                             " ERR : Enter Valid Data::Login Failed!\n");                     }                      break;                  default:                     System.out.println("Invalid Entry!\n");                 }                  if (ch == 5) {                     System.out.println(                         "Exited Successfully!\n\n Thank You :)");                     break;                 }             }             catch (Exception e) {                 System.out.println("Enter Valid Entry!");             }         }         sc.close();     } } 

Output: This class provides a Menu-Driven Interface to the Customer where the Customer can create Account, Login Account, Transfer Money, etc. 

Login: 

  ->||    Welcome to InBank    ||<-       1)Create Account     2)Login Account      Enter Input:2 Enter  UserName:pritesh Enter  Password:123

View Balance:

Enter  UserName:pritesh Enter  Password:123 Hallo, pritesh 1)Transfer Money 2)View Balance 5)LogOut Enter Choice:2 -----------------------------------------------------------   Account No       Name    Balance          112    pritesh          0.00 -----------------------------------------------------------

Transfer Money:

Hallo, pritesh 1)Transfer Money 2)View Balance 5)LogOut Enter Choice:1 Enter Receiver  A/c No:110 Enter Amount:5000 Insufficient Balance! ERR :  Failed!

Logout:

Hallo, pritesh 1)Transfer Money 2)View Balance 5)LogOut Enter Choice:5 MSG : Logout Successfully!
Cosole
Console

Next Article
Mini Banking Application in Java

P

priteshyadav444
Improve
Article Tags :
  • Java
  • Java Programs
  • JDBC
Practice Tags :
  • Java

Similar Reads

    GUI Application for the Student Management System
    Prerequisites: Java SwingWrite a program to build a GUI application which provides the details of the college student, about his course and the fees that need to be paid. The fee is calculated and saved in a text file. The program must also be able to print the receipt.   Approach: The concept is ba
    8 min read
    Java File Handling Programs
    Java is a programming language that can create applications that work with files. Files are containers that store data in different formats, such as text, images, videos, etc. Files can be created, read, updated, and deleted using Java. Java provides the File class from the java.io package to handle
    3 min read
    Java Threading Programs - Basic to Advanced
    Java threading is the concept of using multiple threads to execute different tasks in a Java program. A thread is a lightweight sub-process that runs within a process and shares the same memory space and resources. Threads can improve the performance and responsiveness of a program by allowing paral
    3 min read
    How to Create a Package in Java?
    Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related cla
    4 min read
    Simple Calculator using Java Socket Programming
    Prerequisite: Socket Programming in Java First, we understand the basics of java socket programming. Java Socket is used to communicate between two different JREs. Java socket can be connection-oriented or connection-less. In java, we have a package called "java.net". In this package, we have two cl
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences