Java
Java
aces. Provide examples 3. Explain various methods provided by the Java Arrays class. Illustrate 4. What are legacy classes in Java? Explain with suitable examples: Vector,
List, Set, Queue, Deque, and Map with examples. demonstrating how they are used to sort collections. usage with examples. Hashtable, Stack, and Enumeration.
The Java Collections Framework (JCF) is a unified architecture introduced Comparator and Comparable Interfaces in Java Methods Provided by the Java Arrays Class Legacy Classes in Java
in Java to store and manipulate groups of data using predefined classes In Java, both the Comparator and Comparable interfaces are used to define The Arrays class in Java provides various static methods for manipulating Legacy classes in Java are part of the original version of the Java language
and interfaces. It standardizes how collections (like lists, sets, and maps) or customize the order of objects in a collection, especially when arrays, such as sorting, searching, copying, and comparing arrays. Here’s a and are included for backward compatibility. These include Vector,
are handled, reducing the need to write custom data structures. performing sorting operations. summary of some key methods: Hashtable, Stack, and Enumeration, which were later replaced by the more
1. Comparable Interface 1. sort() Method modern collections in the java.util package.
It provides: Purpose: Sorts the array in ascending order.
Interfaces for various data types like List, Set, Map, Queue, etc. Package: java.lang 1. Vector Class
Purpose: The Comparable interface is used to define the natural Usage: Works with both primitive and object arrays. Purpose: A growable array of objects, similar to ArrayList, but
Concrete classes like ArrayList, HashSet, and HashMap that implement int[] numbers = {5, 3, 8, 1, 2};
these interfaces. ordering of objects in Java. When a class implements this interface, it Arrays.sort(numbers); // Sorted: [1, 2, 3, 5, 8] synchronized (thread-safe).
Utility classes like Collections and Arrays that provide sorting, must override the compareTo(T o) method, which defines how objects 2. binarySearch() Method Usage: Used for storing dynamic lists, but slower than ArrayList.
searching, and other algorithms. of that class should be compared to one another. Purpose: Searches for an element in a sorted array and returns its java
Key Interfaces in Java Collections Framework: Sorting Basis: Sorting is typically based on a single property (like age, index. CopyEdit
1. Collection name, or any other attribute). Usage: Array must be sorted before using this method. Vector<Integer> vector = new Vector<>();
The root interface of the collection hierarchy. It defines basic operations Usage: When a class implements Comparable, you can use methods like int[] numbers = {1, 2, 3, 5, 8}; vector.add(1); // Output: [1]
like add(), remove(), clear(), and size(). Collections.sort() or Arrays.sort() to sort objects of that class directly. int index = Arrays.binarySearch(numbers, 5); // Returns index: 3 2. Hashtable Class
Example: Collection<String> col = new ArrayList<>(); It provides a default, natural ordering for the objects. 3. fill() Method Purpose: Stores key-value pairs. Synchronized and thread-safe but less
For example, if a Student class implements Comparable, we could use the Purpose: Fills an array or part of it with a specified value. efficient than HashMap.
2. List Usage: Can fill the entire array or a specific range.
An ordered collection that allows duplicates and provides indexed access. compareTo() method to define how students should be sorted—perhaps by Usage: Key-value storage, replaced by HashMap.
their marks or name—depending on the criteria we specify. int[] numbers = new int[5]; java
Common implementations: ArrayList, LinkedList, Vector. Arrays.fill(numbers, 10); // Fills entire array with 10
Example: List<String> list = new LinkedList<>(); 2. Comparator Interface 4. equals() Method CopyEdit
3. Set Package: java.util Purpose: Compares two arrays for equality. Hashtable<String, String> hashtable = new Hashtable<>();
A collection that does not allow duplicate elements. Purpose: The Comparator interface is used when you want to provide Usage: Checks if two arrays are of the same length and contain the hashtable.put("A", "Apple"); // Output: {A=Apple}
Common implementations: HashSet, TreeSet, LinkedHashSet. custom sorting logic. Unlike Comparable, which provides a natural same elements. 3. Stack Class
Example: Set<String> set = new HashSet<>(); ordering, Comparator allows you to define multiple different sorting int[] array1 = {1, 2, 3}; Purpose: Implements a LIFO (Last-In, First-Out) stack, extends Vector.
4. Queue strategies for the same class. int[] array2 = {1, 2, 3}; Usage: Used for stack operations like push and pop.
Used for holding elements prior to processing, typically in FIFO order. Method: It has a method compare(T o1, T o2), which compares two boolean isEqual = Arrays.equals(array1, array2); // Returns true java
Common implementations: LinkedList, PriorityQueue. objects of the same class and allows sorting based on various 5. copyOf() Method CopyEdit
attributes. Purpose: Creates a copy of an array with a specified length. Stack<String> stack = new Stack<>();
Example: Queue<String> queue = new LinkedList<>(); Usage: If the new length is larger, the extra elements are initialized to
5. Deque (Double Ended Queue) Sorting Basis: Sorting can be based on any number of properties (e.g., stack.push("One");
name, age, salary), and you can define as many sorting logics as you default values. stack.pop(); // Output: One
Allows insertion and removal from both ends. int[] original = {1, 2, 3};
Common implementations: ArrayDeque, LinkedList. want. int[] copy = Arrays.copyOf(original, 5); // Result: [1, 2, 3, 0, 0] 4. Enumeration Interface
Example: Deque<Integer> dq = new ArrayDeque<>(); Usage: If you need to sort objects based on a property that doesn't 6. copyOfRange() Method Purpose: An older interface for iterating over collections. Replaced by
6. Map form part of their natural order or if you want to sort in multiple ways Purpose: Copies a specific range of an array. Iterator.
Stores key-value pairs. Each key is unique and maps to a value. Though (such as by name, then by age), you can use Comparator. It is Usage: Copies elements between two indices. Usage: Used to iterate over collections like Vector or Hashtable.
not a subtype of Collection, it is an essential part of JCF. commonly used when the class does not implement Comparable or int[] original = {1, 2, 3, 4, 5}; java
Common implementations: HashMap, TreeMap, LinkedHashMap. when you need different sorting strategies. int[] rangeCopy = Arrays.copyOfRange(original, 1, 4); // Result: [2, 3, 4] CopyEdit
Example: Map<Integer, String> map = new HashMap<>(); For example, a Student class might be sorted by name in one case and by 7. toString() Method Enumeration<String> enumeration = vector.elements();
marks in another. In such cases, we would use a Comparator to define the Purpose: Returns a string representation of the array. while (enumeration.hasMoreElements()) {
different sorting strategies. Usage: Useful for printing arrays directly. System.out.println(enumeration.nextElement());
Summary: int[] numbers = {1, 2, 3};
The Java Collections Framework helps in managing data efficiently through }
System.out.println(Arrays.toString(numbers)); // Prints: [1, 2, 3]
well-defined interfaces and powerful implementations. It promotes 8. stream() Method
reusability, reduces coding effort, and ensures high performance. Purpose: Converts an array to a stream for more complex operations.
Usage: Useful for operations like filtering or mapping.
int[] numbers = {1, 2, 3, 4, 5};
int sum = Arrays.stream(numbers).sum(); // Sum: 15
1. Discuss different constructors of the Java String class. Illustrate with 2. Explain character extraction methods (charAt, getChars, getBytes, 4. Differentiate clearly between String, StringBuffer, and StringBuilder.
suitable code examples. 3. Demonstrate the usage of StringBuffer methods: append(), insert(),
toCharArray). Provide example programs. delete(), and reverse() with examples. Focus on mutability, performance, and thread safety.
Constructors of the Java String Class
The String class in Java provides several constructors to create String 1. charAt(int index) ✅ 1. append()
Adds text at the end of the existing string.
' 1.Mutability:
String
❌ Immutable
objects. These constructors allow you to initialize a String in different ways Returns the character at a specified index.
based on the input type. java java Once a String object is created, it cannot be changed.
Here are the main constructors of the String class: CopyEdit CopyEdit Any operation like concat(), replace(), or + creates a new String
1. Default Constructor public class AppendExample { object.
Purpose: Creates an empty String object.
Usage: This constructor initializes an empty string (i.e., a string with no
String str = "Hello";
char ch = str.charAt(1); // Output: e public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
Thread Safety: ✅
Yes
Since strings are immutable, they are naturally thread-safe.
characters).
String str = new String(); // Creates an empty string
System.out.println(ch);
2. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) sb.append(" World");
System.out.println(sb); // Output: Hello World
Performance: ❌
Slower for modifications
Frequent changes create multiple objects, which consumes more
System.out.println(str); // Output: (Empty String) Copies characters from string to a char array.
2. Constructor with Character Array java } memory and CPU.
} Example:
Purpose: Initializes a String object with a character array.
Usage: You can create a string from a set of characters in a char[] array.
CopyEdit
String str = "Character"; ✅ 2. insert() java
char[] chars = {'H', 'e', 'l', 'l', 'o'}; char[] dst = new char[5]; Inserts text at a specified index. CopyEdit
String str = new String(chars); // Initializes the string with 'Hello' str.getChars(0, 5, dst, 0); // Copies "Chara" java String s = "Hello";
System.out.println(str); // Output: Hello System.out.println(dst); CopyEdit s = s + " World"; // A new object is created
3. Constructor with Subrange of Character Array public class InsertExample { System.out.println(s); // Output: Hello World
3. getBytes()
Purpose: Initializes a String object from a subrange of a character array. Converts string to byte array (ASCII/UTF-8). public static void main(String[] args) { ' 2. StringBuffer
Usage: You can specify the start index and length of the subarray to
create the string. java StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " Java");
Mutability: ✅Mutable
Allows direct modification of the object (e.g., using append(),
char[] chars = {'J', 'a', 'v', 'a', 'C', 'o', 'd', 'e'}; CopyEdit
System.out.println(sb); // Output: Hello Java insert(), delete()).
String str = new String(chars, 4, 4); // Creates 'Code' starting from index 4
System.out.println(str); // Output: Code
String str = "Hi";
byte[] bytes = str.getBytes(); } Thread Safety: ✅Yes
} All methods are synchronized, so it's safe to use in multi-threaded
4. Constructor with Byte Array
Purpose: Initializes a String object with a byte array.
for (byte b : bytes) {
System.out.print(b + " "); // Output: 72 105 ✅ 3. delete()
Deletes characters between the given start and end index.
environments.
Performance: ⚠
Moderate
Usage: This constructor is useful when dealing with 8-bit encoded data, }
such as ASCII or UTF-8. 4. toCharArray() java Slower than StringBuilder due to the overhead of synchronization.
byte[] bytes = {65, 66, 67, 68}; Converts string to character array. CopyEdit Example:
String str = new String(bytes); // Initializes the string with 'ABCD' java public class DeleteExample { java
System.out.println(str); // Output: ABCD CopyEdit public static void main(String[] args) { CopyEdit
5. Constructor with Subrange of Byte Array String str = "Java"; StringBuffer sb = new StringBuffer("Hello Java"); StringBuffer sb = new StringBuffer("Hello");
Purpose: Initializes a String object with a subrange of a byte array. sb.delete(5, 10); // Removes " Java" sb.append(" World");
Usage: Allows you to specify the start index and length in the byte array char[] chars = str.toCharArray();
System.out.println(sb); // Output: Hello System.out.println(sb); // Output: Hello World
to create the string. for (char c : chars) {
} ' 3. StringBuilder
byte[] bytes = {65, 66, 67, 68, 69, 70};
String str = new String(bytes, 2, 3); // Creates 'CDE' starting from index 2 }
System.out.print(c + " "); // Output: J a v a
}
✅ 4. reverse()
Mutability: ✅Mutable
Same as StringBuffer, but not synchronized.
System.out.println(str); // Output: CDE
6. Constructor with String Object Reverses the entire string.
java
Thread Safety: ❌
No
Not safe in multi-threaded code unless externally synchronized.
Purpose: Initializes a String object using another String object.
Usage: This constructor creates a new String with the same value as
another String.
CopyEdit
public class ReverseExample {
Performance: ✅
Fastest
Best for single-threaded scenarios where performance matters.
String str1 = "Hello"; public static void main(String[] args) { Example:
String str2 = new String(str1); // Creates a new string from str1 StringBuffer sb = new StringBuffer("Java"); java
System.out.println(str2); // Output: Hello sb.reverse(); CopyEdit
7. Constructor with Unicode Code Points System.out.println(sb); // Output: avaJ StringBuilder sb = new StringBuilder("Hello");
Purpose: Initializes a String object using an array of Unicode code } sb.append(" World");
points.
Usage: This constructor allows you to create a string from an array of } System.out.println(sb); // Output: Hello World
Unicode code points.
int[] codePoints = {72, 101, 108, 108, 111};
1. Explain Java Swing and discuss its key features. Compare Swing with 2. Illustrate how MVC (Model-View-Controller) pattern is implemented in 3. Discuss four commonly used Swing buttons (JButton, JRadioButton, 4. Describe Swing components such as JLabel, JTextField, JScrollPane, and
AWT components. Swing applications. JCheckBox, JToggleButton) with examples. JTable using example programs.
What is Java Swing? ✅MVCMVC(Model-View-Controller)
in Java Swing
separates a program into:
✅ 1. JButton ✅ 1. JLabel
Java Swing is a part of the Java Foundation Classes (JFC) used to create A regular clickable button that performs an action when clicked. Used to display a text label or an image.
Graphical User Interfaces (GUIs) in Java applications. It builds on top of Model: Handles data and logic. Use: Submitting forms, triggering events. Use: Displaying static text or descriptions in a form.
AWT (Abstract Window Toolkit) and offers a more advanced and flexible set View: Displays the GUI. Example: Example:
Controller: Handles user actions and connects Model and View.
of components. Unlike AWT, which relies on the operating system’s native
components, Swing components are mostly written in Java, making them Example: Simple Counter App
1. Model (Counter logic)
java
CopyEdit
JLabel label = new JLabel("Enter your name:");
✅ 2. JTextField
lightweight and platform-independent. JButton button = new JButton("Click Me"); A single-line text input field.
ÿ Key Features of Swing: public class CounterModel { button.addActionListener(e -> System.out.println("Clicked")); Use: Let users enter data like names, emails, etc.
Swing provides a rich set of GUI components such as buttons, text fields,
tables, trees, and more. One of its main strengths is that it supports a
private int count = 0; ✅ 2. JRadioButton Example:
Used when the user must select only one option from a group. JTextField textField = new JTextField(20);
pluggable look and feel, which means you can change the appearance of
your application without altering its logic. Swing follows the Model-View-
public int getCount() { return count; }
public void increment() { count++; }
Use: Selecting gender, modes, etc. ✅ 3. JScrollPane
Note: Group radio buttons using ButtonGroup. Adds scrollbars to another component when needed.
Controller (MVC) architecture, allowing for better separation between data, } Example: Use: Used with large text areas, tables, lists, etc.
UI, and logic. It also uses double buffering to reduce flickering during 2. View (UI components) java Example:
screen updates and allows for easy customization of components. import javax.swing.*; CopyEdit JTextArea area = new JTextArea(5, 20);
ò Difference Between Swing and AWT: import java.awt.*; JRadioButton r1 = new JRadioButton("Option 1"); JScrollPane scrollPane = new JScrollPane(area);
While both Swing and AWT are used to build GUI applications in Java, there
are some key differences. AWT is a heavyweight toolkit because it uses the
public class CounterView extends JFrame {
private JButton button = new JButton("Increment");
JRadioButton r2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
✅ 4. JTable
Displays data in a tabular (grid) format.
native GUI components of the operating system. This can lead to private JLabel label = new JLabel("Count: 0"); group.add(r1); group.add(r2); Use: Showing records, spreadsheets, etc.
inconsistencies across platforms. In contrast, Swing is lightweight, as its
components are rendered using Java code rather than native resources.
public CounterView() {
setLayout(new FlowLayout());
✅ 3. JCheckBox Example:
Lets users select multiple options independently. String[] columns = {"ID", "Name"};
This makes Swing more consistent and portable across different systems. add(label); add(button); Use: Selecting skills, interests, etc. String[][] data = {{"1", "Alice"}, {"2", "Bob"}};
Swing also provides a richer set of components than AWT. For example, setSize(300, 100); setDefaultCloseOperation(EXIT_ON_CLOSE);} Example: JTable table = new JTable(data, columns);
Swing offers JTable, JTree, JTabbedPane, and more, while AWT has only public void setCount(int count) { label.setText("Count: " + count); } java JScrollPane tableScroll = new JScrollPane(table);
basic components like Button, Label, and TextField. Additionally, Swing is
more flexible and customizable, allowing developers to change how
public JButton getButton() { return button; }}
3. Controller (Handles user actions)
CopyEdit Combined Example (Basic GUI)
JCheckBox c1 = new JCheckBox("Java"); import javax.swing.*;
components behave and look. However, one downside is that Swing is not import java.awt.event.*; JCheckBox c2 = new JCheckBox("Python"); public class SwingComponentExample {
thread-safe by default, so developers need to take care when updating the
UI from multiple threads.
public class CounterController {
public CounterController(CounterModel model, CounterView view) {
✅ 4. JToggleButton public static void main(String[] args) {
A button that stays in a pressed ("on") or released ("off") state. JFrame frame = new JFrame("Swing Components");
In terms of performance, AWT can be slightly faster in some cases due to view.getButton().addActionListener(e -> { Use: Like a power switch or mode toggle. frame.setSize(400, 300);
its use of native components, but Swing gives more control and features, model.increment(); Example: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
making it the preferred choice for complex applications. view.setCount(model.getCount()); }); }} java frame.setLayout(new java.awt.FlowLayout());
Simple Swing Example: 4. Main Class
public class MVCDemo {
CopyEdit JLabel label = new JLabel("Name:");
java JToggleButton toggle = new JToggleButton("OFF"); JTextField textField = new JTextField(15);
import javax.swing.*; public static void main(String[] args) { toggle.addActionListener(e -> toggle.setText(toggle.isSelected() ? "ON" : String[][] data = {{"1", "Alice"}, {"2", "Bob"}};
CounterModel model = new CounterModel(); "OFF")); String[] columns = {"ID", "Name"};
public class SwingExample {
public static void main(String[] args) {
CounterView view = new CounterView();
new CounterController(model, view);
. Summary: JTable table = new JTable(data, columns);
JButton – Simple action button. JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Swing Example"); view.setVisible(true); }} JRadioButton – Choose one from a group. frame.add(label);
JButton button = new JButton("Click Me"); JCheckBox – Choose multiple options. frame.add(textField);
JToggleButton – ON/OFF switch style button. frame.add(scrollPane);
frame.setSize(300, 200); frame.setVisible(true);}}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button);
frame.setVisible(true);
}
}
1. Describe the lifecycle of a Servlet. Illustrate with a complete example 2. Explain session tracking techniques in Servlets. Demonstrate handling 3. Define JSP and explain its core concepts: JSP tags, implicit objects, and 4. Explain Cookie handling in Servlets. Describe methods involved and
program. sessions using HttpSession and Cookies. variables with suitable examples. provide an example program.
✅ Lifecycle of a Servlet in Java ✅ Session Tracking in Servlets ✅ What is JSP (JavaServer Pages)?
JSP (JavaServer Pages) is a server-side technology used to create dynamic
A Servlet is a Java class used to handle HTTP requests and generate
responses in a web application. The Servlet lifecycle is managed by the
Session tracking is used to maintain user data across multiple HTTP
requests. Since HTTP is stateless, session tracking techniques allow web
web pages using Java. It allows embedding Java code directly into HTML ✅ Cookie Handling in Servlets
using special tags, making it easy to create interactive web content. Cookies are small data pieces stored on the client and sent with each
Servlet container (e.g., Tomcat) and includes the following key phases:
ò Servlet Lifecycle Stages:
applications to remember individual users.
( Techniques for Session Tracking: ( Core Concepts of JSP
1. JSP Tags
request. They help track sessions or user preferences.
( Common Cookie Methods
1.Loading and Instantiation 1.Cookies – Store data on the client’s browser. new Cookie(String name, String value)
The container loads the servlet class and creates an instance. 2.HttpSession – Store data on the server side, linked with a unique JSP uses various tags to add Java code into HTML pages.
<% ... %> – Scriptlet: contains Java code. response.addCookie(Cookie c)
Happens only once, when the servlet is first requested or at startup session ID. request.getCookies()
<%= ... %> – Expression: outputs a value.
(if configured). 3.URL Rewriting – Passes session ID in the URL. <%! ... %> – Declaration: declares variables or methods. cookie.getName(), cookie.getValue()
2.Initialization (init() method) 4.Hidden Form Fields – Store session data in hidden HTML fields.
Called once after the servlet instance is created.
Used to initialize resources (like DB connections).
✅ 1. Handling Session with HttpSession
import java.io.*;
Example:
<%@ page language="java" %>
cookie.setMaxAge(int seconds)
Example:
<html> java
3.Request Handling (service() method) import javax.servlet.*; CopyEdit
Called every time the servlet receives a request. import javax.servlet.http.*; <body>
<% String name = "Alice"; %> import java.io.*;
Dispatches requests to doGet(), doPost(), etc. public class SessionExample extends HttpServlet { import javax.servlet.*;
<h2>Welcome, <%= name %></h2>
4.Destruction (destroy() method) protected void doGet(HttpServletRequest request, HttpServletResponse import javax.servlet.http.*;
Called when the servlet is being removed from service (e.g., server response) throws IOException { </body>
</html>
shutdown). HttpSession session = request.getSession(); public class CookieServlet extends HttpServlet {
2. Implicit Objects
Used to release resources. session.setAttribute("username", "JohnDoe");
Complete Servlet Example response.setContentType("text/html");
JSP provides several built-in objects that can be used directly without protected void doGet(HttpServletRequest request, HttpServletResponse
✅ File: HelloServlet.java
java
PrintWriter out = response.getWriter();
out.println("<h2>Welcome, " + session.getAttribute("username") + "
declaring them.
request – to get request data
response) throws IOException {
Cookie userCookie = new Cookie("username", "Alice");
response – to send response userCookie.setMaxAge(3600);
CopyEdit </h2>"); }}
import java.io.*; ✅ 2. Handling Session with Cookies session – to manage user session
application – for global context
response.addCookie(userCookie);
import javax.servlet.*; java Cookie[] cookies = request.getCookies();
import javax.servlet.http.*; out – to send output to the browser
config, pageContext, page, exception String name = "Guest";
import java.io.*; if (cookies != null) {
Example:
public class HelloServlet extends HttpServlet { import javax.servlet.*; for (Cookie c : cookies) {
import javax.servlet.http.*; <%
String user = request.getParameter("username"); if (c.getName().equals("username")) {
// Called once when servlet is first loadedpublic void init() throws public class CookieExample extends HttpServlet { name = c.getValue();
out.println("Hello, " + user);
ServletException { protected void doGet(HttpServletRequest request, HttpServletResponse %> }
System.out.println("Servlet Initialized"); response) throws IOException { }
3. Variables in JSP
} Cookie cookie = new Cookie("user", "JohnDoe"); }
response.addCookie(cookie); Variables in JSP can be declared inside:
Scriptlets (<% ... %>) for logic
// Called on every HTTP GET requestprotected void Cookie[] cookies = request.getCookies(); response.setContentType("text/html");
Declarations (<%! ... %>) for global variables/methods
doGet(HttpServletRequest request, HttpServletResponse response) throws String name = "Guest"; Example: PrintWriter out = response.getWriter();
IOException { if (cookies != null) { out.println("<h2>Hello, " + name + "</h2>");
<%! int count = 0; %>
response.setContentType("text/html"); for (Cookie c : cookies) { }
PrintWriter out = response.getWriter(); if (c.getName().equals("user")) { <%
count++; }
out.println("<h1>Hello from Servlet</h1>"); name = c.getValue(); }}}
out.println("Visitor number: " + count);
} response.setContentType("text/html");
PrintWriter out = response.getWriter(); %>
// Called when servlet is unloaded/destroyedpublic void destroy() { out.println("<h2>Hello, " + name + "</h2>");}}
System.out.println("Servlet Destroyed");
}
}
1. Explain JDBC architecture and discuss the different types of JDBC drivers. 2. Describe steps involved in connecting Java applications to databases 3. Explain the configuration and usage of the JDBC-ODBC bridge with the 4. Discuss the concepts of JDBC metadata: ResultSetMetaData,
Illustrate each with examples. using JDBC. Provide example code snippets. ODBC Data Source Administrator. DatabaseMetaData with appropriate examples.
✅JDBCJDBC(Java
Architecture
Database Connectivity) is an API that enables Java applications
✅1.Load
Steps to Connect Java Applications to Databases Using JDBC
the JDBC driver class.
1. JDBC-ODBC Bridge Overview
The JDBC-ODBC Bridge driver (Type 1 driver) allows Java applications to ✅ Concepts of JDBC Metadata
to interact with databases by providing methods to query and update 2.Establish a connection using DriverManager.getConnection(). connect to databases through ODBC drivers. It acts as a bridge converting JDBC provides interfaces to get info about databases and query results.
relational data. 3.Create a Statement or PreparedStatement object. JDBC calls into ODBC calls. This method requires the ODBC driver to be Two important ones are:
( JDBC Architecture Components: 4.Execute SQL queries or updates. configured on the client machine. 1. ResultSetMetaData
Gives details about columns in a ResultSet like count, names, and types,
JDBC API: Interface for Java apps to connect and work with databases. 5.Process the ResultSet if applicable. Note: The JDBC-ODBC bridge is considered obsolete and removed in newer
JDBC Driver Manager: Manages communication between app and 6.Close all database resources. Java versions (from Java 8 onwards). It is mainly used for legacy systems. useful for generic handling of query results.
drivers. Example Code 2. Configuring ODBC Data Source import java.sql.*;
public class ResultSetMetaDataExample {
JDBC Drivers: Implement database-specific protocols to connect Java to java Before using the JDBC-ODBC bridge, you must set up an ODBC Data Source
databases. CopyEdit on your machine: public static void main(String[] args) throws Exception {
Database: The actual data storage (e.g., MySQL, Oracle). import java.sql.*; Open ODBC Data Source Administrator: Class.forName("com.mysql.cj.jdbc.Driver");
Flow: On Windows, search for "ODBC Data Sources" (32-bit or 64-bit Connection con =
Java Application→ JDBC API → Driver Manager → JDBC Driver → public class JdbcExample { depending on your Java version). DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"user", "pass");
Database public static void main(String[] args) { Add a New Data Source:
( Types of JDBC Drivers Connection con = null; Click Add. Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
There are four types with different implementations and performance: Statement stmt = null; Choose the appropriate driver for your database (e.g., SQL Server,
1.Type 1: JDBC-ODBC Bridge Driver ResultSet rs = null; Microsoft Access). ResultSetMetaData rsmd = rs.getMetaData();
2. Converts JDBC calls into ODBC calls using installed ODBC drivers. Provide a name for your Data Source Name (DSN) — this name will int count = rsmd.getColumnCount();
Mostly obsolete now. try { be used in your Java code. System.out.println("Columns: " + count);
3. Example: Class.forName("com.mysql.cj.jdbc.Driver"); Configure connection parameters such as database location, for (int i = 1; i <= count; i++)
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection( credentials, etc. System.out.println(rsmd.getColumnName(i) + " | " +
Connection con = "jdbc:mysql://localhost:3306/mydb", "username", "password"); Test the connection and save the DSN. rsmd.getColumnTypeName(i));
DriverManager.getConnection("jdbc:odbc:DataSourceName"); stmt = con.createStatement(); 3. Using JDBC-ODBC Bridge in Java rs.close();
1.Type 2: Native-API Driver rs = stmt.executeQuery("SELECT * FROM users"); Once the DSN is set up, connect to the database in Java using the DSN stmt.close();
2. Uses native libraries to convert JDBC calls into database calls. Faster name. con.close();}}
but platform-dependent. while (rs.next()) { Example: 2. DatabaseMetaData
3. Example: int id = rs.getInt("id"); import java.sql.*; Provides info about the database product, version, and lists tables, helping
Class.forName("oracle.jdbc.driver.OracleDriver"); String username = rs.getString("username"); public class JdbcOdbcExample { to write database-independent code.
Connection con = String email = rs.getString("email"); public static void main(String[] args) { java
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", System.out.println("ID: " + id + ", Username: " + username + ", try { CopyEdit
"user", "pass"); Email: " + email); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); import java.sql.*;
1.Type 3: Network Protocol Driver } Connection con = public class DatabaseMetaDataExample {
2. Uses a middleware server to translate JDBC calls to database protocol. DriverManager.getConnection("jdbc:odbc:YourDSNName"); public static void main(String[] args) throws Exception {
Database-independent and suited for internet apps. } catch (ClassNotFoundException e) { Statement stmt = con.createStatement(); Class.forName("com.mysql.cj.jdbc.Driver");
3. Example: System.out.println("JDBC Driver not found: " + e.getMessage()); ResultSet rs = stmt.executeQuery("SELECT * FROM YourTable"); Connection con =
Class.forName("com.somevendor.jdbc.NetDriver"); } catch (SQLException e) { while (rs.next()) { DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
Connection con = System.out.println("Database error: " + e.getMessage()); System.out.println(rs.getString(1)); "user", "pass");
DriverManager.getConnection("jdbc:someprotocol://server:port/db", } finally { } DatabaseMetaData dbmd = con.getMetaData();
"user", "pass"); try { if (rs != null) rs.close(); } catch (SQLException e) { } rs.close(); System.out.println("Product: " + dbmd.getDatabaseProductName());
1.Type 4: Thin Driver (Pure Java Driver) try { if (stmt != null) stmt.close(); } catch (SQLException e) { } stmt.close(); System.out.println("Version: " + dbmd.getDatabaseProductVersion());
2. Fully Java-based, converts JDBC calls directly to database protocol. try { if (con != null) con.close(); } catch (SQLException e) { } con.close(); ResultSet tables = dbmd.getTables(null, null, "%", new String[]
Platform-independent and widely used. } } catch (Exception e) { {"TABLE"});
3. Example: } e.printStackTrace(); }}} System.out.println("Tables:");
Class.forName("com.mysql.cj.jdbc.Driver"); } Replace "YourDSNName" with the exact name of your configured ODBC while (tables.next())
Connection con = Data Source. System.out.println(tables.getString("TABLE_NAME"));
DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", Replace "YourTable" with the actual table name you want to query. tables.close();
"user", "pass"); con.close();}}
5. Describe Spliterators in Java. Mention their purpose and demonstrate 5. Explain the usage of string comparison methods: equals(), 5. What is event handling in Swing? Demonstrate with examples using 5. Describe the interfaces and classes present in the jakarta.servlet
usage with examples. equalsIgnoreCase(), regionMatches(), startsWith(), and endsWith(). ActionListener and event delegation model. package.
Explaination
PreparedStatement objects.
executeQuery(): Used for SELECT statements, returns a ResultSet.
executeUpdate(): Used for INSERT, UPDATE, DELETE, returns the number
of affected rows.
execute(): Used for any SQL, returns a boolean indicating if the result is
a ResultSet.
Example:
Connection con = DriverManager.getConnection(dbURL, user, pass);
4X4 = Module 1
Statement stmt = con.createStatement();
// Execute SELECTResultSet rs = stmt.executeQuery("SELECT * FROM
employees");
4X4 = Module 2
4X4 = Module 3
// Execute UPDATEint rowsUpdated = stmt.executeUpdate("UPDATE
employees SET salary=5000 WHERE id=101");
2. Retrieving Results
4X4 = Module 4
Use the ResultSet to access query results. Move the cursor with next() and
retrieve columns by name or index.
Example:
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double salary = rs.getDouble("salary");
4X4 = Module 5
System.out.println(id + " | " + name + " | " + salary);
}
3. Transaction Management
4. Describe Swing components such as JLabel, JTextField, JScrollPane, and JTable using
example programs.
5. What is event handling in Swing? Demonstrate with examples using ActionListener and
event delegation model.
Module 4: Servlets and JSP
1. Describe the lifecycle of a Servlet. Illustrate with a complete example program.