Let’s create an advanced Java banking application tutorial style. We’ll implement user registration, authentication, account management, and transaction handling. Additionally, I’ll guide you on how to set up SQL in Java using JDBC and how to start the main application.
Setting Up SQL in Java using JDBC
To use JDBC in your Java project, you’ll need to follow these steps:
Download JDBC Driver: Download the JDBC driver for your chosen database (e.g., MySQL, PostgreSQL, SQLite). Include the JDBC driver JAR file in your project’s classpath.
Establish Connection: Use the
java.sql.Connection
interface to establish a connection to your database. You’ll typically need the database URL, username, and password.Create Statements: Use the
java.sql.Statement
orjava.sql.PreparedStatement
interface to execute SQL queries and statements.Handle Results: Use the
java.sql.ResultSet
interface to retrieve data from executed queries.
Main Application Structure
Now, let’s outline the structure of our main application:
User Class: This class will handle user registration, authentication, and password hashing.
BankAccount Class: This class will manage bank accounts, including account creation, balance management, and transaction handling.
BankApp Class: This class will serve as the main entry point of the application. It will provide a user interface for interacting with the banking functionalities.
Implementation
Here’s the implementation of the main classes:
1. User Class
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
public class User {
private Connection conn;
public User() {
// Establish database connection
try {
conn = DriverManager.getConnection("jdbc:sqlite:banking_app.db");
} catch (SQLException e) {
System.err.println("Database connection error: " + e.getMessage());
}
}
// Register a new user
public void register(String username, String password) {
String hashedPassword = hashPassword(password);
try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO users (username, password) VALUES (?, ?)")) {
stmt.setString(1, username);
stmt.setString(2, hashedPassword);
stmt.executeUpdate();
System.out.println("User registered successfully.");
} catch (SQLException e) {
System.err.println("Error registering user: " + e.getMessage());
}
}
// Authenticate user
public boolean authenticate(String username, String password) {
try (PreparedStatement stmt = conn.prepareStatement("SELECT password FROM users WHERE username = ?")) {
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
String hashedPassword = rs.getString("password");
String inputHash = hashPassword(password);
return hashedPassword.equals(inputHash);
}
} catch (SQLException e) {
System.err.println("Error authenticating user: " + e.getMessage());
}
return false;
}
// Hash password using SHA-256 algorithm
private String hashPassword(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = md.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte hashByte : hashBytes) {
String hex = Integer.toHexString(0xff & hashByte);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
System.err.println("Error hashing password: " + e.getMessage());
return null;
}
}
public void closeConnection() {
try {
if (conn != null) conn.close();
} catch (SQLException e) {
System.err.println("Error closing connection: " + e.getMessage());
}
}
}
import java.sql.*;
public class BankAccount {
private Connection conn;
public BankAccount() {
// Establish database connection
try {
conn = DriverManager.getConnection("jdbc:sqlite:banking_app.db");
} catch (SQLException e) {
System.err.println("Database connection error: " + e.getMessage());
}
}
// Create a new bank account for a user
public void createAccount(String username) {
try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO accounts (user_id, balance) VALUES (?, ?)")) {
int userId = getUserId(username);
if (userId != -1) {
stmt.setInt(1, userId);
stmt.setDouble(2, 0); // Initial balance is 0
stmt.executeUpdate();
System.out.println("Account created successfully.");
} else {
System.out.println("User not found.");
}
} catch (SQLException e) {
System.err.println("Error creating account: " + e.getMessage());
}
}
// Deposit funds into a bank account
public void deposit(String username, double amount) {
int accountId = getAccountId(username);
if (accountId != -1) {
try (PreparedStatement stmt = conn.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
stmt.setDouble(1, amount);
stmt.setInt(2, accountId);
stmt.executeUpdate();
System.out.println("Deposit successful.");
} catch (SQLException e) {
System.err.println("Error depositing funds: " + e.getMessage());
}
} else {
System.out.println("Account not found.");
}
}
// Withdraw funds from a bank account
public void withdraw(String username, double amount) {
int accountId = getAccountId(username);
if (accountId != -1) {
double balance = getBalance(accountId);
if (balance >= amount) {
try (PreparedStatement stmt = conn.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE id = ?")) {
stmt.setDouble(1, amount);
stmt.setInt(2, accountId);
stmt.executeUpdate();
System.out.println("Withdrawal successful.");
} catch (SQLException e) {
System.err.println("Error withdrawing funds: " + e.getMessage());
}
} else {
System.out.println("Insufficient funds.");
}
} else {
System.out.println("Account not found.");
}
}
// Display balance of a bank account
public void displayBalance(String username) {
int accountId = getAccountId(username);
if (accountId != -1) {
double balance = getBalance(accountId);
System.out.println("Account balance: " + balance);
} else {
System.out.println("Account not found.");
}
}
// Get user ID from username
private int getUserId(String username) {
try (PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE username = ?")) {
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getInt("id");
}
} catch (SQLException e) {
System.err.println("Error retrieving user ID: " + e.getMessage());
}
return -1;
}
// Get account ID from username
private int getAccountId(String username) {
try (PreparedStatement stmt = conn.prepareStatement("SELECT id FROM accounts WHERE user_id = ?")) {
int userId = getUserId(username);
if (userId != -1) {
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getInt("id");
}
} else {
System.out.println("User not found.");
}
} catch (SQLException e) {
System.err.println("Error retrieving account ID: " + e.getMessage());
}
return -1;
}
// Get balance of a bank account
private double getBalance(int accountId) {
try (PreparedStatement stmt = conn.prepareStatement("SELECT balance FROM accounts WHERE id = ?")) {
stmt.setInt(1, accountId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getDouble("balance");
}
} catch (SQLException e) {
System.err.println("Error retrieving account balance: " + e.getMessage());
}
return 0;
}
public void closeConnection() {
try {
if (conn != null) conn.close();
} catch (SQLException e) {
System.err.println("Error closing connection: " + e.getMessage());
}
}
}
import java.util.Scanner;
public class BankApp {
private User user;
private BankAccount bankAccount;
private Scanner scanner;
public BankApp() {
user = new User();
bankAccount = new BankAccount();
scanner = new Scanner(System.in);
}
public void run() {
System.out.println("Welcome to the BankApp!");
while (true) {
System.out.println("\n1. Register");
System.out.println("2. Login");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
String choice = scanner.nextLine();
switch (choice) {
case "1":
registerUser();
break;
case "2":
loginUser();
break;
case "3":
System.out.println("Goodbye!");
scanner.close();
user.closeConnection();
bankAccount.closeConnection();
return;
default:
System.out.println("Invalid choice.");
}
}
}
private void registerUser() {
System.out.print("Enter username: ");
String username = scanner.nextLine();
System.out.print("Enter password: ");
String password = scanner.nextLine();
user.register(username, password);
}
private void loginUser() {
System.out.print("Enter username: ");
String username = scanner.nextLine();
System.out.print("Enter password: ");
String password = scanner.nextLine();
if (user.authenticate(username, password)) {
System.out.println("Login successful.");
bankAccountMenu(username);
} else {
System.out.println("Login failed.");
}
}
private void bankAccountMenu(String username) {
while (true) {
System.out.println("\n1. Create Account");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Display Balance");
System.out.println("5. Exit");
System.out.print("Enter your option: ");
String option = scanner.nextLine();
switch (option) {
case "1":
bankAccount.createAccount(username);
break;
case "2":
depositFunds(username);
break;
case "3":
withdrawFunds(username);
break;
case "4":
bankAccount.displayBalance(username);
break;
case "5":
System.out.println("Logging out.");
return;
default:
System.out.println("Invalid option.");
}
}
}
private void depositFunds(String username) {
System.out.print("Enter deposit amount: ");
double amount = Double.parseDouble(scanner.nextLine());
bankAccount.deposit(username, amount);
}
private void withdrawFunds(String username) {
System.out.print("Enter withdrawal amount: ");
double amount = Double.parseDouble(scanner.nextLine());
bankAccount.withdraw(username, amount);
}
public static void main(String[] args) {
BankApp bankApp = new BankApp();
bankApp.run();
}
}
Starting the Main Application
To start the main application, create an instance of the BankApp
class and call its run
method. This will start the banking application and provide a menu for user interaction.
public class Main {
public static void main(String[] args) {
BankApp bankApp = new BankApp();
bankApp.run();
}
}
Compile all classes and run the Main
class to start the banking application. You’ll be able to register new users, login, create bank accounts, deposit/withdraw funds, and display account balances.
Welcome to DevTechTutor.com, your ultimate resource for mastering web development and technology! Whether you're a beginner eager to dive into coding or an experienced developer looking to sharpen your skills, DevTechTutor.com is here to guide you every step of the way. Our mission is to make learning web development accessible, engaging, and effective.