JavaPaper
JavaPaper
This chapter is like a quick peek at what Java is all about. Java's parts all work together,
so sometimes explaining one thing means you need to know a bit about another. This
chapter gives you the basics so you can start understanding and writing simple Java
programs.
• Encapsulation: The gas pedal is simple to use (interface), but hides complex
engine mechanics.
• Inheritance: You know how to drive a sedan, so you can probably figure out a
minivan because they inherit from a general "vehicle" concept.
• Polymorphism: You press the brake pedal. Whether you have standard brakes
or anti-lock brakes (different implementations), the pedal (interface) works the
same way to stop the car.
3. A First Simple Java Program - "Hello World!"
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example { // 1. Defines a 'class' named Example
// Your program begins with a call to main().
public static void main(String args[]) { // 2. The starting
point of the program
System.out.println("This is a simple Java program."); //
3. Prints text to the screen
}
}
• File Name: The file must be named Example.java (same as the class name, and
Java cares about uppercase/lowercase).
• Compiling (Building):
1. You type your program into a .java file.
2. You use a command like javac Example.java. This turns your human-
readable code into "bytecode" (a .class file, e.g., Example.class). Computers
don't run .java files directly.
• Running (Executing):
1. You use a command like java Example. This tells the Java system to run
the bytecode in Example.class.
• /* ... */ or // ...: These are comments. They are notes for humans; the computer
ignores them.
• class Example { ... }: This declares a class named Example. All Java code lives
inside classes.
• public static void main(String args[]) { ... }: This is the main method. It's the special
starting point for any Java application.
o public: Means it can be accessed from anywhere.
o static: Means you can run this method without creating an "object" of
the Example class first.
o void: Means this method doesn't return any value when it's done.
o main: This specific name tells Java where to start.
o String args[]: This is a place to receive any arguments you might type on
the command line when you run the program (we're not using it here).
• System.out.println("This is a simple Java program.");:
o System.out: A standard way to access system output (like the screen).
o println(): A method that prints whatever is in the parentheses to the
screen, and then moves to a new line.
• ; (Semicolon): Marks the end of a statement (like a period at the end of a
sentence).
• { } (Curly Braces): Define blocks of code, like the body of the class or the body of
the method.
Variables are like named boxes where you can store information.
class Example2 {
public static void main(String args[]) {
int num; // 1. Declares an integer variable named 'num'
num = 100; // 2. Assigns the value 100 to 'num'
Output:
This is num: 100
The value of num * 2 is 200
• int num;: Declares a variable named num that will hold whole numbers (integers).
• num = 100;: Assigns the value 100 to num. The = is the assignment operator.
• "This is num: " + num: The + sign here joins the text string with the value
of num (which is converted to text) before printing.
• System.out.print(): Similar to println(), but it doesn't move to a new line after
printing.
You can group multiple statements together using curly braces { }. This "block" is then
treated as a single unit.
This is useful for if statements or for loops that need to do more than one thing.
if (x < y) { // If x is less than y...
System.out.println("x is smaller"); // ...do this
x = y; // ...and then do this
} // End of block
These are the fundamental pieces that make up your Java program:
• Whitespace: Spaces, tabs, newlines. Java mostly uses them to separate things
and make code readable. Extra whitespace is usually ignored.
• Identifiers: Names you give to things like classes, methods, and variables
(e.g., Example, main, num).
o Rules: Can use letters, numbers, _, $.
o Cannot start with a number.
o Java is case-sensitive (myVariable is different from MyVariable).
• Literals: The actual values you write in your code.
o 100 (integer literal)
o 98.6 (floating-point literal)
o 'X' (character literal - single quotes)
o "This is a string" (string literal - double quotes)
• Comments:
o // Single-line comment
o /* Multi-line comment */
o /** Documentation comment (special type for generating help files) */
• Separators: Characters that help structure the code.
o (): For method parameters, expressions.
o {}: For code blocks.
o []: For arrays.
o ;: Terminates statements.
o ,: Separates items in a list (like variable declarations).
o .: Used to access members of a class or package.
• Keywords: Special reserved words that have specific meanings in Java
(e.g., class, public, static, void, int, if, for). You cannot use these as names for
your variables or methods. (The text shows a table of these).
o true, false, null are also reserved.
8. The Java Class Libraries - Java's Built-in Toolkit
Java comes with a huge collection of pre-written code called class libraries (or APIs).
These libraries provide tons of useful tools and functions for things like:
A big part of learning Java is learning how to use these built-in libraries. You don't have
to reinvent the wheel for common tasks.
In a Nutshell:
Chapter 2 gives you a bird's-eye view of Java. It emphasizes that Java is all about
"objects" (OOP), introduces the core OOP ideas (Encapsulation, Inheritance,
Polymorphism), shows you how to write, compile, and run simple programs, and
touches on the basic syntax elements and the existence of powerful built-in libraries.
Chapter 9
Packages and Interfaces
• Think of it like: Folders on your computer. You put related files (classes) into a
folder (package) to keep things organized and avoid having two files with the
same name in the same place.
• Why use them?
o Organization: Keeps your project tidy, especially large ones.
o Avoid Name Clashes: You can have a class named List in your package,
and Java can have its own List class in its java.util package, and they
won't get confused.
o Control Access: You can decide which classes or methods are visible
only within the package, and which can be used by code outside the
package.
• How to Define a Package:
o Put package packageName; as the very first line in your Java file.
o Example: package com.mycompany.projectname;
o The .class files must be stored in a directory structure that matches the
package name. So, for com.mycompany.projectname.MyClass,
the MyClass.class file would be in a folder path
like com/mycompany/projectname/.
• The "Default Package": If you don't write a package statement, your class goes
into an unnamed "default" package. This is okay for small examples, but not for
real projects.
• How Java Finds Packages:
1. Current Directory: It looks in the current folder and its subfolders.
2. CLASSPATH: An environment variable that tells Java other places to look
for packages. (Don't worry too much about this for simple examples).
• Access Control with Packages:
o public: Anyone, anywhere can access it.
o private: Only accessible within the same class.
o protected: Accessible within the same package, AND by subclasses (even
if those subclasses are in different packages).
o No keyword (default/package-private): Accessible only by other classes
in the same package.
// File: mytools/MyHelper.java
package mytools; // This class is in the 'mytools' package
To Compile and Run (from the folder containing App.java and the mytools folder):
1. javac mytools/MyHelper.java
2. javac App.java
3. java App
Output:
Hello, World from MyHelper!
File 1: Playable.java
// File: Playable.java
interface Playable {
void playSound(); // This is the "contract" - any Playable
must have this
// String getInstrumentType(); // You could add more methods
to the contract
}
File 2: Guitar.java
// File: Guitar.java
class Guitar implements Playable {
// This class "implements" the Playable interface,
// so it MUST provide the playSound() method.
@Override // Good practice to use @Override
public void playSound() { // Must be public
System.out.println("Strumming guitar chords!");
}
}
File 3: Piano.java
// File: Piano.java
class Piano implements Playable {
@Override
public void playSound() { // Must be public
System.out.println("Playing a beautiful piano melody.");
}
}
File 4: MusicPlayer.java (The main application)
// File: MusicPlayer.java
public class MusicPlayer {
public static void main(String[] args) {
Playable myGuitar = new Guitar(); // A Guitar IS-A
Playable
Playable myPiano = new Piano(); // A Piano IS-A
Playable
To Compile and Run (if all files are in the same directory):
Output:
Strumming guitar chords!
Playing a beautiful piano melody.
Band practice:
Strumming guitar chords!
Playing a beautiful piano melody.
Strumming guitar chords!
• Packages: Like folders to keep your Java classes organized and avoid name
fights.
• Interfaces: Like a checklist of tasks (methods) a class promises to do. If a class
says "I implement this interface," it must do all those tasks. This lets different
types of classes be treated in a similar way if they promise to do the same tasks.
Chapter 10
Exception Handling
What is an Exception?
An "exception" is like an unexpected problem that happens while you're baking. For
example:
These are "run-time errors" – problems that occur when the program is actually running.
} catch (ArithmeticException e) {
// What to do if the specific "ArithmeticException"
happens
System.out.println("Oops! You can't divide by
zero.");
System.out.println("Error was: " + e.getMessage());
// Get a short description
}
Output:
Trying to divide...
Oops! You can't divide by zero.
Error was: / by zero
Program continues after the try-catch block.
Without try-catch, the program would crash. With try-catch, we handled the error
gracefully.
Before division.
Exception in thread "main" java.lang.ArithmeticException: / by
zero
at Uncaught.main(Uncaught.java:4)
// Finally Example
public class FinallyDemoSimple {
public static void main(String[] args) {
try {
System.out.println("Inside try block.");
int riskyValue = 10 / 2; // Change to 10 / 0 to see
it with an exception
System.out.println("Result: " + riskyValue);
} catch (ArithmeticException e) {
System.out.println("Caught an arithmetic error!");
} finally {
System.out.println("This finally block always runs,
error or not!");
}
System.out.println("After try-catch-finally.");
}
}
If 10 / 2:
If 10 / 0:
// Throw Example
public class ThrowDemoSimple {
static void checkAge(int age) {
if (age < 18) {
// We decide this is an error condition
throw new ArithmeticException("Access denied - You
must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old
enough.");
}
}
Output:
If a method might cause an exception that it doesn't handle itself, it must declare it
using throws. This mainly applies to "checked exceptions" (more serious ones like file
errors, network errors). ArithmeticException is "unchecked," so you don't have to
declare it, but it's good practice if a method is designed to throw it.
Output:
If main didn't try-catch the readFile call that throws IOException, the
compiler would give an error.
Types of Exceptions
All exceptions are objects. They come from a main class Throwable.
• Error: Very serious problems, usually outside your program's control (like
running out of memory). You typically don't try to catch these.
• Exception: Problems that your program can often recover from (bad user input,
file not found, etc.). These are the ones you usually catch.
o RuntimeException: A special kind
of Exception (like ArithmeticException, NullPointerExceptio
n, ArrayIndexOutOfBoundsException). These are "unchecked" –
the compiler doesn't force you to use try-catch or throws for them,
though you often should handle them.
o Other Exceptions (like IOException): These are "checked" – the
compiler forces you to either handle them with try-catch or declare
them with throws.
Output:
Output:
Chapter 13
String Handling
1. Creating Strings:
o The easiest way:
o String greeting = "Hello, World!"; // This is a string
literal
String name = "Alice";
Use this when you know you'll be modifying a string many times, like building it up in a
loop.
1. Creating StringBuffer:
2. StringBuffer sb1 = new StringBuffer(); // Starts empty,
default capacity
3. StringBuffer sb2 = new StringBuffer("Initial Text"); //
Starts with some text
StringBuffer sb3 = new StringBuffer(50); // Starts empty,
but reserves space for 50 chars
• String:
o For text that won't change.
o Most of the time, for simple text representation.
o When passing text around (methods, etc.) because they are inherently
safe from modification.
• StringBuilder (or StringBuffer if thread safety is a must):
o When you need to build a string in a loop.
o When you are performing many modifications (append, insert, delete) on a
sequence of characters.
o String s = ""; for (int i=0; i<1000; i++) { s = s + i;
} <-- BAD performance! This creates 1000 new String objects.
o StringBuilder sb = new StringBuilder(); for (int i=0;
i<1000; i++) { sb.append(i); } String s =
sb.toString(); <-- GOOD performance! Modifies one object.
Chapter 14
Exploring java.lang
java.lang is like the most basic toolbox for any Java programmer. You get it
automatically in every Java program; you don't even need to write import
java.lang.*; because Java does it for you. It contains the essential building blocks.
Java has basic types like int (for whole numbers), double (for decimal
numbers), char (for single characters), and boolean (for true/false). These are fast
but are not "objects." Sometimes, you need them to act like objects (e.g., to store them
in collections like ArrayList). Wrapper classes "wrap" these basic types into objects.
• Number (The Parent): This is an abstract class, like a blueprint for all numeric
wrapper classes. You don't use it directly often.
• Integer (for int):
o Purpose: Wraps an int value into an object. Also provides utility
methods for int.
o Key uses: Converting a String to an int, storing int in collections.
o Example:
o public class IntegerExample {
o public static void main(String[] args) {
o // Convert String to int
o String numStr = "123";
o int number = Integer.parseInt(numStr);
o System.out.println("String to int: " + (number
+ 7)); // Output: 130
o
o // Wrap an int into an Integer object
o Integer myIntObject = Integer.valueOf(42);
o System.out.println("Integer object value: " +
myIntObject.intValue()); // Output: 42
o }
}
• Long (for long): Similar to Integer, but for larger whole numbers (long).
• Short (for short): Similar to Integer, but for smaller whole numbers
(short).
• Byte (for byte): Similar to Integer, but for very small whole numbers (byte).
• Double (for double):
o Purpose: Wraps a double (decimal) value.
o Key uses: Converting String to double, special values like NaN (Not a
Number), POSITIVE_INFINITY.
o Example:
o public class DoubleExample {
o public static void main(String[] args) {
o Double d1 = Double.valueOf("3.14");
o System.out.println("Double from String: " +
d1.doubleValue()); // Output: 3.14
o
o Double infiniteVal = Double.POSITIVE_INFINITY;
o Double nanVal = Double.NaN; // Not a Number
(e.g., 0.0 / 0.0)
o
o System.out.println("Is d1 infinite? " +
d1.isInfinite()); // Output: false
o System.out.println("Is infiniteVal infinite? "
+ infiniteVal.isInfinite()); // Output: true
o System.out.println("Is nanVal NaN? " +
nanVal.isNaN()); // Output: true
o }
}
• Float (for float): Similar to Double, but for float (less precise decimal)
values.
• Character (for char):
o Purpose: Wraps a char value. Provides many utility methods for
characters.
o Key uses: Checking if a character is a digit, letter, uppercase, etc.
o Example:
o public class CharacterExample {
o public static void main(String[] args) {
o char myChar = 'A';
o Character charObj = Character.valueOf(myChar);
o
o System.out.println("Is '" + myChar + "' a
letter? " + Character.isLetter(myChar)); // Output:
true
o System.out.println("Is '7' a digit? " +
Character.isDigit('7')); // Output: true
o System.out.println("Is ' ' whitespace? " +
Character.isWhitespace(' ')); // Output: true
o }
}
• Boolean (for boolean):
o Purpose: Wraps a boolean (true/false) value.
o Example:
o public class BooleanExample {
o public static void main(String[] args) {
o Boolean boolTrue = Boolean.valueOf(true);
o Boolean boolFromString =
Boolean.valueOf("TrUe"); // Case-insensitive "true"
o
o System.out.println("boolTrue: " +
boolTrue.booleanValue()); // Output: true
o System.out.println("boolFromString: " +
boolFromString.booleanValue()); // Output: true
o }
}
• Void: Represents the void keyword as a type. You rarely use this directly.
Every class in Java is a descendant of Object, whether you say so or not. It provides
some fundamental methods that all objects have.
• Key Methods:
o equals(Object obj): Checks if two objects are "equal" (you often
override this).
o hashCode(): Returns a number representing the object (used in hash-
based collections).
o toString(): Returns a String representation of the object (you often
override this to make it meaningful).
o getClass(): Tells you what class an object belongs to.
o clone(): Creates a copy of an object (needs Cloneable interface).
• Example (toString, getClass):
• class Person {
• String name;
• Person(String name) { this.name = name; }
•
• @Override // Overriding toString for better output
• public String toString() {
• return "Person[name=" + name + "]";
• }
• }
•
• public class ObjectExample {
• public static void main(String[] args) {
• Person p = new Person("Ali");
• System.out.println(p.toString()); // Output:
Person[name=Ali]
• System.out.println("Class of p: " +
p.getClass().getName()); // Output: Person
• }
}
• Purpose: When you need to change text a lot (e.g., building a long string piece
by piece), String is
inefficient. StringBuffer and StringBuilder are mutable (can be
changed).
o StringBuffer: Thread-safe (slower, use if multiple threads might
change it).
o StringBuilder: Not thread-safe (faster, use if only one thread changes
it - most common case).
• Example (StringBuilder):
• public class StringBuilderExample {
• public static void main(String[] args) {
• StringBuilder sb = new StringBuilder("Hi");
• sb.append(" "); // Add to the end
• sb.append("There");
• sb.insert(0, "Oh, "); // Insert at the beginning
•
• System.out.println(sb.toString()); // Output: Oh,
Hi There
• }
}
• Purpose: Provides common math functions. All its methods are static, so you
call them on the class itself (e.g., Math.sqrt()).
• Key Methods: sqrt() (square root), pow() (power), abs() (absolute
value), max(), min(), random() (random number), sin(), cos(), PI, E.
• Example:
• public class MathExample {
• public static void main(String[] args) {
• System.out.println("Square root of 25: " +
Math.sqrt(25)); // Output: 5.0
• System.out.println("2 to the power of 3: " +
Math.pow(2, 3)); // Output: 8.0
• System.out.println("A random number (0-1): " +
Math.random());
• System.out.println("Value of PI: " + Math.PI);
• }
}
• StrictMath: Similar to Math, but guarantees bit-for-bit identical results across
all Java platforms for its floating-point operations. This might come at a slight
performance cost.
• Purpose: Allows your program to interface with the environment in which it's
running.
• Key Methods:
o Runtime.getRuntime(): Gets the current Runtime object.
o freeMemory(), totalMemory(): Get information about memory.
o gc(): Suggests garbage collection (like System.gc()).
o exec(String command): Executes an external program/command (can
be risky and platform-dependent).
• Example:
• public class RuntimeExample {
• public static void main(String[] args) {
• Runtime runtime = Runtime.getRuntime();
•
• System.out.println("Total Memory: " +
runtime.totalMemory() + " bytes");
• System.out.println("Free Memory: " +
runtime.freeMemory() + " bytes");
•
• runtime.gc(); // Suggest garbage collection
• System.out.println("Free Memory after GC
suggestion: " + runtime.freeMemory() + " bytes");
•
• /*
• // Example of running an external command (e.g.,
'notepad' on Windows)
• // Be careful with exec(), it can have security
implications.
• try {
• // Process p = runtime.exec("notepad.exe"); //
For Windows
• // Process p = runtime.exec("gedit"); // For
some Linux
• // p.waitFor(); // Wait for the process to
finish
• // System.out.println("External program
finished.");
• } catch (Exception e) {
• System.err.println("Error executing external
program: " + e.getMessage());
• }
• */
• }
}
• ClassLoader: Responsible for loading class files into the JVM. Advanced topic.
• Compiler: Provides access to the Java compiler. Rarely used directly in typical
applications.
• SecurityManager: Used to define and enforce security policies. Advanced
topic.
• Throwable: The parent class for all errors and exceptions in Java. If something
goes wrong, an object of a class derived from Throwable is "thrown."
o Example (conceptual, exceptions are covered in more detail
elsewhere):
o public class ThrowableExample {
o public static void main(String[] args) {
o try {
o int result = 10 / 0; // This will cause an
ArithmeticException
o System.out.println(result);
o } catch (ArithmeticException e) { //
ArithmeticException is a subclass of Throwable
o System.err.println("Oops, an error: " +
e.getMessage());
o // e.printStackTrace(); // Prints detailed
error info
o }
o }
}
• Package: Represents package information (like version details).
• StackTraceElement: Represents a single "stack frame" in an error's stack
trace (tells you where in the code an error happened).
• RuntimePermission: Related to Java's security model for runtime operations.
Interfaces in java.lang:
Sub-packages of java.lang:
Let's create a simple Java Swing Student Form with CRUD (Create, Read, Update,
Delete) operations connected to a MySQL database.
Complete Procedure:
1. Install Java Development Kit (JDK): Make sure you have JDK installed.
2. Install VS Code: Download and install Visual Studio Code.
3. Install Java Extensions for VS Code:
o Open VS Code.
o Go to the Extensions view (Ctrl+Shift+X).
o Search for "Extension Pack for Java" by Microsoft and install it. This will
install several useful Java extensions.
4. Download MySQL Connector/J:
o Go to the MySQL Connector/J download
page: https://dev.mysql.com/downloads/connector/j/
o Select "Platform Independent" and download the ZIP or TAR archive.
o Extract the archive. You will find a .jar file like mysql-connector-j-
X.X.XX.jar (e.g., mysql-connector-j-8.0.33.jar).
5. Create a New Java Project in VS Code:
o Open the Command Palette (Ctrl+Shift+P).
o Type "Java: Create Java Project".
o Select "No build tools".
o Choose a location for your project (e.g., StudentFormApp).
o Enter a project name (e.g., StudentFormApp).
6. Add MySQL Connector/J to Project:
o Inside your project folder (e.g., StudentFormApp), create a folder
named lib.
o Copy the mysql-connector-j-X.X.XX.jar file into this lib folder.
o In VS Code's Explorer, right-click on the .jar file under the lib folder
and select "Add to Classpath".
o Alternatively, VS Code might prompt you or you can manually edit
the .classpath file (if it exists) or configure it via the Java Projects view.
A simpler way is often:
▪ Open the Command Palette (Ctrl+Shift+P).
▪ Type "Java: Configure Classpath".
▪ Go to "Referenced Libraries" and click the "+" icon.
▪ Navigate to your lib folder and select the mysql-connector-j-
X.X.XX.jar file.
1. DBConnection.java
// src/DBConnection.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// 2. Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);
System.out.println("Connected database
successfully...");
} catch (SQLException se) {
System.err.println("SQL Exception: " +
se.getMessage());
se.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("MySQL JDBC Driver not found: " +
e.getMessage());
e.printStackTrace();
}
return conn;
}
Important:
2. StudentForm.java
// src/StudentForm.java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
// GUI Components
private JTextField txtName, txtRollNumber, txtDepartment;
private JButton btnAdd, btnView, btnUpdate, btnDelete,
btnClear;
private JTable studentTable;
private DefaultTableModel tableModel;
private JScrollPane scrollPane;
// Database Connection
private Connection conn;
public StudentForm() {
// Initialize Database Connection
conn = DBConnection.getConnection();
if (conn == null) {
JOptionPane.showMessageDialog(this, "Failed to
connect to database. Exiting.", "Database Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1); // Exit if DB connection fails
}
// Frame Setup
setTitle("Student Management System");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window
setLayout(new BorderLayout(10, 10)); // Main layout
inputPanel.add(new JLabel("Name:"));
txtName = new JTextField();
inputPanel.add(txtName);
inputPanel.add(new JLabel("Department:"));
txtDepartment = new JTextField();
inputPanel.add(txtDepartment);
add(inputPanel, BorderLayout.NORTH);
buttonPanel.add(btnAdd);
buttonPanel.add(btnView);
buttonPanel.add(btnUpdate);
buttonPanel.add(btnDelete);
buttonPanel.add(btnClear);
add(buttonPanel, BorderLayout.SOUTH);
txtName.setText(tableModel.getValueAt(selectedRow,
1).toString());
txtRollNumber.setText(tableModel.getValueAt(selectedRow,
2).toString());
txtDepartment.setText(tableModel.getValueAt(selectedRow,
3).toString());
txtRollNumber.setEditable(false); // Don't
allow editing roll number when updating via selection
}
}
});
if (name.isEmpty() || rollNumber.isEmpty()) {
JOptionPane.showMessageDialog(this, "Name and Roll
Number are required!", "Input Error",
JOptionPane.ERROR_MESSAGE);
return;
}
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String rollNumber = rs.getString("roll_number");
String department = rs.getString("department");
tableModel.addRow(new Object[]{id, name,
rollNumber, department});
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error fetching
students: " + ex.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
if (rollNumber.isEmpty()) {
JOptionPane.showMessageDialog(this, "Select a
student or enter Roll Number to update.", "Input Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (name.isEmpty()) {
JOptionPane.showMessageDialog(this, "Name cannot be
empty for update.", "Input Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (rollNumber.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please select a
student from the table or enter their Roll Number to delete.",
"Input Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (confirm == JOptionPane.YES_OPTION) {
String sql = "DELETE FROM students WHERE roll_number
= ?";
try (PreparedStatement pstmt =
conn.prepareStatement(sql)) {
pstmt.setString(1, rollNumber);
int affectedRows = pstmt.executeUpdate();
if (affectedRows > 0) {
JOptionPane.showMessageDialog(this, "Student
deleted successfully!");
clearFields();
viewStudents(); // Refresh table
} else {
JOptionPane.showMessageDialog(this, "Student
with Roll Number '" + rollNumber + "' not found.", "Delete
Error", JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Database
error: " + ex.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
Alternatively, VS Code might show a "Run" link above the main method.
• DBConnection.java:
o Handles creating a connection to your MySQL database.
o Crucially, update DB_URL, USER, and PASS with your actual MySQL
credentials.
• StudentForm.java:
o GUI Components: JTextField for inputs, JButton for
actions, JTable to display data, DefaultTableModel to manage table
data.
o Layouts: BorderLayout for the main frame, GridLayout for the input
form, FlowLayout for buttons.
o Constructor (StudentForm()):
▪ Sets up the JFrame.
▪ Initializes DBConnection.getConnection().
▪ Creates and arranges all GUI components.
▪ Attaches ActionListeners to buttons to trigger methods when
clicked.
▪ Attaches a MouseAdapter to the JTable so when you click a
row, its data populates the input fields.
▪ Calls viewStudents() initially to load data.
o addStudent():
▪ Gets data from text fields.
▪ Constructs an SQL INSERT statement
using PreparedStatement (good for preventing SQL injection).
▪ Executes the statement.
▪ Shows a message and refreshes the table.
o viewStudents():
▪ Clears the current table.
▪ Executes an SQL SELECT query.