0% found this document useful (0 votes)
3 views18 pages

Advance Java

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

Advance Java

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

Module 1: Collections Framework & Legacy Classes

Q1. Explain the Java Collection Framework. Discuss the core methods
defined by the Collection, List, NavigableSet, and Queue interfaces.
Java Collection Framework:
The Java Collection Framework (JCF) is a unified architecture provided in the
[Link] package for representing and manipulating collections of objects. It
provides pre-packaged data structures (interfaces and classes) and algorithms to
store, retrieve, and manipulate data efficiently, reducing programming effort and
increasing performance.
Core Methods by Interface:
 Collection Interface (Root Interface):
o boolean add(E e): Ensures the collection contains the specified
element.
o boolean remove(Object o): Removes a single instance of the
specified element.
o void clear(): Removes all elements from the collection.
 List Interface (Ordered collection allowing duplicates):
o void add(int index, E element): Inserts the element at the specified
position.
o E get(int index): Returns the element at the specified position.
o E set(int index, E element): Replaces the element at the specified
position with the new element.
 NavigableSet Interface (SortedSet with navigation methods):
o E lower(E e): Returns the greatest element strictly less than the
given element, or null if none exists.
o E higher(E e): Returns the least element strictly greater than the
given element.
o E pollFirst(): Retrieves and removes the first (lowest) element.
 Queue Interface (FIFO data structure):
o boolean offer(E e): Inserts an element (preferred over add for
capacity-restricted queues).
o E poll(): Retrieves and removes the head of the queue (returns null
if empty).
o E peek(): Retrieves, but does not remove, the head of the queue.
Q2. Define a Comparator. Explain how it differs from Comparable and
write a Java program demonstrating sorting elements in a TreeSet in
reverse order.
Comparator Definition:
[Link] is an interface used to define custom, external sorting logic
for user-defined objects. It allows sorting objects based on multiple data
members and different sequences (e.g., ascending or descending).
Difference between Comparable and Comparator:

Feature Comparable Comparator

Package [Link] [Link]

compare(Object obj1,
Method compareTo(Object obj)
Object obj2)

Defines natural (default) Defines custom (multiple)


Sorting Logic
sorting. sorting sequences.

Original class remains


Original class must be
Modification untouched (implemented
modified to implement it.
externally).

Program: TreeSet Reverse Order Sorting


Java
import [Link].*;

// Custom Comparator for reverse sorting


class ReverseSort implements Comparator<Integer> {
public int compare(Integer num1, Integer num2) {
return [Link](num1); // Reverses natural order
}
}

public class TreeSetReverse {


public static void main(String[] args) {
// Pass the custom comparator to the TreeSet constructor
TreeSet<Integer> ts = new TreeSet<>(new ReverseSort());
[Link](10);
[Link](50);
[Link](30);
[Link](20);

[Link]("Reverse Sorted TreeSet: " + ts);


// Output: [50, 30, 20, 10]
}
}
Q3. What are Legacy Classes? Explain any four legacy classes of Java's
Collection framework with their characteristics.
Legacy Classes:
Before the Collections Framework was introduced in JDK 1.2, Java provided
several classes to store and manipulate objects. These are known as legacy
classes. They were later re-engineered to implement the new collection
interfaces. A key characteristic of all legacy classes is that they are fully
synchronized (thread-safe), which makes them slightly slower in single-
threaded environments compared to modern alternatives.
Four Key Legacy Classes:
1. Vector: Implements a dynamic array. It is similar to ArrayList but is
synchronized. It contains many legacy methods not part of the collections
framework (like addElement()).
2. Hashtable: Implements a hash table mapping keys to values. It is similar
to HashMap but is synchronized and strictly prohibits null keys or null
values.
3. Stack: A subclass of Vector that implements a standard Last-In-First-Out
(LIFO) stack. It provides standard operations like push() to add, pop() to
remove, and peek() to view the top element.
4. Properties: A subclass of Hashtable where both keys and values are
strictly of type String. It is widely used to manage application
configuration settings and properties files.
Q4. Describe the concept of Spliterators in Java. Enumerate the key
methods and characteristics provided by the Spliterator interface.
Concept:
Introduced in Java 8, Spliterator (Splitable Iterator) is designed for traversing
and partitioning sequences of elements. Unlike standard Iterators that process
elements sequentially, Spliterators are optimized for parallel processing. They
can split a collection into multiple parts, allowing different threads to process
them simultaneously using Java Streams.
Key Methods:
 boolean tryAdvance(Consumer<? super T> action): If a remaining
element exists, it performs the action on it and returns true; otherwise, it
returns false.
 Spliterator<T> trySplit(): If the Spliterator can be partitioned, it returns a
new Spliterator covering some elements, while the original Spliterator
covers the rest. Returns null if splitting is not possible.
 long estimateSize(): Returns an estimate of the number of elements left to
traverse.
Characteristics (Flags):
Spliterators provide an int characteristics() method that returns a bitwise OR of
flags representing properties of the source:
 ORDERED: Elements have a strictly defined sequence.
 DISTINCT: No two elements are equal (like in a Set).
 SORTED: Elements follow a predefined sorting order.
 SIZED: The exact number of elements is known (estimateSize() returns
an exact count).
Module 2: String Handling & Manipulation
Q1. Explain the following StringBuffer methods with clear code examples:
append(), insert(), reverse(), and delete().
StringBuffer represents a mutable, thread-safe sequence of characters. Its
methods modify the existing object rather than creating a new one.
Java
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");

// 1. append(): Adds string to the end


[Link](" Programming");
[Link]("After append: " + sb);
// Output: Java Programming

// 2. insert(): Inserts string at specified index


[Link](5, "Advanced ");
[Link]("After insert: " + sb);
// Output: Java Advanced Programming

// 3. delete(): Removes characters from start index to (end - 1)


[Link](5, 14); // Removes "Advanced "
[Link]("After delete: " + sb);
// Output: Java Programming

// 4. reverse(): Reverses the entire character sequence


[Link]();
[Link]("After reverse: " + sb);
// Output: gnimmargorP avaJ
}
}
Q2. Differentiate between String, StringBuffer, and StringBuilder classes.

Feature String StringBuffer StringBuilder

Immutable
(Cannot be Mutable (Can Mutable (Can be
Mutability
modified after be modified). modified).
creation).

Inherently
Thread-safe
Thread thread-safe Not thread-safe
(Methods are
Safety (due to (Unsynchronized).
synchronized).
immutability).

Slow (creates a Moderate


Fastest (no
new object for (slower due to
Performance synchronization
every synchronization
overhead).
modification). overhead).

String Pool /
Storage Heap memory. Heap memory.
Heap memory.

Q3. Discuss the various overloaded constructors of the String class with
suitable programming examples.
The String class provides several constructors to initialize strings from various
data sources.
1. Default Constructor: Creates an empty string.
Java
String s1 = new String();
2. Character Array Constructor: Creates a string from an array of characters.
Java
char[] chars = {'V', 'T', 'U'};
String s2 = new String(chars); // Result: "VTU"
3. Sub-array Constructor: String(char[] chars, int startIndex, int numChars)
extracts a portion of a char array.
Java
char[] chars = {'A', 'd', 'v', 'a', 'n', 'c', 'e', 'd'};
String s3 = new String(chars, 0, 3); // Result: "Adv"
4. Byte Array Constructor: Constructs a string by decoding a byte array
(useful for I/O operations).
Java
byte[] ascii = {65, 66, 67, 68};
String s4 = new String(ascii); // Result: "ABCD"
Q4. Compare the equals() method and the == operator. Explain indexOf()
and lastIndexOf().
equals() vs ==:
 equals() method: Compares the actual character content of the strings for
equality.
 == operator: Compares object memory references (i.e., whether both
references point to the exact same object in memory).
Java
String s1 = new String("Hello");
String s2 = new String("Hello");
[Link]([Link](s2)); // true (contents are same)
[Link](s1 == s2); // false (different memory locations)
indexOf() and lastIndexOf():
Used to search for characters or substrings within a string. They return -1 if the
target is not found.
 indexOf(String str): Searches from left-to-right. Returns the index of the
first occurrence.
 lastIndexOf(String str): Searches from right-to-left. Returns the index of
the last occurrence.
Java
String text = "programming";
[Link]([Link]('r')); // Output: 1 (first 'r')
[Link]([Link]('r')); // Output: 4 (last 'r')
Module 3: Java Swing Architecture & Components
Q1. Describe the Model-View-Controller (MVC) design pattern and explain
how it is implemented within Java Swing applications.
MVC Architecture:
MVC is a design pattern that separates an application into three interconnected
components to separate internal representations of data from the ways
information is presented to the user.
1. Model: Manages the data, logic, and rules of the application (State).
2. View: Renders the UI and displays the data from the Model to the user.
3. Controller: Intercepts user inputs (events), translates them, and updates
the Model or View accordingly.
Implementation in Swing (Model-Delegate Pattern):
Swing uses a modified MVC called the Model-Delegate architecture. In
Swing, the View and Controller are often combined into a single UI object
called a "delegate," while the Model remains separate.
 Example: A JButton is the View (what you see) and contains the
Controller logic (the ActionListener you attach to it). The button's pressed
state is stored in its underlying Model (ButtonModel).
Q2. Develop a comprehensive Java Swing program that creates a GUI
containing a JLabel, JTextField, and a JButton that handles event actions
using an ActionListener.
Java
import [Link].*;
import [Link].*;
import [Link].*;
public class SwingDemo {
public static void main(String[] args) {
// Create Frame
JFrame frame = new JFrame("Swing Action Demo");
[Link](300, 200);
[Link](new FlowLayout());
[Link](JFrame.EXIT_ON_CLOSE);

// Create Components
JLabel label = new JLabel("Enter Name: ");
JTextField textField = new JTextField(15);
JButton button = new JButton("Submit");

// Add ActionListener to Button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = [Link]();
// Display input in a dialog box
[Link](frame, "Welcome, " + input);
}
});

// Add components to frame


[Link](label);
[Link](textField);
[Link](button);
// Set visibility
[Link](true);
}
}
Q3. Elaborate on the concept of painting in Java Swing. Explain the
specific role of the paintComponent(Graphics g) method with an example.
Painting in Swing:
Swing components are lightweight, meaning they don't rely on native OS peers
for rendering. Instead, they draw themselves onto a top-level container (like
JFrame). Swing handles painting via an automatic, double-buffered rendering
pipeline.
The paintComponent(Graphics g) method:
To draw custom graphics (shapes, images) in Swing, you extend a component
(usually JPanel) and override the protected void paintComponent(Graphics g)
method.
 Crucial Rule: You must always call [Link](g) as the first
line to ensure the background is cleared and UI artifacts are not left
behind.
Example:
Java
class CustomPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
[Link](g); // Clear background
[Link]([Link]);
[Link](50, 50, 100, 100); // Draw custom graphics
}
}
Q4. Discuss the evolution and key features of Java Swing, highlighting how
it builds on top of the Abstract Window Toolkit (AWT).
Evolution (AWT to Swing):
Java initially provided AWT for GUI development. AWT used "heavyweight"
components directly mapped to OS-native GUI elements. This caused
applications to look and behave differently across Windows, Mac, and Linux.
Swing was introduced in the JFC (Java Foundation Classes) to solve this.
Swing vs. AWT / Key Features of Swing:
1. Lightweight Components: Swing components are written entirely in
Java and do not rely on native OS peers, making them highly efficient
and perfectly consistent across platforms.
2. Pluggable Look and Feel (PLAF): Developers can change the visual
appearance of a Swing application at runtime (e.g., making it look like
Windows, Mac, or standard Java Metal) without changing the underlying
code.
3. MVC Architecture: Swing components are built on the Model-Delegate
MVC architecture.
4. Rich Component Set: Swing provides advanced components that AWT
lacked, such as JTable, JTree, and JTabbedPane.
Module 4: Servlets & JSP
Q1. Explain the complete Life Cycle of a Java Servlet along with a
structural diagram showing all execution stages.
A servlet's life cycle is managed by the Servlet Container (like Apache Tomcat).
It consists of three main functional phases.
Lifecycle Stages:
1. Initialization (init): When the servlet is first requested, the container
loads the servlet class, instantiates it, and calls the init(ServletConfig
config) method exactly once. Used for establishing database connections
or loading resources.
2. Service (service): For every client request, the container spawns a new
thread and calls the service(ServletRequest, ServletResponse) method.
The service method checks the HTTP request type (GET, POST, etc.) and
dispatches it to the appropriate handler method (doGet, doPost).
3. Destruction (destroy): When the container shuts down or unloads the
servlet, it calls the destroy() method once. Used for closing connections
and resource cleanup.
Structural Flow Diagram:
Plaintext
[ Client Request ]
|
v
[ Web Container ] ---> (If Servlet not loaded) ---> 1. init()
|
v
2. service() ---> (Dispatches to doGet() or doPost())
|
v
[ Server Shutdown ] ---> 3. destroy() ---> [ Garbage Collection ]
Q2. Define JSP. Explain the different categories of JSP tags with syntax
guidelines.
JSP (JavaServer Pages):
JSP is a server-side technology used to create dynamic web pages. It allows
developers to embed Java code directly inside HTML using specific tags. When
requested, the JSP engine translates the JSP file into a Java Servlet, compiles it,
and executes it.
JSP Tags:
1. Directives <%@ ... %>: Provide global instructions to the JSP container
about page translation.
o Syntax: <%@ page import="[Link].*" %>
2. Declarations <%! ... %>: Used to declare class-level variables or
methods. These are placed outside the service() method of the generated
servlet.
o Syntax: <%! int counter = 0; %>
3. Scriptlets <% ... %>: Used to contain standard Java code. This code is
inserted directly into the service() method of the generated servlet.
o Syntax: <% [Link]("Hello"); %>
4. Expressions <%= ... %>: Evaluates a Java expression, converts it to a
String, and outputs it directly to the HTML page. (No semicolon at the
end).
o Syntax: <%= new [Link]() %>
Q3. Discuss Session Tracking mechanisms in web development. Expand on
how Session objects and Cookies are set up and handled in Servlets.
Session Tracking:
HTTP is a stateless protocol; it forgets client data as soon as a request is
fulfilled. Session tracking is the mechanism to maintain state (user data) across
multiple requests from the same client (e.g., keeping a user logged in or
managing a shopping cart).
1. HttpSession Object:
Provides a way to store data on the server-side linked to a unique session ID.
 Creation/Retrieval: HttpSession session = [Link]();
 Setting Data: [Link]("username", "Nihan");
 Getting Data: String user = (String) [Link]("username");
2. Cookies:
Small text files stored on the client's browser. Sent back to the server with every
request.
 Creation: Cookie c = new Cookie("userRole", "admin");
 Sending to Client: [Link](c);
 Reading from Client: ```java
Cookie[] cookies = [Link]();
if(cookies != null) {
// loop through to find specific cookie
}
Q4. List and describe the core classes and interfaces present in the
standard servlet package framework ([Link]).
The [Link] (formerly [Link]) package contains the core generic
API for servlets.
Core Interfaces:
1. Servlet: The central interface all servlets must implement. Defines
lifecycle methods (init, service, destroy).
2. ServletRequest & ServletResponse: Objects passed into the service
method. They encapsulate the data sent from the client and the response
sent back.
3. ServletConfig: Contains configuration data (initialization parameters)
passed to the servlet during init().
4. ServletContext: Represents the entire web application environment,
allowing servlets to communicate with the container and share global
data.
Core Classes:
1. GenericServlet: An abstract class that implements the Servlet and
ServletConfig interfaces. It provides a protocol-independent servlet.
2. HttpServlet (in [Link]): An abstract class extending
GenericServlet, explicitly designed for handling HTTP requests.
Developers extend this and override doGet or doPost.
Module 5: JDBC Database Connectivity
Q1. Explain the significance of JDBC. Detail and explain the four distinct
types of JDBC Drivers.
Significance of JDBC:
Java Database Connectivity (JDBC) is an API that allows Java applications to
interact with relational databases (MySQL, Oracle, etc.). It provides a standard
abstraction layer so developers can write database-independent code using SQL.
Four Types of JDBC Drivers:
1. Type-1: JDBC-ODBC Bridge Driver: Translates JDBC calls into
ODBC calls. It requires the ODBC driver to be installed on the client
machine. (Deprecated in modern Java).
2. Type-2: Native-API Driver: Converts JDBC calls into native C/C++
API calls of the specific database. Requires database client libraries
installed on the client machine.
3. Type-3: Network Protocol Driver: Translates JDBC calls into a
middleware-specific protocol, which the middleware server translates into
database-specific calls. Ideal for enterprise environments.
4. Type-4: Thin Driver (Pure Java Driver): Converts JDBC calls directly
into the vendor-specific database network protocol. It requires no native
libraries or middleware and is the most widely used driver today (e.g.,
MySQL Connector/J).
Q2. Detail the exact procedural steps involved in the JDBC process to
connect to a database. Provide a clean code snippet implementing these
steps.
Procedural Steps:
1. Import Packages: Import [Link].*.
2. Load/Register the Driver: Use [Link]() to load the driver class
dynamically.
3. Establish Connection: Use [Link]() passing the
DB URL, username, and password.
4. Create Statement: Call [Link]() to create an
execution object.
5. Execute Query: Execute SQL queries using executeQuery() for SELECT
or executeUpdate() for INSERT/UPDATE.
6. Process Results: Iterate through the returned ResultSet.
7. Close Connections: Close the ResultSet, Statement, and Connection to
prevent memory leaks.
Code Snippet:
Java
import [Link].*;

public class JDBCDemo {


public static void main(String[] args) {
try {
// 2. Load Driver
[Link]("[Link]");

// 3. Establish Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/myDB", "root", "password");

// 4. Create Statement
Statement stmt = [Link]();

// 5. Execute Query
ResultSet rs = [Link]("SELECT id, name FROM students");

// 6. Process Results
while([Link]()) {
[Link]([Link]("id") + " : " + [Link]("name"));
}

// 7. Close Connections
[Link]();
[Link]();
[Link]();

} catch(Exception e) {
[Link]();
}
}
}
Q3. Explain and differentiate between DatabaseMetaData and
ResultSetMetaData with distinct use-case examples for each.
1. DatabaseMetaData:
Provides macro-level information about the database engine itself, rather than
the data. It is retrieved using [Link]().
 Use-case: Checking database product name, driver version, supported
SQL features, or listing all tables present in the database.
 Example: DatabaseMetaData dbmd = [Link]();
[Link]([Link]());
2. ResultSetMetaData:
Provides structural micro-level information about the specific columns returned
in a ResultSet after a query is executed. Retrieved using
[Link]().
 Use-case: Determining the number of columns returned, column names,
and the SQL data types of those columns (useful when generating
dynamic tables).
 Example: ResultSetMetaData rsmd = [Link]();
[Link]("Column count: " + [Link]());
Q4. What is a Statement object in JDBC? Differentiate between Statement,
PreparedStatement, and CallableStatement.
Statement Object:
An object used to send SQL commands to the database.
Differentiation:

CallableStatem
Feature Statement PreparedStatement
ent

Executes
Executes basic, Executes
parameterized
Usage static SQL database Stored
(dynamic) SQL
statements. Procedures.
statements.
CallableStatem
Feature Statement PreparedStatement
ent

Query is Calls pre-


compiled every compiled code
Compilat Query is pre-compiled
time it is stored directly
ion once and cached.
executed by the on the DB
DB. server.

Prevents SQL
Vulnerable to Injection Inherently
Security
SQL Injection. (automatically escapes secure.
inputs).

[Link](
[Link](
[Link] "{call
Creation "INSERT INTO table
ment(); myProcedure()}
VALUES (?)");
");

Much faster for Fastest for


Performa Slower for
executing the same complex, multi-
nce repetitive tasks.
query multiple times. step DB logic.

You might also like