📚 Unit 3 — Index

☕ Java Programming

Unit 3 — Event Handling, AWT, Applets, Servlets & JDBC

🎯 Chapter 1 — Event Handling, AWT, Applets & Servlets
🗺️ CHAPTER 1 — MIND MAP
Delegation Event Model → Source generates event → Listener handles → Register using addXxxListener()
Events → ActionEvent (click) | MouseEvent (mouse) | KeyEvent (keyboard) | WindowEvent | ItemEvent | TextEvent
Listeners → ActionListener → actionPerformed() | MouseListener → mouseClicked() | KeyListener → keyPressed()
Adapter Classes → MouseAdapter, KeyAdapter, WindowAdapter — extend instead of implement, override only needed methods
Applet Life Cycle → init() → start() → paint(g) → stop() → destroy()
AWT Hierarchy → Component → Container → Panel / Window → Frame / Dialog
AWT Components → Label, Button, TextField, TextArea, Checkbox, CheckboxGroup, Choice, List, Scrollbar, Canvas
Layouts → FlowLayout (Panel default) | BorderLayout (Frame default) | GridLayout | CardLayout
Servlets → init() → service() → doGet()/doPost() → destroy() | Advantages over CGI: thread-based, fast, secure

1. Delegation Event Model

📖 Definition: The Delegation Event Model is the standard mechanism in Java for handling GUI events. When a user interacts with a component (clicks button, presses key), the event is delegated from the source component to a registered listener object for processing. Introduced in Java 1.1 to replace the old inheritance-based model.
💡 Real-Life Analogy:
Think of a fire alarm system in a building:
Source = Smoke sensor (detects fire, raises alarm)
Event Object = Alert signal (carries location, time, type of alert)
Listener = Fire department (registered to handle alarms, takes action)

The sensor doesn't fight the fire — it delegates the task to the fire department!
🔑 Three Key Components:
ComponentRoleExamplesHow Created
SourceGenerates the event when user interactsButton, TextField, Checkbox, MouseInstantiated: new Button("OK")
Event ObjectEncapsulates information about the eventActionEvent, MouseEvent, KeyEventAuto-created by JVM when event fires
ListenerReceives and handles the eventActionListener, MouseListenerImplement interface; register on source
USER ACTION (click button / press key) ↓ SOURCE (e.g. Button) — generates EventObject ↓ EVENT OBJECT (ActionEvent) carries: source, time, command ↓ LISTENER (registered via addActionListener) ↓ Handler method fires → actionPerformed(e) → YOUR CODE RUNS ✓
Delegation Event Model — Complete Flow
3 Steps to Use Delegation Event Model:
Step 1 — Implement: Create a class implementing listener interface
   class MyClass implements ActionListener { ... }
Step 2 — Register: Attach listener to source component
   button.addActionListener(myClassObject);
Step 3 — Override: Implement the handler method
   public void actionPerformed(ActionEvent e) { /* handle */ }
import java.awt.*; import java.awt.event.*; // Step 1: Implement ActionListener public class ButtonDemo extends Frame implements ActionListener { Button btn; Label lbl; int clickCount = 0; public ButtonDemo() { btn = new Button("Click Me!"); lbl = new Label("No clicks yet"); // Step 2: Register listener (this class IS the listener) btn.addActionListener(this); setLayout(new FlowLayout()); add(lbl); add(btn); setTitle("Event Demo"); setSize(300, 120); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); } // Step 3: Override handler method public void actionPerformed(ActionEvent e) { clickCount++; lbl.setText("Clicked " + clickCount + " time(s) | Cmd: " + e.getActionCommand()); } public static void main(String[] args) { new ButtonDemo(); } } // Output: Window opens. On each click label updates with count and command name.

2. Events, Event Classes & Listener Interfaces

📖 Event: An event is an object that describes a state change in a source. It is created by the JVM when user interacts with the GUI. All events inherit from java.util.EventObject. Java provides a rich set of event classes in java.awt.event package.
Event ClassTrigger ConditionListener InterfaceKey Methods to Override
ActionEventButton click, Enter in TextField, Menu selectActionListeneractionPerformed(ActionEvent e)
MouseEventMouse click, press, release, move, drag, enter, exitMouseListener / MouseMotionListenermouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), mouseExited()
KeyEventKey pressed, released, or typed on keyboardKeyListenerkeyPressed(), keyReleased(), keyTyped()
WindowEventWindow opened, closed, minimized, restoredWindowListenerwindowOpened(), windowClosing(), windowClosed()
ItemEventCheckbox/radio/choice selection changedItemListeneritemStateChanged(ItemEvent e)
TextEventText changed in TextField or TextAreaTextListenertextValueChanged(TextEvent e)
FocusEventComponent gains or loses focusFocusListenerfocusGained(), focusLost()
AdjustmentEventScrollbar value changedAdjustmentListeneradjustmentValueChanged()
Key Methods of ActionEvent:
ActionEvent methods:
getActionCommand() — returns the label/name of the button that was clicked
getSource() — returns the object that generated the event
getModifiers() — returns modifier keys pressed (Shift, Ctrl, Alt)
getWhen() — returns timestamp when event occurred
MouseListener Full Example:
import java.awt.*; import java.awt.event.*; public class MouseDemo extends Frame implements MouseListener { Label lbl = new Label("Move/click mouse here", Label.CENTER); public MouseDemo() { lbl.addMouseListener(this); // Register add(lbl); setSize(350, 150); setVisible(true); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){dispose();} }); } public void mouseClicked(MouseEvent e) { lbl.setText("Clicked at ("+e.getX()+","+e.getY()+")"); } public void mousePressed(MouseEvent e) { lbl.setText("Mouse Pressed!"); } public void mouseReleased(MouseEvent e) { lbl.setText("Mouse Released!"); } public void mouseEntered(MouseEvent e) { lbl.setBackground(Color.CYAN); } public void mouseExited(MouseEvent e) { lbl.setBackground(null); } public static void main(String[] a) { new MouseDemo(); } } // Output: Hover → background turns cyan. Click → shows coordinates.
KeyListener Example:
import java.awt.*; import java.awt.event.*; public class KeyDemo extends Frame implements KeyListener { TextField tf = new TextField(20); Label lbl = new Label("Type something..."); public KeyDemo() { tf.addKeyListener(this); setLayout(new FlowLayout()); add(lbl); add(tf); setSize(350, 100); setVisible(true); } public void keyPressed(KeyEvent e) { lbl.setText("Pressed: " + KeyEvent.getKeyText(e.getKeyCode())); } public void keyReleased(KeyEvent e) { lbl.setText("Released: " + e.getKeyChar()); } public void keyTyped(KeyEvent e) { /* called for printable chars */ } public static void main(String[] a) { new KeyDemo(); } } // Output: Press 'A' → "Pressed: A" → "Released: a"

3. Adapter Classes

📖 Adapter Classes: Abstract classes that provide empty (do-nothing) implementations of all methods in a listener interface. They solve the problem of having to implement ALL methods of an interface even when you only need one or two.
💡 Problem & Solution:
Problem: MouseListener has 5 methods. If you implement it, you MUST define all 5 — even the ones you don't use.

Solution: Extend MouseAdapter — it implements all 5 as empty methods. Override only what you need!
Adapter ClassCorresponding InterfaceMethods Count
MouseAdapterMouseListener5 methods
MouseMotionAdapterMouseMotionListener2 methods
KeyAdapterKeyListener3 methods
WindowAdapterWindowListener7 methods
FocusAdapterFocusListener2 methods
ComponentAdapterComponentListener4 methods
import java.awt.*; import java.awt.event.*; public class AdapterDemo extends Frame { Label lbl = new Label("Use mouse and keyboard"); public AdapterDemo() { setLayout(new FlowLayout()); add(lbl); // Using MouseAdapter — only override mouseClicked (rest are empty) addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { lbl.setText("Clicked at: " + e.getX() + "," + e.getY()); } }); // Using KeyAdapter — only override keyPressed addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { lbl.setText("Key: " + KeyEvent.getKeyText(e.getKeyCode())); } }); // Using WindowAdapter — only override windowClosing addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); setTitle("Adapter Demo"); setSize(300, 120); setVisible(true); } public static void main(String[] a) { new AdapterDemo(); } } // Clean! No need to implement all 5/7/3 methods, just the ones we need.
💡 Note: You cannot use Adapter classes when your class already extends another class (since Java doesn't support multiple inheritance). In that case, implement the listener interface directly OR use anonymous inner classes (as shown above).

4. Applet & Life Cycle of Applet

📖 What is an Applet?
An Applet is a small Java program designed to run inside a web browser or Applet Viewer. It provides a way to embed interactive Java programs in HTML web pages.

Package: java.applet
Extends: java.applet.Applet class
Run with: appletviewer filename.html
Note: Applets are deprecated from Java 9+ but still in exam syllabus
💡 Analogy:
A regular Java application is a standalone shop. An applet is a kiosk inside a shopping mall (browser) — it cannot run alone, lives inside the browser, but performs tasks within it.
Life Cycle of Applet — 5 Methods:
init()
start()
paint(g)
stop()
destroy()
Applet Life Cycle — Called in this order by browser/JVM
MethodWhen CalledCalled How Many TimesPurpose
init()Applet is first loadedONCE onlyInitialize variables, set up GUI, set background. Use instead of constructor.
start()After init(); also when user returns to pageMultiple timesStart or resume execution, start threads/animations
paint(Graphics g)Window needs drawing/redrawingMultiple timesDraw text, shapes, images using Graphics object
stop()User leaves the page / minimizesMultiple timesPause activities, stop threads to save resources
destroy()Browser closes / applet removedONCE onlyFinal cleanup — release memory, close connections
import java.applet.*; import java.awt.*; /* HTML to run: <applet code="LifeCycleDemo.class" width="400" height="220"> <param name="student" value="Ankush"> </applet> */ public class LifeCycleDemo extends Applet { String studentName; int visitCount = 0; int paintCount = 0; // 1. init() — called ONCE at first load public void init() { studentName = getParameter("student"); // Read HTML param if (studentName == null) studentName = "Guest"; setBackground(Color.WHITE); System.out.println("1. init() — Name: " + studentName); } // 2. start() — called after init() and on each page revisit public void start() { visitCount++; System.out.println("2. start() — Visit #" + visitCount); repaint(); // trigger paint() } // 3. paint() — called to draw on applet public void paint(Graphics g) { paintCount++; g.setFont(new Font("Arial", Font.BOLD, 16)); g.setColor(Color.BLUE); g.drawString("Hello, " + studentName + "!", 30, 40); g.setColor(Color.BLACK); g.drawString("Visit count: " + visitCount, 30, 70); g.drawString("Paint count: " + paintCount, 30, 95); // Draw shapes g.setColor(Color.RED); g.fillOval(30, 120, 60, 60); g.setColor(Color.GREEN); g.fillRect(120, 120, 80, 60); g.setColor(Color.ORANGE); g.drawRoundRect(230, 115, 100, 70, 15, 15); g.setColor(Color.GRAY); g.drawString("3. paint() called #" + paintCount, 30, 200); } // 4. stop() — called when user leaves page public void stop() { System.out.println("4. stop() called"); } // 5. destroy() — called when applet removed public void destroy() { System.out.println("5. destroy() — Bye!"); } } /* Console Output: 1. init() — Name: Ankush 2. start() — Visit #1 [user leaves page] 4. stop() called [user returns] 2. start() — Visit #2 [browser closes] 4. stop() called → 5. destroy() — Bye! */
Applet vs Application:
FeatureAppletApplication
Runs inBrowser / AppletViewerJVM (standalone)
Entry pointinit() methodmain() method
InheritanceMust extend AppletNo mandatory inheritance
HTML tag<applet> tag requiredNot needed
SecuritySandbox restrictions (no file/network)Full system access
Life cycleManaged by browser (5 methods)Starts & ends with main()
ConstructorNot used — use init()Can use constructor
💡 Important Applet Facts:
repaint() calls paint() again — use for animation
showStatus("message") shows text in browser status bar
getParameter("name") reads value from HTML <param> tag
getCodeBase() returns URL where applet code is located
• Graphics methods: drawString, drawLine, drawRect, fillRect, drawOval, fillOval, drawArc, fillArc

5. Abstract Window Toolkit (AWT) — Components

📖 AWT (Abstract Window Toolkit):
AWT is Java's original GUI framework in java.awt package. It provides platform-dependent GUI components — each AWT component maps to a native OS widget (uses OS rendering). AWT is the foundation on which Swing is built.
AWT Class Hierarchy:
java.lang.Object └── java.awt.Component (abstract base — all GUI elements) ├── Button, Label, TextField, TextArea ├── Checkbox, Choice, List, Scrollbar, Canvas └── java.awt.Container (can hold other components) ├── java.awt.Panel (no title bar — groups components) └── java.awt.Window (top-level, no title bar) ├── java.awt.Frame ← MAIN WINDOW (title, border, buttons) ✓ └── java.awt.Dialog ← Popup window
AWT Class Hierarchy — Know this for exams!
ClassDescriptionKey Methods
ComponentAbstract base of all GUI widgets. Cannot be instantiated.setSize(), setVisible(), setBackground(), setFont(), setEnabled()
ContainerCan hold other components using layout manageradd(), remove(), setLayout(), getComponents()
PanelSimple container. No title bar. Used to group components.Inherits Container methods. Default layout: FlowLayout
WindowTop-level window with no decorations (no title/border)setLocation(), toFront(), dispose()
FrameMain application window with title bar, border, min/max/close buttonssetTitle(), setSize(), setVisible(), setResizable()
CanvasBlank rectangular area for custom drawingOverride paint(Graphics g) to draw
All AWT Components with Code:
import java.awt.*; import java.awt.event.*; public class AllComponentsDemo extends Frame implements ActionListener { // Declare all components Label lblName, lblCity, lblResult; TextField tfName; TextArea taAddress; Checkbox cbJava, cbPython; CheckboxGroup genderGroup; Checkbox rbMale, rbFemale; Choice cityChoice; List skillList; Scrollbar slider; Button btnSubmit; public AllComponentsDemo() { setLayout(null); // Manual (absolute) positioning // 1. LABEL — displays non-editable text lblName = new Label("Name:"); lblName.setBounds(20, 30, 80, 25); add(lblName); // 2. TEXTFIELD — single-line text input tfName = new TextField("Enter name", 20); tfName.setBounds(110, 30, 200, 25); add(tfName); // 3. TEXTAREA — multi-line text input lblCity = new Label("Address:"); lblCity.setBounds(20, 70, 80, 25); taAddress = new TextArea("City, State", 4, 25); // 4 rows, 25 cols taAddress.setBounds(110, 70, 200, 70); add(lblCity); add(taAddress); // 4. CHECKBOX — toggle (can select multiple) cbJava = new Checkbox("Java", true); // pre-checked cbPython = new Checkbox("Python", false); cbJava.setBounds(20, 155, 100, 25); cbPython.setBounds(130, 155, 100, 25); add(cbJava); add(cbPython); // 5. RADIO BUTTONS — CheckboxGroup makes them mutually exclusive genderGroup = new CheckboxGroup(); rbMale = new Checkbox("Male", genderGroup, true); rbFemale = new Checkbox("Female", genderGroup, false); rbMale.setBounds(20, 190, 80, 25); rbFemale.setBounds(110, 190, 90, 25); add(rbMale); add(rbFemale); // 6. CHOICE — dropdown (select ONE item) cityChoice = new Choice(); cityChoice.add("Delhi"); cityChoice.add("Mumbai"); cityChoice.add("Ludhiana"); cityChoice.add("Bangalore"); cityChoice.select("Ludhiana"); // default selection cityChoice.setBounds(20, 225, 180, 25); add(cityChoice); // 7. LIST — visible list (can allow multi-select) skillList = new List(3, true); // 3 rows, multi-select = true skillList.add("HTML"); skillList.add("CSS"); skillList.add("Java"); skillList.add("SQL"); skillList.setBounds(210, 225, 100, 65); add(skillList); // 8. SCROLLBAR — sliding value control slider = new Scrollbar(Scrollbar.HORIZONTAL, 50, 10, 0, 110); // (orientation, initialValue, visibleAmount, min, max) slider.setBounds(20, 300, 290, 20); add(slider); // 9. BUTTON — clickable btnSubmit = new Button("Submit"); btnSubmit.addActionListener(this); btnSubmit.setBounds(110, 335, 100, 30); add(btnSubmit); // 10. RESULT LABEL lblResult = new Label(""); lblResult.setBounds(20, 375, 310, 25); add(lblResult); setTitle("All AWT Components"); setSize(360, 420); setVisible(true); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){dispose();} }); } public void actionPerformed(ActionEvent e) { String name = tfName.getText(); String gender = genderGroup.getSelectedCheckbox().getLabel(); String city = cityChoice.getSelectedItem(); String java = cbJava.getState() ? "Java" : ""; lblResult.setText(name + " | " + gender + " | " + city + " | " + java); } public static void main(String[] a) { new AllComponentsDemo(); } } // Output: Fill form → click Submit → result label shows: "Ankush | Male | Ludhiana | Java"
Canvas — Custom Drawing Area:
import java.awt.*; import java.awt.event.*; class DrawCanvas extends Canvas { public void paint(Graphics g) { // Draw various shapes g.setColor(Color.RED); g.fillRect(20, 20, 100, 60); g.setColor(Color.BLUE); g.fillOval(140, 20, 80, 80); g.setColor(Color.GREEN); g.drawRoundRect(240, 20, 90, 60, 20, 20); g.setColor(Color.ORANGE); g.fillArc(20, 110, 100, 80, 0, 270); g.setColor(Color.BLACK); g.drawLine(0, 200, 350, 200); g.setFont(new Font("Arial", Font.BOLD, 14)); g.setColor(Color.MAGENTA); g.drawString("Java AWT Canvas Drawing", 30, 230); } } public class CanvasDemo extends Frame { public CanvasDemo() { DrawCanvas c = new DrawCanvas(); c.setSize(360, 250); c.setBackground(Color.WHITE); add(c); setTitle("Canvas Demo"); setSize(380, 280); setVisible(true); } public static void main(String[] a) { new CanvasDemo(); } }

6. Layout Managers

📖 Layout Manager: A layout manager automatically arranges components inside a container. It controls the size and position of each component. Without it, you would have to manually position every component using setBounds(x, y, w, h).

Set Layout: container.setLayout(new FlowLayout());
1. FlowLayout — Default for Panel & Applet
FlowLayout: Arranges components in a row from left to right. When the row is full, starts a new row. Components maintain their preferred size.
┌─────────────────────────────────────────┐ │ [Button1] [Button2] [Button3] │ │ [Button4] [Button5] │ └─────────────────────────────────────────┘ FlowLayout(FlowLayout.LEFT, 10, 5) → hgap=10, vgap=5 Alignment options: FlowLayout.LEFT | CENTER | RIGHT
setLayout(new FlowLayout()); // CENTER alignment, gap=5 setLayout(new FlowLayout(FlowLayout.LEFT)); // Left aligned setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 8)); // Right, hgap=10, vgap=8 // Usage: add(new Button("Home")); add(new Button("About")); add(new Button("Contact")); // Components are added left to right automatically
2. GridLayout — Equal-Size Grid
GridLayout: Divides container into a rectangular grid of equal-sized cells. Components are placed row by row, left to right. All cells have the same size.
GridLayout(3, 3, 5, 5) → 3 rows × 3 cols, hgap=5, vgap=5 ┌──────────┬──────────┬──────────┐ │ [7] │ [8] │ [9] │ ├──────────┼──────────┼──────────┤ │ [4] │ [5] │ [6] │ ├──────────┼──────────┼──────────┤ │ [1] │ [2] │ [3] │ └──────────┴──────────┴──────────┘ Perfect for: calculator keypads, calendars, game boards
setLayout(new GridLayout(3, 3, 5, 5)); // 3 rows, 3 cols, gaps=5 String[] keys = {"7","8","9","4","5","6","1","2","3","0",".","+/-"}; for (String k : keys) { add(new Button(k)); // Added left-to-right, top-to-bottom }
3. BorderLayout — Default for Frame & Dialog
BorderLayout: Divides container into 5 regions: NORTH, SOUTH, EAST, WEST, and CENTER. CENTER region expands to fill all remaining space.
┌─────────────────────────────────────┐ │ NORTH │ ├──────────┬──────────────┬───────────┤ │ │ │ │ │ WEST │ CENTER │ EAST │ │ │ (expands!) │ │ ├──────────┴──────────────┴───────────┤ │ SOUTH │ └─────────────────────────────────────┘ Only CENTER is required. Others are optional.
// BorderLayout is DEFAULT for Frame — no need to set it // But can set explicitly: setLayout(new BorderLayout(5, 5)); // hgap=5, vgap=5 add(new Button("NORTH"), BorderLayout.NORTH); add(new Button("SOUTH"), BorderLayout.SOUTH); add(new Button("EAST"), BorderLayout.EAST); add(new Button("WEST"), BorderLayout.WEST); add(new TextArea("CENTER — This expands!"), BorderLayout.CENTER);
4. CardLayout — One Panel at a Time
CardLayout: Treats the container as a deck of cards — only one panel is visible at a time. Others are hidden behind. Used for tabbed panes, wizards, multi-step forms.
CardLayout — deck of panels: Card 1 [HOME visible] Card 2 [ABOUT hidden] Card 3 [CONTACT hidden] ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │ Home Content │ │ About Content │ │ Contact Form │ └────────────────┘ └────────────────┘ └────────────────┘ cl.show(p,"home") → cl.next(p) → cl.previous(p) → cl.first(p)
import java.awt.*; import java.awt.event.*; public class CardLayoutDemo extends Frame implements ActionListener { CardLayout cl = new CardLayout(); Panel cardPanel = new Panel(); Button prev, next; public CardLayoutDemo() { cardPanel.setLayout(cl); // Create pages Panel home = new Panel(); home.add(new Label("🏠 Home Page")); home.setBackground(Color.PINK); Panel about = new Panel(); about.add(new Label("ℹ️ About Page")); about.setBackground(Color.CYAN); Panel contact = new Panel(); contact.add(new Label("📧 Contact")); contact.setBackground(Color.YELLOW); // Add to CardLayout with names cardPanel.add(home, "home"); cardPanel.add(about, "about"); cardPanel.add(contact, "contact"); prev = new Button("◀ Prev"); next = new Button("Next ▶"); prev.addActionListener(this); next.addActionListener(this); Panel nav = new Panel(); nav.add(prev); nav.add(next); Button goHome = new Button("Go Home"); goHome.addActionListener(e -> cl.show(cardPanel, "home")); nav.add(goHome); add(cardPanel, BorderLayout.CENTER); add(nav, BorderLayout.SOUTH); setTitle("CardLayout"); setSize(350, 200); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == next) cl.next(cardPanel); else cl.previous(cardPanel); } public static void main(String[] a) { new CardLayoutDemo(); } }
💡 Layout Manager Summary:
  • FlowLayout — left to right, wraps. Default: Panel, Applet. Use: nav bars, simple forms
  • GridLayout — equal cells. No default. Use: calculators, game boards, login grids
  • BorderLayout — 5 regions. Default: Frame, Dialog. Use: most application windows
  • CardLayout — one at a time. No default. Use: tabs, wizards, multi-step forms
  • null layout — manual: setLayout(null) + setBounds(x,y,w,h)

7. Servlets

📖 Servlet: A Servlet is a Java class that runs on a web/application server (like Apache Tomcat) and handles HTTP requests from clients (web browsers). It generates dynamic web content (HTML, JSON, XML) in response.

Package: javax.servlet and javax.servlet.http
Key Class: HttpServlet (extends GenericServlet)
Deploy on: Apache Tomcat, JBoss, GlassFish
💡 Analogy:
Browser (you) enters restaurant. Waiter takes your order (request) to kitchen (servlet). Kitchen prepares food (processes data) and sends it back (HTML response). You didn't need to go to the kitchen!
Servlet Life Cycle — 3 Phases:
init()
Once — load
service()
Each request
doGet() / doPost()
Handle request
destroy()
Once — shutdown
Servlet Life Cycle
MethodWhen CalledTimesPurpose
init()First request or server startupONCEOne-time initialization — DB connections, config loading
service()Every HTTP requestPer requestRoutes to doGet() or doPost() based on HTTP method
doGet()GET request (URL params)Per GET reqRead URL params: req.getParameter("name")
doPost()POST request (form data)Per POST reqRead form fields securely (not visible in URL)
destroy()Server shutdown / undeploymentONCECleanup — close DB connections, log shutdown
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // A complete Servlet example — Student Login public class LoginServlet extends HttpServlet { public void init() throws ServletException { System.out.println("LoginServlet initialized!"); } // Handles GET request: http://localhost:8080/app/login?user=Raj&pass=1234 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String user = req.getParameter("user"); String pass = req.getParameter("pass"); processLogin(user, pass, res); } // Handles POST request (form submission — data hidden from URL) public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String user = req.getParameter("user"); String pass = req.getParameter("pass"); processLogin(user, pass, res); } private void processLogin(String user, String pass, HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><head><title>Login Result</title></head><body>"); if ("admin".equals(user) && "1234".equals(pass)) { out.println("<h2 style='color:green'>✓ Login Successful!</h2>"); out.println("<p>Welcome, " + user + "!</p>"); } else { out.println("<h2 style='color:red'>✗ Login Failed!</h2>"); out.println("<p>Invalid username or password.</p>"); } out.println("<a href='index.html'>← Back to Login</a>"); out.println("</body></html>"); } public void destroy() { System.out.println("LoginServlet destroyed!"); } } // URL: http://localhost:8080/myapp/login?user=admin&pass=1234 // Output: Login Successful! Welcome, admin!
Servlet vs CGI Comparison:
FeatureServletCGI (Common Gateway Interface)
Per RequestNew thread (lightweight)New process (heavyweight)
PerformanceFast — threads share memorySlow — each process is separate
LanguageJava (platform independent)C, Perl (platform dependent)
MemoryLow (threads share JVM)High (each process has own memory)
StateCan maintain sessions (HttpSession)Stateless
SecurityJava Security Manager protectsLess secure
ScalabilityHighly scalableLimited scalability
✅ Advantages of Servlets:
Platform independent — runs on any OS with JVM
High performance — thread-based request handling
Powerful APIs — HttpSession, cookies, RequestDispatcher
Database integration — easy JDBC connectivity inside doGet/doPost
Secure — POST hides sensitive data; Java security model
Persistent — servlet stays in memory between requests (unlike CGI)
🗄️ Chapter 2 — Database Connectivity (JDBC)
🗺️ CHAPTER 2 — JDBC MIND MAP
JDBC = Java DataBase Connectivity — API in java.sql to connect Java programs to RDBMS
Architecture → Java App → JDBC API → DriverManager → JDBC Driver → Database
4 Driver Types → Type1 (JDBC-ODBC, deprecated) | Type2 (Native API) | Type3 (Network Protocol) | Type4 ⭐ (Pure Java — preferred)
Essential Classes → DriverManager (connect) | Connection (session) | Statement (execute) | PreparedStatement (safe, fast) | ResultSet (data) | SQLException (errors)
6 Steps → Load Driver → Get Connection → Create Statement → Execute Query → Process ResultSet → Close All
CRUD → INSERT / SELECT (executeQuery→ResultSet) / UPDATE / DELETE (executeUpdate→int rows)
PreparedStatement → Uses ? placeholders → setString/setInt → safe from SQL Injection → faster (precompiled)
Transaction → setAutoCommit(false) → do operations → commit() or rollback()

1. Introduction to JDBC — What, Why & Architecture

📖 JDBC (Java DataBase Connectivity):
JDBC is a standard Java API in the java.sql package that provides a uniform way for Java programs to interact with relational databases using SQL (Structured Query Language).

Full Form: Java DataBase Connectivity
Developed by: Sun Microsystems (now part of Oracle JDK)
Used for: Connecting to databases and executing SQL queries — SELECT, INSERT, UPDATE, DELETE
💡 Real-Life Analogy:
JDBC is like a waiter in a restaurant:
• You (Java program) give your order (SQL query)
• Waiter (JDBC) takes the order to the kitchen (database)
• Kitchen prepares food (executes query, returns data)
• Waiter brings it back (ResultSet)

Without JDBC, you'd need to speak each kitchen's language (MySQL protocol, Oracle protocol etc.) — impossible! JDBC gives ONE standard language.
Why JDBC? — Need and Advantages:
✅ Advantages of JDBC:
1. Platform Independent — Java's WORA; same code on Windows, Linux, Mac
2. Database Independent — change driver to switch DB; your code stays same
3. Easy to Use — simple method calls like executeQuery(), getInt(), getString()
4. Secure — PreparedStatement prevents SQL Injection attacks
5. Transaction Support — commit() and rollback() for data integrity
6. Rich API — supports stored procedures, batch updates, scrollable ResultSets
7. Scalable — from simple apps to large enterprise systems
JDBC Architecture:
┌──────────────────────────────────────────────────────┐ │ JAVA APPLICATION │ │ (Your Java code: StudentMgmt.java, Shop.java etc.) │ └────────────────────────┬─────────────────────────────┘ │ uses ▼ ┌──────────────────────────────────────────────────────┐ │ JDBC API (java.sql package) │ │ DriverManager, Connection, Statement, ResultSet... │ └────────────────────────┬─────────────────────────────┘ │ managed by ▼ ┌──────────────────────────────────────────────────────┐ │ JDBC DRIVER MANAGER │ │ Loads drivers, matches URL to correct driver │ └──────────────┬───────────────────────────┬───────────┘ │ │ ▼ ▼ ┌──────────────────┐ ┌──────────────────────┐ │ MySQL Driver │ │ Oracle Driver │ │ (Type 4, .jar) │ │ (Type 4, .jar) │ └────────┬─────────┘ └──────────┬────────────┘ │ │ ▼ ▼ ┌──────────────────┐ ┌──────────────────────┐ │ MySQL DB │ │ Oracle DB │ └──────────────────┘ └──────────────────────┘
JDBC Architecture — Two-layer design (API + Driver API)
FeatureTwo-Tier ArchitectureThree-Tier Architecture
StructureJava App → directly → DBJava App → App Server → DB
Middle LayerNoneTomcat, JBoss, GlassFish
SecurityLower (DB exposed to client)Higher (DB hidden behind server)
Use CaseSimple desktop/lab appsWeb apps, enterprise apps
ScalabilityLimitedHighly scalable

2. JDBC Driver Types — All 4 Types

📖 JDBC Driver: A JDBC Driver is a software component (usually a .jar file) that enables Java programs to interact with a specific database. It translates JDBC API calls into database-specific protocol calls. There are 4 types of drivers, each with different implementation approaches.
TypeNameHow it WorksProsCons
Type 1JDBC-ODBC BridgeJDBC → ODBC → DB. Needs ODBC driver installed.Easy setup, works with any ODBC DBSlowest, requires ODBC installation, deprecated in Java 8 ✗
Type 2Native-API Driver (Partial Java)JDBC → Native DB API (C/C++) → DBFaster than Type 1Platform dependent, native libs required, not fully Java ✗
Type 3Network Protocol Driver (Middleware)JDBC → Middleware Server → DB Protocol → DBFlexible, works over networkNeeds extra middleware server, complex setup ✗
Type 4 ⭐Thin Driver (Pure Java)JDBC directly → DB-specific protocol → DBFastest, pure Java, platform-independent, most popularDB-specific (need different jar per DB) — minor inconvenience
💡 Type 4 — What to use in practice:
MySQL: Driver class = com.mysql.cj.jdbc.Driver | JAR = mysql-connector-java-x.x.x.jar
Oracle: Driver class = oracle.jdbc.driver.OracleDriver | JAR = ojdbc8.jar
PostgreSQL: Driver class = org.postgresql.Driver | JAR = postgresql-x.x.jar
SQLite: Driver class = org.sqlite.JDBC | JAR = sqlite-jdbc.jar

3. Essential JDBC Classes & Interfaces

Class/InterfaceTypePurposeKey Methods
DriverManagerClassManages JDBC drivers; creates ConnectiongetConnection(url, user, pass)
ConnectionInterfaceRepresents active DB session/connectioncreateStatement(), prepareStatement(sql), setAutoCommit(b), commit(), rollback(), close()
StatementInterfaceSends simple SQL to DB; no parametersexecuteQuery(sql), executeUpdate(sql), execute(sql), close()
PreparedStatementInterfacePrecompiled SQL with ? placeholders; safe & fastsetString(i,v), setInt(i,v), setDouble(i,v), executeQuery(), executeUpdate()
ResultSetInterfaceHolds rows returned by SELECT querynext(), getString(col), getInt(col), getDouble(col), first(), last(), close()
CallableStatementInterfaceCalls stored procedures in databaseexecute(), registerOutParameter()
SQLExceptionClassException for database errorsgetMessage(), getErrorCode(), getSQLState()
ResultSetMetaDataInterfaceInformation about ResultSet columnsgetColumnCount(), getColumnName(i), getColumnType(i)
DatabaseMetaDataInterfaceInformation about the database itselfgetDatabaseProductName(), getTables()
MethodUsed ForReturnsExample
executeQuery(sql)SELECT statements ONLYResultSetResultSet rs = stmt.executeQuery("SELECT * FROM students");
executeUpdate(sql)INSERT, UPDATE, DELETE, DDL (CREATE TABLE)int (rows affected)int n = stmt.executeUpdate("INSERT INTO ...");
execute(sql)Any SQL when type unknownboolean (true if ResultSet)boolean b = stmt.execute(anySql);
ResultSet Navigation:
rs.next() — moves cursor to next row; returns false when no more rows
• ResultSet cursor starts BEFORE the first row — always call rs.next() before reading
• Column index in getXxx(index) starts at 1, not 0
• For scrollable ResultSet: con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)

4. The 6 Steps — Database Connectivity

1. Load Driver
2. Connect
3. Statement
4. Execute
5. ResultSet
6. Close
Always follow this EXACT order! ← Exam Critical
Step 1 — Load the JDBC Driver:
Class.forName("com.mysql.cj.jdbc.Driver");
Loads driver class into JVM memory. From JDBC 4.0+, auto-done if JAR is in classpath.

Step 2 — Establish Connection:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "pass");
URL Format: jdbc:subprotocol://host:port/dbName

Step 3 — Create Statement:
Statement stmt = con.createStatement(); OR
PreparedStatement ps = con.prepareStatement(sql);

Step 4 — Execute SQL Query:
SELECT: ResultSet rs = stmt.executeQuery("SELECT * FROM students");
Others: int rows = stmt.executeUpdate("INSERT INTO ...");

Step 5 — Process ResultSet (for SELECT):
while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); }

Step 6 — Close All Resources (reverse order):
rs.close(); stmt.close(); con.close();
💡 MySQL URL: jdbc:mysql://localhost:3306/databaseName
Oracle URL: jdbc:oracle:thin:@localhost:1521:orcl
Close Order: ResultSet → Statement → Connection (reverse of creation!)
MySQL Setup — Run this SQL first:
-- Create database and table (run in MySQL/MariaDB first) CREATE DATABASE college; USE college; CREATE TABLE students ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, marks INT DEFAULT 0, city VARCHAR(30), email VARCHAR(80) ); INSERT INTO students (name, marks, city, email) VALUES ('Raj', 85, 'Delhi', 'raj@email.com'), ('Priya', 92, 'Mumbai', 'priya@email.com'), ('Amit', 78, 'Bangalore', 'amit@email.com'), ('Neha', 65, 'Ludhiana', 'neha@email.com'); SELECT * FROM students;
Complete Connection Program:
import java.sql.*; public class JDBCConnection { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college"; Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Step 1: Load driver Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("Step 1: Driver loaded!"); // Step 2: Connect con = DriverManager.getConnection(url, "root", "password"); System.out.println("Step 2: Connected to 'college' database!"); // Step 3: Create Statement stmt = con.createStatement(); System.out.println("Step 3: Statement created!"); // Step 4: Execute query rs = stmt.executeQuery("SELECT * FROM students ORDER BY marks DESC"); System.out.println("Step 4: Query executed!\n"); // Step 5: Process ResultSet System.out.printf("%-4s %-12s %-6s %-12s%n", "ID", "Name", "Marks", "City"); System.out.println("-".repeat(38)); while (rs.next()) { System.out.printf("%-4d %-12s %-6d %-12s%n", rs.getInt("id"), rs.getString("name"), rs.getInt("marks"), rs.getString("city")); } } catch (ClassNotFoundException e) { System.out.println("ERROR: Driver not found! " + e.getMessage()); } catch (SQLException e) { System.out.println("SQL ERROR: " + e.getMessage()); System.out.println("Error Code: " + e.getErrorCode()); } finally { // Step 6: Always close in finally block! try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); System.out.println("\nStep 6: All resources closed!"); } catch (SQLException e) { e.printStackTrace(); } } } } /* Output: Step 1: Driver loaded! Step 2: Connected to 'college' database! Step 3: Statement created! Step 4: Query executed! ID Name Marks City -------------------------------------- 2 Priya 92 Mumbai 1 Raj 85 Delhi 3 Amit 78 Bangalore 4 Neha 65 Ludhiana Step 6: All resources closed! */

5. INSERT & SELECT — CRUD Operations

INSERT — Adding Data:
INSERT Operation: Use SQL INSERT INTO with executeUpdate().
Returns: int — number of rows inserted (should be 1 for single insert).
import java.sql.*; import java.util.Scanner; public class InsertDemo { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); System.out.print("Enter name: "); String name = sc.nextLine(); System.out.print("Enter marks: "); int marks = sc.nextInt(); sc.nextLine(); System.out.print("Enter city: "); String city = sc.nextLine(); Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college", "root", "password"); // Method 1: Statement (AVOID for user input — SQL Injection risk!) // String sql = "INSERT INTO students(name,marks,city) VALUES('" + name + "'," + marks + ",'" + city + "')"; // Method 2: PreparedStatement (ALWAYS use for user input) PreparedStatement ps = con.prepareStatement( "INSERT INTO students(name, marks, city) VALUES(?, ?, ?)"); ps.setString(1, name); // Position 1 = first ? ps.setInt(2, marks); // Position 2 = second ? ps.setString(3, city); // Position 3 = third ? int rows = ps.executeUpdate(); // Execute INSERT System.out.println(rows > 0 ? "✓ Inserted successfully!" : "✗ Insert failed!"); ps.close(); con.close(); } } /* Input: name=Ravi, marks=88, city=Chennai Output: ✓ Inserted successfully! */
SELECT — Retrieving Data:
SELECT Operation: Use SQL SELECT with executeQuery().
Returns: ResultSet — use rs.next() to iterate rows.
import java.sql.*; public class SelectDemo { public static void main(String[] args) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college", "root", "password"); Statement stmt = con.createStatement(); // 1. Get ALL records ResultSet rs = stmt.executeQuery("SELECT * FROM students"); System.out.println("--- All Students ---"); while (rs.next()) { System.out.println(rs.getInt("id") + " | " + rs.getString("name") + " | " + rs.getInt("marks") + " | " + rs.getString("city")); } // 2. Filtered SELECT with PreparedStatement (safe!) PreparedStatement ps = con.prepareStatement( "SELECT name, marks FROM students WHERE marks > ? ORDER BY marks DESC"); ps.setInt(1, 80); ResultSet rs2 = ps.executeQuery(); System.out.println("\n--- Students scoring > 80 ---"); while (rs2.next()) { System.out.println(rs2.getString("name") + " → " + rs2.getInt("marks")); } // 3. Aggregate functions ResultSet rs3 = stmt.executeQuery( "SELECT COUNT(*) AS total, AVG(marks) AS avg, MAX(marks) AS top FROM students"); if (rs3.next()) { System.out.printf("%nTotal: %d | Avg: %.1f | Top: %d%n", rs3.getInt("total"), rs3.getDouble("avg"), rs3.getInt("top")); } rs.close(); rs2.close(); rs3.close(); stmt.close(); ps.close(); con.close(); } } /* Output: --- All Students --- 1 | Raj | 85 | Delhi 2 | Priya | 92 | Mumbai 3 | Amit | 78 | Bangalore 4 | Neha | 65 | Ludhiana --- Students scoring > 80 --- Priya → 92 Raj → 85 Total: 4 | Avg: 80.0 | Top: 92 */

6. UPDATE & DELETE Operations

UPDATE — Modifying Data:
import java.sql.*; public class UpdateDemo { public static void main(String[] args) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college", "root", "password"); // Update marks for a specific student PreparedStatement ps = con.prepareStatement( "UPDATE students SET marks = ? WHERE id = ?"); ps.setInt(1, 95); // new marks ps.setInt(2, 2); // student id int rows = ps.executeUpdate(); System.out.println("Updated: " + rows + " row(s)"); // Verify ResultSet rs = con.createStatement().executeQuery( "SELECT name, marks FROM students WHERE id=2"); if (rs.next()) System.out.println("Now: " + rs.getString("name") + " → " + rs.getInt("marks")); ps.close(); con.close(); } } /* ⚠️ WITHOUT WHERE: UPDATE students SET marks=100; → ALL rows updated! Always include WHERE clause! Output: Updated: 1 row(s) Now: Priya → 95 */
DELETE — Removing Data:
import java.sql.*; public class DeleteDemo { public static void main(String[] args) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college", "root", "password"); // Delete a specific student PreparedStatement ps = con.prepareStatement( "DELETE FROM students WHERE id = ?"); ps.setInt(1, 4); // Delete student with id=4 int rows = ps.executeUpdate(); if (rows > 0) System.out.println("✓ Deleted " + rows + " student(s)!"); else System.out.println("✗ No student found with that ID"); // Delete by condition — remove students with marks < 40 PreparedStatement ps2 = con.prepareStatement( "DELETE FROM students WHERE marks < ?"); ps2.setInt(1, 40); System.out.println("Failed students removed: " + ps2.executeUpdate()); ps.close(); ps2.close(); con.close(); } } /* ⚠️ WITHOUT WHERE: DELETE FROM students; → ALL rows deleted! Output: ✓ Deleted 1 student(s)! Failed students removed: 0 */
⚠️ DANGER — Always use WHERE clause!
UPDATE students SET marks=100; → Updates ALL students to 100!
DELETE FROM students; → Deletes ALL records permanently!
DELETE FROM students WHERE id=3; → Safe ✓

DELETE vs TRUNCATE vs DROP:
• DELETE — removes specific rows (can rollback) ✓
• TRUNCATE — removes all rows faster (no rollback)
• DROP — removes entire table permanently ✗

7. PreparedStatement & Complete CRUD Program

📖 PreparedStatement:
A PreparedStatement is a precompiled SQL statement that accepts parameters via ? placeholders. It is the recommended way to execute SQL in JDBC for user input.

Create: PreparedStatement ps = con.prepareStatement("INSERT INTO t VALUES(?,?,?)");
Fill: ps.setString(1, name); ps.setInt(2, marks);
Execute: ps.executeUpdate(); or ps.executeQuery();
Setter MethodJava TypeSQL Column TypeExample
setString(pos, val)StringVARCHAR, CHAR, TEXTps.setString(1, "Ankush")
setInt(pos, val)intINT, INTEGER, TINYINTps.setInt(2, 88)
setDouble(pos, val)doubleDOUBLE, DECIMAL, FLOATps.setDouble(3, 9.5)
setBoolean(pos, val)booleanBOOLEAN, TINYINT(1)ps.setBoolean(4, true)
setDate(pos, date)java.sql.DateDATEps.setDate(5, Date.valueOf("2024-01-15"))
setNull(pos, type)nullAny nullable columnps.setNull(3, Types.INTEGER)
FeatureStatementPreparedStatement
SQL CompilationCompiled on EVERY executionCompiled ONCE, reused → faster
ParametersEmbedded in SQL string (risky)? placeholders (safe)
SQL Injection⚠️ Vulnerable✓ Protected — params are data, not code
PerformanceSlower for repeated queriesFaster for repeated queries
Code QualityMessy string concatenationClean, readable
Create viacon.createStatement()con.prepareStatement(sql)
Complete CRUD — Student Management System:
import java.sql.*; public class StudentCRUD { static final String URL = "jdbc:mysql://localhost:3306/college"; static final String USER = "root"; static final String PASS = "password"; static Connection connect() throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(URL, USER, PASS); } // CREATE — Insert new student static void insert(String name, int marks, String city) throws Exception { try (Connection c = connect(); PreparedStatement ps = c.prepareStatement( "INSERT INTO students(name,marks,city) VALUES(?,?,?)")) { ps.setString(1,name); ps.setInt(2,marks); ps.setString(3,city); System.out.println("✓ Inserted: " + name + " (" + ps.executeUpdate() + " row)"); } } // READ — Display all students static void readAll() throws Exception { try (Connection c = connect(); Statement s = c.createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM students ORDER BY id")) { System.out.println("\nID | Name | Marks | City"); System.out.println("---+------------+-------+----------"); while (rs.next()) System.out.printf("%-3d| %-10s | %-5d | %s%n", rs.getInt("id"), rs.getString("name"), rs.getInt("marks"), rs.getString("city")); } } // UPDATE — Modify marks static void update(int id, int newMarks) throws Exception { try (Connection c = connect(); PreparedStatement ps = c.prepareStatement( "UPDATE students SET marks=? WHERE id=?")) { ps.setInt(1,newMarks); ps.setInt(2,id); int r = ps.executeUpdate(); System.out.println(r>0 ? "✓ Updated ID "+id+" → marks="+newMarks : "✗ ID not found"); } } // DELETE — Remove a student static void delete(int id) throws Exception { try (Connection c = connect(); PreparedStatement ps = c.prepareStatement( "DELETE FROM students WHERE id=?")) { ps.setInt(1,id); int r = ps.executeUpdate(); System.out.println(r>0 ? "✓ Deleted ID "+id : "✗ ID not found"); } } public static void main(String[] args) throws Exception { System.out.println("=== Student Management System ===\n"); insert("Ankush", 92, "Ludhiana"); insert("Simran", 88, "Chandigarh"); readAll(); update(1, 95); delete(4); readAll(); } } /* Output: === Student Management System === ✓ Inserted: Ankush (1 row) ✓ Inserted: Simran (1 row) ID | Name | Marks | City ---+------------+-------+---------- 1 | Raj | 85 | Delhi 2 | Priya | 92 | Mumbai 3 | Amit | 78 | Bangalore 4 | Neha | 65 | Ludhiana 5 | Ankush | 92 | Ludhiana 6 | Simran | 88 | Chandigarh ✓ Updated ID 1 → marks=95 ✓ Deleted ID 4 ID | Name | Marks | City 1 | Raj | 95 | Delhi 2 | Priya | 92 | Mumbai 3 | Amit | 78 | Bangalore 5 | Ankush | 92 | Ludhiana 6 | Simran | 88 | Chandigarh */
💡 JDBC Best Practices:
  • Always use PreparedStatement for user-supplied data (prevents SQL Injection)
  • Always close in reverse order: ResultSet → Statement → Connection
  • Use try-with-resources — auto-closes resources even if exception occurs
  • Use transactions for multi-step operations: setAutoCommit(false) → commit()/rollback()
  • Column index in PreparedStatement starts at 1, not 0!
  • ResultSet cursor is BEFORE first row — call rs.next() before reading any data
Ready for Exam? Sab padh liya? Ab Quick Revision karo — life cycles, tables, key points aur exam tips ek jagah! Quick Revision Karo →
⚡ Quick Revision — Last Minute Notes
📌 How to Use: Read this 5–10 minutes before exam. Contains all important points in condensed form. Focus on life cycles, tables, and key topics!

🎯 Delegation Event Model (IMP!)

3 Components:
1. Source — generates event (Button, TextField, Mouse, Checkbox)
2. Event Object — carries info (ActionEvent, MouseEvent, KeyEvent, WindowEvent)
3. Listener — handles event (ActionListener, MouseListener, KeyListener)
3 Steps: Implement interface → Register (btn.addActionListener(this)) → Override method (actionPerformed(e))
// Minimum pattern — memorize this! btn.addActionListener(e -> label.setText("Cmd: " + e.getActionCommand())); // OR: implement ActionListener and override actionPerformed(ActionEvent e)
Event ClassListener InterfaceKey Method(s)
ActionEventActionListeneractionPerformed(e)
MouseEventMouseListenermouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), mouseExited()
KeyEventKeyListenerkeyPressed(), keyReleased(), keyTyped()
WindowEventWindowListenerwindowOpened(), windowClosing(), windowClosed()
ItemEventItemListeneritemStateChanged(e)
Adapter Classes — provide empty implementations of all interface methods so you override only what you need:
MouseAdapter (5 methods) | KeyAdapter (3 methods) | WindowAdapter (7 methods)

🍎 Applet Life Cycle (5M)

5 Methods in correct order:
1. init() — ONCE at first load. Initialize variables, set up GUI. Use instead of constructor.
2. start() — After init() + every page revisit. Start/resume execution.
3. paint(Graphics g) — Draw graphics on applet. drawString(), fillRect(), fillOval(), fillArc()
4. stop() — User leaves page / minimizes. Pause tasks to save resources.
5. destroy() — ONCE at end. Final cleanup.
AppletApplication
Runs in browser/AppletViewerRuns in JVM standalone
No main() neededmain() is entry point
Extends java.applet.AppletNo mandatory inheritance
init() for setup (no constructor)Constructor/main() for setup
Sandbox securityFull system access
Exam Tip: repaint() calls paint() again | getParameter("name") reads HTML param | showStatus() → browser status bar

🧩 AWT Components (2M)

Hierarchy: Object → Component → Container → Panel → Window → Frame ✓

Label("text") — display text, non-editable
Button("text") — clickable, generates ActionEvent
TextField(cols) — single-line input. getText(), setText()
TextArea(rows, cols) — multi-line input
Checkbox("label") — toggle on/off | CheckboxGroup → radio buttons (mutually exclusive)
Choice — dropdown: ch.add("item"), ch.getSelectedItem()
List(rows, multiSelect) — visible list, can allow multi-select
Scrollbar — sliding control: new Scrollbar(HORIZONTAL, val, vis, min, max)
Canvas — blank drawing area: override paint(Graphics g)

📐 Layout Managers (5M)

LayoutHow it ArrangesDefault ForUse Case
FlowLayoutLeft→Right, wraps to next rowPanel, AppletNav bars, toolbars
BorderLayout5 regions: N/S/E/W/CenterFrame, DialogMain app windows
GridLayout(r,c)Equal-size cells in gridCalculators, keyboards
CardLayoutOne panel visible at a timeTabs, wizards
CardLayout methods: cl.next(panel) | cl.previous(panel) | cl.show(panel,"name") | cl.first(panel)
Null layout: setLayout(null); + comp.setBounds(x, y, w, h); for manual positioning

🌐 Servlet Life Cycle (IMP!)

3 Phases — 5 Methods:
1. init() — ONCE when servlet loads. One-time setup (DB connections, config).
2. service() — Every HTTP request. Routes to doGet() or doPost().
3. doGet() — Handles GET requests (URL params visible). req.getParameter("name")
4. doPost() — Handles POST requests (form data, hidden in body).
5. destroy() — ONCE at shutdown. Cleanup resources.
ServletCGI
Thread per request (fast, lightweight)Process per request (slow, heavy)
Java — platform independentC/Perl — platform dependent
Threads share JVM memory (efficient)Each process has own memory (wasteful)
Session management via HttpSessionStateless — no session tracking
Persistent (stays in memory)Reloaded for each request

🗄️ JDBC Introduction & Drivers (2M)

JDBC = Java DataBase Connectivity. Package: java.sql
• Platform independent + DB independent (just change the driver jar!)
• PreparedStatement → prevents SQL Injection attacks
• Transactions: setAutoCommit(false)commit() / rollback()
TypeNameStatus
Type 1JDBC-ODBC Bridge✗ Deprecated Java 8
Type 2Native-API Driver✗ Platform dependent
Type 3Network Protocol✗ Needs middleware server
Type 4 ⭐Thin / Pure Java✓ Fastest, preferred
MySQL Type 4: Driver class = com.mysql.cj.jdbc.Driver | Add: mysql-connector-java.jar

🔑 6 Steps of JDBC — RATTO YEH! (5M)

Step 1 — Load Driver:
Class.forName("com.mysql.cj.jdbc.Driver");

Step 2 — Connect:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","pass");

Step 3 — Statement:
Statement stmt = con.createStatement();

Step 4 — Execute:
SELECT → ResultSet rs = stmt.executeQuery("SELECT * FROM students");
Others → int rows = stmt.executeUpdate("INSERT INTO ...");

Step 5 — Process ResultSet:
while(rs.next()){ rs.getInt("id"); rs.getString("name"); rs.getInt("marks"); }

Step 6 — Close (REVERSE order):
rs.close(); stmt.close(); con.close();
URL format: jdbc:mysql://localhost:3306/dbName
Always close in finally block or use try-with-resources!

📊 CRUD Operations & Key Classes (IMP!)

OperationSQLJDBC MethodReturns
INSERTINSERT INTO t VALUES(?)executeUpdate()int (rows inserted)
SELECTSELECT * FROM t WHERE…executeQuery()ResultSet
UPDATEUPDATE t SET c=? WHERE id=?executeUpdate()int (rows updated)
DELETEDELETE FROM t WHERE id=?executeUpdate()int (rows deleted)
StatementPreparedStatement
Compiled every time (slow)Compiled once, reused (fast)
SQL Injection risk ⚠️Safe — ? params are data only ✓
con.createStatement()con.prepareStatement(sql)
Good for static SQLGood for user input / repeated SQL
PreparedStatement index starts at 1! ps.setString(1, name); ps.setInt(2, marks);
ResultSet cursor starts BEFORE first row — always call rs.next() before reading!
⚠️ Without WHERE: UPDATE/DELETE affects ALL rows!

⚠️ Common Exam Mistakes

❌ Calling rs.getString() before rs.next() — cursor not moved yet!
❌ Using index 0 in ps.setString(0, val) — must start from 1
❌ Forgetting WHERE clause in UPDATE/DELETE — all rows get affected!
❌ Using executeQuery() for INSERT — use executeUpdate()
❌ Not closing resources in finally block — memory leak!
❌ Using Applet constructor instead of init()
❌ Implementing MouseListener when MouseAdapter is simpler
❌ Calling run() directly — must call start() to create new thread

✅ Pre-Exam Checklist

☑ Delegation Event Model — 3 components + 3 steps
☑ All 5 event classes with listener interface + handler method
☑ Adapter classes — purpose + MouseAdapter, KeyAdapter, WindowAdapter
☑ Applet life cycle — 5 methods in correct order
☑ Applet vs Application — comparison table
☑ AWT Hierarchy — Component → Container → Frame
☑ All 10 AWT components + usage code
☑ All 4 layouts — default, arrangement, use case
☑ Servlet life cycle — 3 phases, 5 methods
☑ Servlet vs CGI — comparison table
☑ JDBC 6 steps — in correct order (memorize!)
☑ 4 JDBC driver types — Type 4 is preferred
☑ Essential JDBC classes — DriverManager to SQLException
☑ executeQuery vs executeUpdate — what each returns
☑ Statement vs PreparedStatement — 4 key differences
☑ PreparedStatement CRUD programs with correct syntax

🎯 Exam Strategy

2 Mark Questions:
• 2–3 sentences + key points. Time: 3–4 minutes max.
• "Differentiate" → draw a 2-column table (always!).
• Life cycle → list all methods in order with one-line purpose.

5 Mark Questions:
• Definition + Diagram/Flow + Code + Output. Time: 7–8 minutes.
• Always write: import java.awt.*; import java.awt.event.*; import java.sql.*;
• Show expected output at the end of code.

Marks-saving tip:
Even if full code is forgotten, writing the 6 JDBC steps or life cycle methods with correct names earns partial marks!
🌟 All the Best Bhai!
Event handling, AWT, Applets, Servlets aur JDBC — sab practice-based hain! Life cycles yaad karo, tables compare karo, aur code patterns practice karo. Tu definitely kar sakta hai! 💪☕
❓ Important Questions — Unit 3 (2M & 5M)
📌 10 questions of 2 marks + 5 questions of 5 marks. All from both chapters. Click any question to expand the answer.

📝 2 Marks Questions

2M
Q1. What is the Delegation Event Model in Java? Name its three components.
Answer:

The Delegation Event Model is a standard mechanism in Java (introduced in Java 1.1) where event handling is delegated from the source component to a separate listener object. When a user interacts with a GUI component, the event is generated at the source and passed to a registered listener for processing.

Three Components:
1. Source — component that generates the event (Button, TextField, Checkbox)
2. Event Object — encapsulates event information (ActionEvent, MouseEvent, KeyEvent)
3. Listener — object that handles/processes the event (ActionListener → actionPerformed())

Registration: source.addActionListener(listenerObject);
2M
Q2. List the 5 life cycle methods of an Applet with their purpose.
Answer:

Applet Life Cycle — 5 Methods in order:

1. init() — Called ONCE when applet first loads. Purpose: initialize variables, set up GUI. (Replaces constructor)
2. start() — Called after init() and every time user returns to page. Purpose: start or resume execution.
3. paint(Graphics g) — Called to draw/redraw applet window. Purpose: display graphics, text, shapes using Graphics object.
4. stop() — Called when user leaves page or minimizes browser. Purpose: pause activities to save resources.
5. destroy() — Called ONCE when applet is removed. Purpose: final cleanup, release all resources.

Order: init → start → paint → [stop ↔ start repeats] → destroy
2M
Q3. Differentiate between Applet and Java Application.
Answer:

AppletJava Application
Runs in browser / AppletViewerRuns in JVM as standalone program
No main() neededmain() method is the entry point
Must extend java.applet.AppletNo mandatory inheritance
Uses init() for setup (no constructor)Uses constructor or main() for setup
Sandbox security (limited file/network access)Full system and file access
Needs HTML <applet> tag to embedRuns with: java ClassName
2M
Q4. What are Adapter Classes? Give two examples with the interface they correspond to.
Answer:

Adapter Classes are abstract classes in Java that provide empty (default) implementations of all methods declared in a listener interface. They solve the problem of having to implement ALL interface methods even when you only need one or two.

Problem: MouseListener has 5 methods — you must override all 5 even if you only need mouseClicked().
Solution: Extend MouseAdapter — override only mouseClicked(), rest are auto-provided as empty.

Examples:
1. MouseAdapter — for MouseListener (mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited)
2. WindowAdapter — for WindowListener (windowOpened, windowClosing, windowClosed, etc. — 7 methods)
3. KeyAdapter — for KeyListener (keyPressed, keyReleased, keyTyped)
2M
Q5. Differentiate between FlowLayout and BorderLayout with their default containers.
Answer:

FlowLayoutBorderLayout
Arranges components left-to-right, wraps to next rowDivides into 5 regions: N, S, E, W, CENTER
Default layout for Panel and AppletDefault layout for Frame and Dialog
No region names — just add(component)Specify region: add(btn, BorderLayout.NORTH)
Components maintain preferred sizeCENTER region expands to fill remaining space
Good for: nav bars, toolbars, simple formsGood for: most application windows
2M
Q6. What is JDBC? State its advantages over ODBC.
Answer:

JDBC (Java DataBase Connectivity) is a standard Java API in the java.sql package that enables Java programs to connect to and interact with relational databases using SQL.

Advantages of JDBC over ODBC:
1. Platform Independent — JDBC is pure Java (runs anywhere); ODBC is C-based and platform-dependent
2. Object-Oriented — JDBC uses Java interfaces and classes; ODBC uses procedural C API
3. Better Security — Java's security model protects; ODBC has fewer safeguards
4. Easy Integration — JDBC integrates seamlessly with Java's exception handling, OOP
5. Portability — Same JDBC code works on Windows, Linux, Mac with just a driver change
2M
Q7. List the 4 types of JDBC drivers. Which one is most preferred and why?
Answer:

4 JDBC Driver Types:
1. Type 1 — JDBC-ODBC Bridge: Converts JDBC calls to ODBC. Slowest, deprecated in Java 8.
2. Type 2 — Native-API Driver: Converts JDBC to native DB API (C/C++). Platform dependent.
3. Type 3 — Network Protocol Driver: Uses middleware server. Flexible but needs extra server.
4. Type 4 — Thin Driver (Pure Java) ⭐: Converts JDBC directly to DB-specific protocol.

Most Preferred: Type 4
Reasons: Pure Java (platform independent), fastest performance, no extra libraries or servers needed, directly talks to database, widely supported (MySQL Connector/J, Oracle JDBC).
2M
Q8. Differentiate between Statement and PreparedStatement in JDBC.
Answer:

StatementPreparedStatement
SQL compiled on EVERY executionSQL compiled ONCE, reused → faster
No parameter placeholdersUses ? for parameters (setString, setInt)
Vulnerable to SQL Injection ⚠️Safe — parameters treated as data ✓
con.createStatement()con.prepareStatement(sql)
Good for static SQL (no user input)Good for dynamic SQL with user input
2M
Q9. List the 6 steps to connect a Java program with a MySQL database.
Answer:

6 Steps of JDBC Connection:

1. Load Driver: Class.forName("com.mysql.cj.jdbc.Driver");
2. Get Connection: Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "pass");
3. Create Statement: Statement stmt = con.createStatement();
4. Execute Query:
  • SELECT: ResultSet rs = stmt.executeQuery("SELECT * FROM t");
  • Others: int n = stmt.executeUpdate("INSERT INTO ...");
5. Process ResultSet: while(rs.next()) { System.out.println(rs.getString("name")); }
6. Close Resources (reverse order): rs.close(); stmt.close(); con.close();
2M
Q10. What is a Servlet? State advantages of Servlet over CGI.
Answer:

Servlet: A Servlet is a Java class that runs on a web server, handles HTTP requests from browsers, and generates dynamic responses (HTML, JSON). Package: javax.servlet.http. Extends HttpServlet.

Advantages of Servlet over CGI:
1. Performance: Servlet creates a new thread per request (lightweight); CGI creates a new process (heavyweight, slow)
2. Platform Independent: Java runs on any OS; CGI (C/Perl) is platform-dependent
3. Memory Efficient: Threads share the same JVM; each CGI process has separate memory
4. State Management: Servlet can maintain sessions using HttpSession; CGI is stateless
5. Persistent: Servlet stays loaded in memory; CGI is reloaded for each request

📝 5 Marks Questions

5M
Q11. Explain the Delegation Event Model with a Java program demonstrating button click and key press events.
Answer:

Delegation Event Model has 3 components: Source → Event Object → Listener. Listener is registered on source and called automatically when event fires.

Flow: User Action → Source creates EventObject → Delivers to Listener → Handler method runs

import java.awt.*; import java.awt.event.*; public class EventModelDemo extends Frame implements ActionListener, KeyListener { Button btn = new Button("Click Me!"); TextField tf = new TextField(20); Label lbl = new Label("Waiting for events...", Label.CENTER); public EventModelDemo() { // Register listeners (this class IS the listener) btn.addActionListener(this); // Button click tf.addKeyListener(this); // Key press in TextField setLayout(new FlowLayout()); add(new Label("Type here:")); add(tf); add(btn); add(lbl); setTitle("Delegation Event Model"); setSize(380, 150); setVisible(true); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){dispose();} }); } // ActionListener — fires when button is clicked public void actionPerformed(ActionEvent e) { lbl.setText("Button clicked! Text = " + tf.getText()); } // KeyListener — fires on key events in TextField public void keyPressed(KeyEvent e) { lbl.setText("Key pressed: " + KeyEvent.getKeyText(e.getKeyCode())); } public void keyReleased(KeyEvent e) { /* not used */ } public void keyTyped(KeyEvent e) { /* not used */ } public static void main(String[] args) { new EventModelDemo(); } } // Output: Type text → label shows key pressed // Click button → label shows button click + text entered
5M
Q12. Write an Applet program to demonstrate all 5 life cycle methods with graphics drawing.
Answer:

Applet Life Cycle Order: init() → start() → paint() ← [stop() ↔ start()] → destroy()

import java.applet.*; import java.awt.*; /* HTML to run: <applet code="AppletLifeCycle.class" width="400" height="250"> <param name="name" value="Ankush"> </applet> */ public class AppletLifeCycle extends Applet { String studentName; int visitCount = 0; int paintCount = 0; // 1. init() — ONCE at first load public void init() { studentName = getParameter("name"); if (studentName == null) studentName = "Student"; setBackground(Color.WHITE); System.out.println("1. init() called for: " + studentName); } // 2. start() — after init() + each page revisit public void start() { visitCount++; System.out.println("2. start() — Visit #" + visitCount); repaint(); // triggers paint() } // 3. paint() — draws the applet window public void paint(Graphics g) { paintCount++; g.setFont(new Font("Arial", Font.BOLD, 16)); g.setColor(Color.BLUE); g.drawString("Hello, " + studentName + "!", 30, 40); g.setColor(Color.DARK_GRAY); g.setFont(new Font("Arial", Font.PLAIN, 13)); g.drawString("Page visits: " + visitCount, 30, 70); g.drawString("Repaints: " + paintCount, 30, 90); // Draw colorful shapes g.setColor(Color.RED); g.fillOval(30, 110, 70, 70); g.setColor(Color.GREEN); g.fillRect(120, 110, 80, 70); g.setColor(Color.BLUE); g.drawRoundRect(220,110,100,70,15,15); g.setColor(Color.ORANGE);g.fillArc(330, 110, 60, 70, 45, 200); g.setColor(Color.GRAY); g.drawString("3. paint() — draw " + paintCount, 30, 200); } // 4. stop() — user leaves page public void stop() { System.out.println("4. stop() called"); } // 5. destroy() — ONCE at end public void destroy() { System.out.println("5. destroy() — Goodbye!"); } } /* Console Output: 1. init() called for: Ankush 2. start() — Visit #1 [user leaves page] → 4. stop() called [user comes back] → 2. start() — Visit #2 [browser closes] → 4. stop() called → 5. destroy() — Goodbye! */
5M
Q13. Explain all 4 Layout Managers in Java AWT with diagrams and code examples.
Answer:

1. FlowLayout — Left to right, wraps. Default: Panel, Applet.
setLayout(new FlowLayout(FlowLayout.LEFT, 8, 5));
Diagram: [Btn1][Btn2][Btn3] → wraps → [Btn4][Btn5]

2. GridLayout — Equal-size R×C grid. No default.
setLayout(new GridLayout(2, 3, 5, 5)); → 2 rows, 3 cols
Diagram: [1][2][3] / [4][5][6] — all cells equal size

3. BorderLayout — 5 regions. Default: Frame, Dialog.
add(btn, BorderLayout.NORTH);
Diagram: NORTH at top, SOUTH at bottom, EAST/WEST sides, CENTER expands

4. CardLayout — One panel at a time. No default.
cl.next(panel); cl.show(panel,"home");

import java.awt.*; import java.awt.event.*; public class AllLayouts extends Frame implements ActionListener { CardLayout cl = new CardLayout(); Panel cards = new Panel(); Button next, prev; public AllLayouts() { // Card 1 — FlowLayout demo Panel p1 = new Panel(new FlowLayout()); p1.setBackground(new Color(255,220,220)); for (int i=1;i<=5;i++) p1.add(new Button("Btn-"+i)); // Card 2 — GridLayout demo Panel p2 = new Panel(new GridLayout(2,3,4,4)); p2.setBackground(new Color(220,255,220)); for (int i=1;i<=6;i++) p2.add(new Button("G-"+i)); // Card 3 — BorderLayout demo Panel p3 = new Panel(new BorderLayout(4,4)); p3.setBackground(new Color(220,220,255)); p3.add(new Button("N"),BorderLayout.NORTH); p3.add(new Button("S"),BorderLayout.SOUTH); p3.add(new Button("E"),BorderLayout.EAST); p3.add(new Button("W"),BorderLayout.WEST); p3.add(new Button("CENTER"),BorderLayout.CENTER); cards.setLayout(cl); cards.add(p1,"flow"); cards.add(p2,"grid"); cards.add(p3,"border"); prev=new Button("◀ Prev"); next=new Button("Next ▶"); prev.addActionListener(this); next.addActionListener(this); Panel nav=new Panel(); nav.add(prev); nav.add(next); add(cards, BorderLayout.CENTER); add(nav, BorderLayout.SOUTH); setTitle("Layout Demo"); setSize(380,220); setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==next) cl.next(cards); else cl.previous(cards); } public static void main(String[] a) { new AllLayouts(); } } // Output: A window showing different layouts on each page navigation
5M
Q14. Explain JDBC Architecture with a diagram. Write a JDBC program to display all records from a students table.
Answer:

JDBC Architecture: Two main layers — JDBC API (java.sql) and JDBC Driver API. DriverManager manages drivers and creates connections.

Flow: Java App → JDBC API → DriverManager → JDBC Driver → Database

Key Classes: DriverManager, Connection, Statement, ResultSet, SQLException

import java.sql.*; public class DisplayStudents { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college"; Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Step 1: Load driver Class.forName("com.mysql.cj.jdbc.Driver"); // Step 2: Establish connection con = DriverManager.getConnection(url, "root", "password"); System.out.println("Connected!\n"); // Step 3: Create statement stmt = con.createStatement(); // Step 4: Execute SELECT query rs = stmt.executeQuery("SELECT * FROM students ORDER BY marks DESC"); // Step 5: Process ResultSet System.out.printf("%-4s %-12s %-6s %-12s%n","ID","Name","Marks","City"); System.out.println("-".repeat(38)); int count = 0; while (rs.next()) { count++; System.out.printf("%-4d %-12s %-6d %-12s%n", rs.getInt("id"), rs.getString("name"), rs.getInt("marks"), rs.getString("city")); } System.out.println("\nTotal students: " + count); } catch (ClassNotFoundException e) { System.out.println("Driver not found: " + e.getMessage()); } catch (SQLException e) { System.out.println("SQL Error: " + e.getMessage()); System.out.println("Error Code: " + e.getErrorCode()); } finally { // Step 6: Close resources — always in finally! try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); System.out.println("Resources closed."); } catch (SQLException e) { e.printStackTrace(); } } } } /* Output: Connected! ID Name Marks City -------------------------------------- 2 Priya 92 Mumbai 1 Raj 85 Delhi 3 Amit 78 Bangalore 4 Neha 65 Ludhiana Total students: 4 Resources closed. */
5M
Q15. Write a JDBC program using PreparedStatement to perform INSERT, UPDATE and DELETE operations on a students table.
Answer:

PreparedStatement uses ? placeholders — prevents SQL Injection, faster (precompiled), cleaner code.

import java.sql.*; public class CRUDWithPS { static final String URL = "jdbc:mysql://localhost:3306/college"; static final String USER = "root", PASS = "password"; static Connection connect() throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(URL, USER, PASS); } // INSERT — add new student static void insert(String name, int marks, String city) throws Exception { try (Connection c = connect(); PreparedStatement ps = c.prepareStatement( "INSERT INTO students(name,marks,city) VALUES(?,?,?)")) { ps.setString(1, name); ps.setInt(2, marks); ps.setString(3, city); int r = ps.executeUpdate(); System.out.println("INSERT: " + name + " → " + r + " row inserted"); } } // UPDATE — change marks static void update(int id, int newMarks) throws Exception { try (Connection c = connect(); PreparedStatement ps = c.prepareStatement( "UPDATE students SET marks=? WHERE id=?")) { ps.setInt(1, newMarks); ps.setInt(2, id); int r = ps.executeUpdate(); System.out.println("UPDATE: ID " + id + " → marks=" + newMarks + (r>0 ? " ✓" : " ✗ Not found")); } } // DELETE — remove student static void delete(int id) throws Exception { try (Connection c = connect(); PreparedStatement ps = c.prepareStatement( "DELETE FROM students WHERE id=?")) { ps.setInt(1, id); int r = ps.executeUpdate(); System.out.println("DELETE: ID " + id + (r>0 ? " ✓ Deleted" : " ✗ Not found")); } } public static void main(String[] args) throws Exception { System.out.println("=== CRUD with PreparedStatement ===\n"); insert("Anjali", 87, "Chandigarh"); // Insert insert("Varun", 72, "Amritsar"); // Insert update(1, 95); // Update Raj → 95 delete(3); // Delete Amit System.out.println("\nAll operations completed!"); } } /* Output: === CRUD with PreparedStatement === INSERT: Anjali → 1 row inserted INSERT: Varun → 1 row inserted UPDATE: ID 1 → marks=95 ✓ DELETE: ID 3 ✓ Deleted All operations completed! */