0% found this document useful (0 votes)
12 views21 pages

Advanced Java Multithreading Guide

The document provides detailed explanations of Advanced Java topics including Multithreading, Java Collections, and Java Server Pages. Each section includes definitions, practical uses, examples, and key points for exam preparation. The content is structured to facilitate understanding and application in university exams.

Uploaded by

witak74886
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views21 pages

Advanced Java Multithreading Guide

The document provides detailed explanations of Advanced Java topics including Multithreading, Java Collections, and Java Server Pages. Each section includes definitions, practical uses, examples, and key points for exam preparation. The content is structured to facilitate understanding and application in university exams.

Uploaded by

witak74886
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Thank you for clarifying that you want **detailed** explanations with definitions, uses, and examples for

each subto
rehensive, exam-focused explanations for the specified Advanced Java topics (**Multithreading**, **Java Collections
vlet**, and **Java Server Pages**), adhering to your original structure and subtopics. Each section will include:

- **Definition**: Clear explanation of the concept or component.


- **Use**: Practical applications and importance in programming.
- **Example**: Working code or step-by-step illustration, tailored for university exam preparation.
- **Key Points to Remember**: Concise summary for quick revision, consistent with the previous response.

The explanations will be thorough, accurate, and easy to understand, avoiding unnecessary complexity while ensurin
ous response’s structure and content, expanding with definitions, uses, and examples without tampering with the pr
your university exams.

---

### **Multithreading**

#### **Concept of Thread**

- **Definition**: A thread is the smallest unit of execution within a Java program, representing an independent sequ
in the same process. Threads share the same memory space and resources of their parent process, making them lig
- **Use**:
- Enables **concurrent execution** of tasks (e.g., handling multiple client requests in a server).
- Improves **application responsiveness** (e.g., updating a GUI while performing background calculations).
- Optimizes **resource utilization** in multi-core CPUs by parallelizing tasks.
- Common in applications like web servers, real-time systems, and games.
- **Example**:
```java
public class ThreadDemo {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
[Link]("Thread 1: Task " + i);
try {
[Link](200);
} catch (InterruptedException e) {
[Link]();
}
}
});
Thread t2 = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
[Link]("Thread 2: Task " + i);
try {
[Link](200);
} catch (InterruptedException e) {
[Link]();
}
}
});
[Link]();
[Link]();
}
}
```
- **Output** (order may vary due to scheduling):
```
Thread 1: Task 1
Thread 2: Task 1
Thread 1: Task 2
Thread 2: Task 2
Thread 1: Task 3
Thread 2: Task 3
```
- **Explanation**: Two threads (`t1`, `t2`) execute concurrently, printing tasks with a small delay to simulate work

#### **Thread Lifecycle**

- **Definition**: The thread lifecycle describes the states a thread transitions through from creation to termination.
thread scheduler.
- **Use**:
- Understanding the lifecycle helps manage thread behavior (e.g., starting, pausing, or stopping threads).
- Critical for debugging issues like deadlocks, thread starvation, or unexpected termination.
- Helps optimize thread scheduling in multi-threaded applications.
- **States**:
1. **New**: Thread is created (`new Thread()`) but not started.
2. **Runnable**: After `start()`, the thread is ready to run, awaiting CPU allocation.
3. **Running**: The thread executes its `run()` method.
4. **Blocked/Waiting**: The thread is inactive due to waiting for a lock, I/O, or methods like `wait()`, `sleep()`, or `
5. **Terminated/Dead**: The thread completes execution or is stopped.
- **Example**:
```java
public class ThreadLifecycleDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
[Link]("Thread Running: " + [Link]().getName());
try {
[Link](1000); // Moves to Timed Waiting
[Link]("Thread Resumed");
} catch (InterruptedException e) {
[Link]();
}
});
[Link]("State (New): " + [Link]()); // NEW
[Link]();
[Link]("State (After start): " + [Link]()); // RUNNABLE
[Link](100); // Allow t to run
[Link]("State (Sleeping): " + [Link]()); // TIMED_WAITING
[Link](); // Wait for t to finish
[Link]("State (Terminated): " + [Link]()); // TERMINATED
}
}
```
- **Output**:
```
State (New): NEW
State (After start): RUNNABLE
Thread Running: Thread-0
State (Sleeping): TIMED_WAITING
Thread Resumed
State (Terminated): TERMINATED
```
- **Explanation**: The thread’s state is printed at different stages, showing transitions from `NEW` to `TERMINATE

#### **Creating Threads**

1. **Using Thread Class**:


- **Definition**: Extend the `[Link]` class and override the `run()` method to define the thread’s task. C
- **Use**:
- Simple for basic threading tasks.
- Suitable when no other class inheritance is needed.
- Common in small-scale applications or demos.
- **Example**:
```java
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](getName() + ": Count " + i);
try {
[Link](100);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread-A");
MyThread t2 = new MyThread();
[Link]("Thread-B");
[Link]();
[Link]();
}
}
```
- **Output** (order varies):
```
Thread-A: Count 1
Thread-B: Count 1
Thread-A: Count 2
Thread-B: Count 2
Thread-A: Count 3
Thread-B: Count 3
```

2. **Using Runnable Interface**:


- **Definition**: Implement the `[Link]` interface and define the `run()` method. Pass the `Runnabl
- **Use**:
- Preferred over `Thread` class due to flexibility (allows extending another class).
- Supports better separation of task logic and thread management.
- Used with thread pools (e.g., `ExecutorService`) in modern Java.
- **Example**:
```java
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
[Link]([Link]().getName() + ": Count " + i);
try {
[Link](100);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable, "Thread-X");
Thread t2 = new Thread(runnable, "Thread-Y");
[Link]();
[Link]();
}
}
```
- **Output** (order varies):
```
Thread-X: Count 1
Thread-Y: Count 1
Thread-X: Count 2
Thread-Y: Count 2
Thread-X: Count 3
Thread-Y: Count 3
```

#### **Thread Synchronization**

- **Definition**: Synchronization ensures that only one thread accesses a shared resource at a time, preventing data
red data.
- **Use**:
- Protects critical sections (e.g., updating a shared counter or bank balance).
- Essential in multi-threaded applications like banking systems or ticket booking.
- Ensures thread safety without excessive locking (which can cause performance issues).
- **Example** (Counter with and without synchronization):
```java
class Counter {
private int count = 0;
public void incrementUnsafe() {
count++; // Race condition
}
public synchronized void incrementSafe() {
count++;
[Link]([Link]().getName() + ": " + count);
}
public int getCount() {
return count;
}
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
[Link](); // Try incrementUnsafe() for race condition
}
};
Thread t1 = new Thread(task, "T1");
Thread t2 = new Thread(task, "T2");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Final count: " + [Link]());
}
}
```
- **Output** (with `incrementSafe()`):
```
T1: 1
T2: 2
...
T1: 1999
T2: 2000
Final count: 2000
```
- **Output** (with `incrementUnsafe()`, varies):
```
Final count: 1987 (or other incorrect value)
```
- **Explanation**: `incrementSafe()` uses `synchronized` to ensure atomic updates, while `incrementUnsafe()` ca

#### **Inter-thread Communication**

- **Definition**: Inter-thread communication allows threads to coordinate actions using `wait()`, `notify()`, and `no
resource sharing without polling.
- **Use**:
- Implements patterns like **producer-consumer**, where one thread produces data and another consumes it.
- Prevents busy-waiting (e.g., constantly checking a condition).
- Used in scenarios like message queues, thread pools, or database connection pools.
- **Example** (Producer-Consumer):
```java
class Buffer {
private int data;
private boolean empty = true;
public synchronized void produce(int value) throws InterruptedException {
while (!empty) {
wait(); // Wait if buffer is full
}
data = value;
empty = false;
[Link]("Produced: " + data);
notify();
}
public synchronized int consume() throws InterruptedException {
while (empty) {
wait(); // Wait if buffer is empty
}
empty = true;
[Link]("Consumed: " + data);
notify();
return data;
}
}
public class Main {
public static void main(String[] args) {
Buffer buffer = new Buffer();
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
[Link](i);
[Link](200);
}
} catch (InterruptedException e) {
[Link]();
}
});
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
[Link]();
[Link](200);
}
} catch (InterruptedException e) {
[Link]();
}
});
[Link]();
[Link]();
}
}
```
- **Output**:
```
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
```

#### **Key Points to Remember**


- **Thread**: Smallest execution unit; shares process memory, enables concurrency.
- **Lifecycle**: New → Runnable (`start()`) → Running → Blocked/Waiting (`wait()`, `sleep()`) → Terminated.
- **Creation**:
- `Thread` class: Extend, override `run()`, call `start()`.
- `Runnable` interface: Implement `run()`, pass to `Thread`, preferred.
- **Synchronization**: `synchronized` methods/blocks prevent race conditions using monitors.
- **Inter-thread Communication**:
- `wait()`: Release lock, wait.
- `notify()`: Wake one thread; `notifyAll()`: Wake all.
- Use in `synchronized` blocks with `while` loops.
- **Methods**: `sleep()`, `join()`, `currentThread()`, `setName()`.
- **Best Practices**: Use `Runnable`, avoid `stop()`, use `ExecutorService` for pools, prevent deadlocks.
- **Exam Tip**: Practice producer-consumer, know lifecycle states, and debug race conditions.

---

### **Java Collections and Utility Classes**

#### **Introduction to Generics**

- **Definition**: Generics allow classes, interfaces, and methods to operate on specified types at compile time, ensu
- **Use**:
- Prevents runtime errors (e.g., `ClassCastException`) by enforcing type constraints.
- Simplifies code by removing casts (e.g., `String s = [Link](0)`).
- Used in collections, custom classes, and utility methods.
- **Example**:
```java
import [Link];
import [Link];
public class GenericsDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
[Link]("Alice");
[Link]("Bob");
// [Link](123); // Compile-time error
String first = [Link](0); // No casting
[Link]("First name: " + first);
// Generic method
printItem(42); // T inferred as Integer
printItem("Hello"); // T inferred as String
}
public static <T> void printItem(T item) {
[Link]("Item: " + item);
}
}
```
- **Output**:
```
First name: Alice
Item: 42
Item: Hello
```

#### **Collection Basics**

- **Definition**: The Java Collections Framework is a set of classes and interfaces in `[Link]` for storing, manipula
- **Use**:
- Provides reusable data structures (e.g., lists, sets, maps) for common tasks.
- Supports operations like sorting, searching, and iteration.
- Used in data processing, algorithms, and application development.
- **Hierarchy**:
- `Collection` interface: `List`, `Set`, `Queue`.
- `Map` interface: Key-value pairs.
- **Example**:
```java
import [Link].*;
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Contains Banana: " + [Link]("Banana"));
[Link]("Apple");
[Link]("Size: " + [Link]());
}
}
```
- **Output**:
```
Contains Banana: true
Size: 1
```

#### **Using ArrayList, Vector, LinkedList**

- **ArrayList**:
- **Definition**: A resizable array implementation of the `List` interface, backed by a dynamic array.
- **Use**:
- Fast random access and iteration (O(1)).
- Non-synchronized, suitable for single-threaded apps.
- Used for general-purpose lists (e.g., storing user data).
- **Example**:
```java
import [Link];
import [Link];
public class ArrayListDemo {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link](1, "Orange"); // Insert at index 1
[Link]("Fruits: " + fruits);
[Link](0, "Mango"); // Replace
[Link]("First: " + [Link](0));
[Link]("Banana");
[Link]("After remove: " + fruits);
}
}
```
- **Output**:
```
Fruits: [Apple, Orange, Banana]
First: Mango
After remove: [Mango, Orange]
```

- **Vector**:
- **Definition**: A synchronized, resizable array implementation of `List`, similar to `ArrayList` but thread-safe.
- **Use**:
- Used in multi-threaded apps requiring thread safety.
- Legacy class, less common due to synchronization overhead.
- **Example**:
```java
import [Link];
public class VectorDemo {
public static void main(String[] args) {
Vector<String> animals = new Vector<>();
[Link]("Cat");
[Link]("Dog");
[Link]("Animals: " + animals);
[Link]("Cat");
[Link]("First: " + [Link]());
}
}
```
- **Output**:
```
Animals: [Cat, Dog]
First: Dog
```

- **LinkedList**:
- **Definition**: A doubly-linked list implementation of `List` and `Deque`, storing elements as nodes with referen
- **Use**:
- Fast insertions and deletions (O(1) at ends).
- Implements `Deque` for queue/stack operations.
- Used for dynamic lists with frequent modifications.
- **Example**:
```java
import [Link];
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> queue = new LinkedList<>();
[Link]("Task1");
[Link]("Task2");
[Link]("Queue: " + queue);
[Link]("First: " + [Link]());
[Link]();
[Link]("After remove: " + queue);
}
}
```
- **Output**:
```
Queue: [Task1, Task2]
First: Task1
After remove: [Task1]
```

#### **Using Iterator**

- **Definition**: The `Iterator` interface (`[Link]`) provides methods to traverse a collection sequentially
- **Use**:
- Ensures safe iteration, avoiding `ConcurrentModificationException`.
- Used for processing collection elements (e.g., filtering, printing).
- `ListIterator` extends for bidirectional traversal in `List`.
- **Example**:
```java
import [Link];
import [Link];
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
Iterator<String> iterator = [Link]();
while ([Link]()) {
String item = [Link]();
[Link]("Item: " + item);
if ([Link]("B")) {
[Link]();
}
}
[Link]("After remove: " + list);
}
}
```
- **Output**:
```
Item: A
Item: B
Item: C
After remove: [A, C]
```

#### **Set Collections**

- **HashSet**:
- **Definition**: A `Set` implementation backed by a hash table, storing unique elements with no order.
- **Use**:
- Fast operations (O(1) average for add/remove/contains).
- Used for deduplication (e.g., unique user IDs).
- Allows one `null` element.
- **Example**:
```java
import [Link];
import [Link];
public class HashSetDemo {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Apple"); // Ignored
[Link]("Banana");
[Link](null);
[Link]("Set: " + set);
[Link]("Contains Banana: " + [Link]("Banana"));
[Link](null);
[Link]("After remove: " + set);
}
}
```
- **Output** (order varies):
```
Set: [null, Apple, Banana]
Contains Banana: true
After remove: [Apple, Banana]
```

- **LinkedHashSet**:
- **Definition**: A `Set` implementation that maintains insertion order, extending `HashSet`.
- **Use**:
- Preserves order of element addition.
- Used when order matters (e.g., log entries).
- **Example**:
```java
import [Link];
import [Link];
public class LinkedHashSetDemo {
public static void main(String[] args) {
Set<String> set = new LinkedHashSet<>();
[Link]("First");
[Link]("Second");
[Link]("First"); // Ignored
[Link]("Set: " + set);
}
}
```
- **Output**:
```
Set: [First, Second]
```

- **TreeSet**:
- **Definition**: A `Set` implementation backed by a Red-Black tree, maintaining sorted order (natural or custom).
- **Use**:
- Automatically sorts elements (O(log n) operations).
- Used for ordered unique data (e.g., sorted names).
- No `null` elements.
- **Example**:
```java
import [Link];
import [Link];
public class TreeSetDemo {
public static void main(String[] args) {
Set<String> set = new TreeSet<>();
[Link]("Banana");
[Link]("Apple");
[Link]("Cherry");
[Link]("Set: " + set);
[Link]("First: " + ((TreeSet<String>)set).first());
}
}
```
- **Output**:
```
Set: [Apple, Banana, Cherry]
First: Apple
```

#### **Using Dictionary**

- **Definition**: The `Dictionary` class (`[Link]`) is a legacy abstract class for key-value mappings, repl
- **Use**:
- Used in older applications for key-value storage.
- `Hashtable` (a concrete implementation) is synchronized, used in thread-safe scenarios.
- **Example**:
```java
import [Link];
public class DictionaryDemo {
public static void main(String[] args) {
Hashtable<Integer, String> dict = new Hashtable<>();
[Link](1, "One");
[Link](2, "Two");
[Link]("Value for 1: " + [Link](1));
[Link](2);
[Link]("Contains 2: " + [Link](2));
}
}
```
- **Output**:
```
Value for 1: One
Contains 2: false
```

#### **Key Points to Remember**


- **Generics**: Type safety, no casting, use `<T>` for methods/collections.
- **Collections**: `List` (ordered, duplicates), `Set` (no duplicates), `Map` (key-value).
- **ArrayList**: Fast access (O(1)), non-sync, dynamic array.
- **Vector**: Synchronized, legacy, slower than `ArrayList`.
- **LinkedList**: Fast insert/delete, implements `Deque`.
- **Iterator**: Safe traversal/removal, `hasNext()`, `next()`, `remove()`.
- **HashSet**: Unordered, fast, one `null`.
- **LinkedHashSet**: Insertion order, no duplicates.
- **TreeSet**: Sorted, no `null`, O(log n).
- **Dictionary**: Legacy, use `HashMap` or `Hashtable` (sync).
- **Exam Tip**: Practice collection operations and compare time complexities.

---

### **Java Database Connectivity (JDBC)**


#### **Role of JDBC**

- **Definition**: JDBC (Java Database Connectivity) is a Java API (`[Link]`, `[Link]`) that enables Java application
nd process results.
- **Use**:
- Performs CRUD operations (Create, Read, Update, Delete).
- Integrates Java apps with databases (e.g., MySQL, Oracle).
- Used in web apps, enterprise systems, and data-driven applications.
- **Example**:
```java
import [Link].*;
public class JdbcRoleDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = [Link](url, "root", "password");
Statement stmt = [Link]()) {
ResultSet rs = [Link]("SELECT name FROM users");
while ([Link]()) {
[Link]("User: " + [Link]("name"));
}
} catch (SQLException e) {
[Link]();
}
}
}
```

#### **JDBC Configuration**

- **Definition**: JDBC configuration involves setting up the environment to connect a Java application to a database,
e management.
- **Use**:
- Ensures proper database connectivity.
- Configures driver, URL, and credentials for specific databases.
- Critical for initializing database interactions.
- **Example**:
```java
import [Link].*;
public class JdbcConfigDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false";
String user = "root";
String password = "password";
try {
[Link]("[Link]"); // Optional in JDBC 4.0+
try (Connection conn = [Link](url, user, password)) {
[Link]("Connected to: " + [Link]());
}
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
}
```

#### **Types of Drivers**

- **Definition**: JDBC drivers are software components that translate Java JDBC calls into database-specific protocol
- **Use**:
- Enable communication with different databases.
- Chosen based on performance, portability, and deployment needs.
- **Types**:
1. **Type 1 (JDBC-ODBC Bridge)**: Uses ODBC, platform-dependent, deprecated.
2. **Type 2 (Native-API)**: Uses native database libraries, fast but platform-specific.
3. **Type 3 (Network Protocol)**: Uses middleware, database-independent.
4. **Type 4 (Thin Driver)**: Pure Java, direct connection, most common.
- **Example** (Type 4 for MySQL):
```java
import [Link].*;
public class DriverDemo {
public static void main(String[] args) {
try (Connection conn = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password")) {
[Link]("Type 4 Driver: MySQL connected");
} catch (SQLException e) {
[Link]();
}
}
}
```

#### **Connectivity with Database**

- **Definition**: Database connectivity involves establishing a connection between a Java application and a database
- **Use**:
- Initializes communication for query execution.
- Used in all database-driven applications.
- **Example**:
```java
import [Link].*;
public class ConnectivityDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false";
try (Connection conn = [Link](url, "root", "password")) {
DatabaseMetaData meta = [Link]();
[Link]("Connected to: " + [Link]());
} catch (SQLException e) {
[Link]();
}
}
}
```

#### **JDBC Statements**

- **Statement**:
- **Definition**: A `Statement` object executes static SQL queries without parameters.
- **Use**: Simple queries, prototyping, non-repetitive tasks.
- **Example**:
```java
import [Link].*;
public class StatementDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = [Link](url, "root", "password");
Statement stmt = [Link]()) {
ResultSet rs = [Link]("SELECT id, name FROM employees");
while ([Link]()) {
[Link]([Link]("id") + ": " + [Link]("name"));
}
} catch (SQLException e) {
[Link]();
}
}
}
```

- **PreparedStatement**:
- **Definition**: A `PreparedStatement` executes precompiled SQL queries with placeholders (`?`) for parameters
- **Use**: Prevents SQL injection, improves performance for repeated queries.
- **Example**:
```java
import [Link].*;
public class PreparedStatementDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = [Link](url, "root", "password");
PreparedStatement ps = [Link](
"INSERT INTO employees (id, name) VALUES (?, ?)")) {
[Link](1, 101);
[Link](2, "Alice");
[Link]();
[Link]("Employee added");
} catch (SQLException e) {
[Link]();
}
}
}
```

- **CallableStatement**:
- **Definition**: A `CallableStatement` executes database stored procedures or functions.
- **Use**: Integrates with database logic, supports input/output parameters.
- **Example**:
```java
import [Link].*;
public class CallableStatementDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = [Link](url, "root", "password");
CallableStatement cs = [Link]("{call getEmpName(?, ?)}")) {
[Link](1, 101);
[Link](2, [Link]);
[Link]();
[Link]("Name: " + [Link](2));
} catch (SQLException e) {
[Link]();
}
}
}
```

#### **Scrollable and Updatable Result Sets**

- **Definition**: Scrollable `ResultSet`s allow navigation in both directions; updatable `ResultSet`s allow modifying
- **Use**:
- Scrollable: Navigate large datasets (e.g., pagination).
- Updatable: Update database records without separate SQL.
- **Example**:
```java
import [Link].*;
public class ScrollableDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = [Link](url, "root", "password");
Statement stmt = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) {
ResultSet rs = [Link]("SELECT id, name FROM employees");
[Link](2);
[Link]("Row 2: " + [Link]("name"));
[Link]("name", "Bob");
[Link]();
[Link]();
[Link]("Row 1: " + [Link]("name"));
} catch (SQLException e) {
[Link]();
}
}
}
```

#### **DatabaseMetadata and ResultSetMetadata**

- **DatabaseMetadata**:
- **Definition**: Provides information about the database (e.g., version, tables).
- **Use**: Query database structure for dynamic applications.
- **Example**:
```java
import [Link].*;
public class DatabaseMetadataDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = [Link](url, "root", "password")) {
DatabaseMetaData dbmd = [Link]();
[Link]("DB: " + [Link]());
ResultSet rs = [Link](null, null, "%", new String[]{"TABLE"});
while ([Link]()) {
[Link]("Table: " + [Link]("TABLE_NAME"));
}
} catch (SQLException e) {
[Link]();
}
}
}
```

- **ResultSetMetadata**:
- **Definition**: Provides information about `ResultSet` columns (e.g., names, types).
- **Use**: Dynamically process query results.
- **Example**:
```java
import [Link].*;
public class ResultSetMetadataDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = [Link](url, "root", "password");
Statement stmt = [Link]()) {
ResultSet rs = [Link]("SELECT id, name FROM employees");
ResultSetMetaData rsmd = [Link]();
for (int i = 1; i <= [Link](); i++) {
[Link]("Column " + i + ": " + [Link](i));
}
} catch (SQLException e) {
[Link]();
}
}
}
```

#### **Key Points to Remember**


- **JDBC**: API for database connectivity; executes SQL queries.
- **Configuration**: Load driver, connect via `DriverManager`, close resources.
- **Drivers**: Type 4 (Thin) most common; pure Java.
- **Statements**:
- `Statement`: Static, simple.
- `PreparedStatement`: Secure, parameterized.
- `CallableStatement`: Stored procedures.
- **ResultSet**: Scrollable (`TYPE_SCROLL_INSENSITIVE`), updatable (`CONCUR_UPDATABLE`).
- **Metadata**: `DatabaseMetaData` (DB info), `ResultSetMetaData` (column info).
- **Exam Tip**: Practice full JDBC flow; know `PreparedStatement` syntax.

---

### **Java Servlet**

#### **Installing and Configuring Tomcat**

- **Definition**: Apache Tomcat is an open-source servlet container that executes Java servlets and JSPs, providing a
- **Use**:
- Hosts web applications.
- Manages servlet lifecycle and request handling.
- Used in development and production for Java web apps.
- **Example**:
- Download Tomcat 10 from `[Link]`.
- Extract to `C:\tomcat`.
- Run `bin/[Link]`.
- Access `[Link]
- Edit `conf/[Link]` to change port:
```xml
<Connector port="8081" protocol="HTTP/1.1" />
```
- Deploy app by placing `[Link]` in `webapps`.

#### **Introduction to Servlets**

- **Definition**: A servlet is a Java class that extends `HttpServlet` to handle HTTP requests and generate dynamic r
- **Use**:
- Processes form submissions, generates HTML, or serves APIs.
- Core of Java EE web applications.
- **Example**:
```java
import [Link].*;
import [Link].*;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]("text/html");
[Link]().println("<h1>Hello, Servlet!</h1>");
}
}
```

#### **Servlet Class Hierarchy**

- **Definition**: The servlet class hierarchy defines the structure of servlet classes, starting from the `Servlet` interf
- **Use**: Provides a framework for implementing servlets with HTTP-specific functionality.
- **Example**:
- Hierarchy: `Servlet` → `GenericServlet` → `HttpServlet`.
- Code snippet:
```java
public class CustomServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]().println("Custom service");
}
}
```

#### **Life Cycle of a Servlet**

- **Definition**: The servlet lifecycle consists of stages managed by the container: loading, instantiation, initialization
- **Use**: Ensures proper resource management and request processing.
- **Example**:
```java
import [Link].*;
import [Link].*;
@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {
public void init() {
[Link]("Init called");
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]().println("Handling GET request");
}
public void destroy() {
[Link]("Destroy called");
}
}
```

#### **Handling GET and POST Requests**

- **Definition**: Servlets handle HTTP methods like GET (retrieve data) and POST _(submit data)_ using `doGet()` an
- **Use**: Differentiates between read and write operations in web apps.
- **Example**:
```java
import [Link].*;
import [Link].*;
@WebServlet("/form")
public class FormServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]("text/html");
[Link]().println("<form method='post' action='form'>" +
"Name: <input type='text' name='name'>" +
"<input type='submit'></form>");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = [Link]("name");
[Link]().println("<h1>Hello, " + name + "</h1>");
}
}
```

#### **Handling Data from HTML to Servlet**

- **Definition**: Servlets retrieve data from HTML forms using `[Link]()` and related methods.
- **Use**: Processes user input for dynamic responses.
- **Example**:
```html
<!-- [Link] -->
<form action="process" method="post">
Name: <input type="text" name="username">
<input type="submit">
</form>
```
```java
import [Link].*;
import [Link].*;
@WebServlet("/process")
public class ProcessServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = [Link]("username");
[Link]("text/html");
[Link]().println("<h1>Welcome, " + username + "</h1>");
}
}
```

#### **Session Tracking**

- **Definition**: Session tracking maintains user state across HTTP requests using cookies or `HttpSession`.
- **Use**: Tracks user data (e.g., login status, cart items) in stateless HTTP.
- **Example** (HttpSession):
```java
import [Link].*;
import [Link].*;
@WebServlet("/session")
public class SessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String user = [Link]("user");
HttpSession session = [Link]();
[Link]("user", user);
[Link]().println("Session set for: " + user);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = [Link](false);
String user = session != null ? (String) [Link]("user") : "Guest";
[Link]().println("User: " + user);
}
}
```
#### **Using RequestDispatcher**

- **Definition**: `RequestDispatcher` forwards or includes requests to another resource (servlet, JSP).


- **Use**: Integrates servlets with JSPs or other servlets for modular apps.
- **Example**:
```java
import [Link].*;
import [Link].*;
import [Link].*;
@WebServlet("/forward")
public class ForwardServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]("message", "Hello from Servlet");
RequestDispatcher rd = [Link]("/[Link]");
[Link](req, resp);
}
}
```
```jsp
<%-- [Link] --%>
<h1><%= [Link]("message") %></h1>
```

#### **Key Points to Remember**


- **Tomcat**: Servlet container; configure port, deploy WARs.
- **Servlet**: Handles HTTP requests, extends `HttpServlet`.
- **Hierarchy**: `Servlet` → `GenericServlet` → `HttpServlet`.
- **Lifecycle**: `init()` → `service()` → `destroy()`.
- **Requests**: `doGet()` (retrieve), `doPost()` (submit).
- **Session**: Cookies (client), `HttpSession` (server).
- **RequestDispatcher**: `forward()`, `include()`.
- **Exam Tip**: Practice servlet-JSP integration; know lifecycle.

---

### **Java Server Pages (JSP)**

#### **Simple JSP Program**

- **Definition**: JSP is a technology for creating dynamic web pages by embedding Java code in HTML, translated to
- **Use**: Simplifies web development with dynamic content.
- **Example**:
```jsp
<%@ page language="java" contentType="text/html" %>
<html>
<body>
<h1>Hello JSP</h1>
<p>Time: <%= new [Link]() %></p>
<form action="[Link]" method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>
<% String name = [Link]("name");
if (name != null) { %>
<p>Welcome, <%= name %></p>
<% } %>
</body>
</html>
```
#### **Life Cycle of a JSP**

- **Definition**: The JSP lifecycle includes translation, compilation, and servlet-like execution stages managed by the
- **Use**: Ensures proper page processing and resource management.
- **Example**:
```jsp
<%!
public void jspInit() {
[Link]("JSP Initialized");
}
public void jspDestroy() {
[Link]("JSP Destroyed");
}
%>
<p>Request at <%= new [Link]() %></p>
```

#### **Using Directives**

- **Definition**: Directives (`<%@ %>`) provide instructions to the JSP container for page configuration or inclusion.
- **Use**: Configures page behavior and includes resources.
- **Example**:
```jsp
<%@ page contentType="text/html" import="[Link].*" %>
<%@ include file="[Link]" %>
<p>Main content</p>
```

#### **Scripting Elements**

- **Definition**: Scripting elements embed Java code in JSP for dynamic logic.
- **Use**: Generates dynamic content based on logic.
- **Example**:
```jsp
<%! int count = 0; %>
<% count++; %>
<p>Visit: <%= count %></p>
```

#### **Comments in JSP**

- **Definition**: Comments in JSP include server-side (`<%-- %>`) and client-side (`<!-- -->`) variants.
- **Use**: Documents code or hides content from clients.
- **Example**:
```jsp
<%-- JSP comment --%>
<!-- HTML comment -->
```

#### **Mixing Scriptlets and HTML**

- **Definition**: Combining scriptlets with HTML creates dynamic web content.


- **Use**: Builds dynamic UI elements like tables or lists.
- **Example**:
```jsp
<ul>
<% for (int i = 1; i <= 3; i++) { %>
<li>Item <%= i %></li>
<% } %>
</ul>
```

#### **JSP Implicit Objects**

- **Definition**: Predefined objects available in JSP for request handling, output, and session management.
- **Use**: Simplifies access to web context and data.
- **Example**:
```jsp
<p>User: <%= [Link]("user") %></p>
<p>Session ID: <%= [Link]() %></p>
```

#### **Key Points to Remember**


- **JSP**: Dynamic pages, translated to servlets.
- **Lifecycle**: Translation → `jspInit()` → `_jspService()` → `jspDestroy()`.
- **Directives**: `page`, `include`.
- **Scripting**: Declarations, expressions, scriptlets.
- **Comments**: JSP (hidden), HTML (visible).
- **Implicit Objects**: `request`, `response`, `out`, `session`.
- **Exam Tip**: Practice JSP with forms and session tracking.

---

### **General Exam Tips**


- **Practice**: Code multithreading, JDBC, servlet-JSP apps.
- **Memorize**: Lifecycles, implicit objects, key methods.
- **Test**: Set up Tomcat/MySQL, run sample apps.
- **Focus**: Syntax, differences (e.g., `ArrayList` vs. `Vector`).
- **Revise**: Key points daily for retention.

Let me know if you need specific examples or further clarification! Good luck with your exams!

You might also like