0% found this document useful (0 votes)
2 views19 pages

Advanced Java Complete VTU Answers

Uploaded by

vvk4486
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)
2 views19 pages

Advanced Java Complete VTU Answers

Uploaded by

vvk4486
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

ADVANCED JAVA (BIS402)

Complete VTU 10-Mark Answers

All Repeated Questions with Detailed Solutions

Prepared: 23-06-2026

CBCS Scheme (2023-24 onwards)


MODULE - 1: COLLECTIONS FRAMEWORK

Q1.1: Collection Framework - Methods & Interfaces

[Repetitions: 4 times] [Marks: 10]


Question: What is Collection Framework? Explain the methods defined by Collection Interface. List and explain the various
String comparison methods.

Answer:
Collection Framework: Collection Framework is a unified architecture for representing and manipulating groups of objects. It
provides interfaces (Collection, List, Set, Queue) and classes (ArrayList, LinkedList, HashSet, etc.) to handle groups of objects
efficiently.

Collection Interface Methods:


1. add(E e) - Adds element to collection
2. remove(Object o) - Removes specified element
3. clear() - Removes all elements
4. contains(Object o) - Checks if element exists
5. isEmpty() - Returns true if collection is empty
6. size() - Returns number of elements
7. iterator() - Returns Iterator for traversal
8. toArray() - Converts collection to array

Key Interfaces in Collection Framework:


• List: Ordered collection allowing duplicates (ArrayList, LinkedList, Vector)
• Set: Unordered collection with no duplicates (HashSet, TreeSet)
• Queue: FIFO data structure (PriorityQueue, Deque)
• Map: Key-value pairs (HashMap, TreeMap)

Advantages: Reusable components, type-safe (generics), optimized performance, reduced development effort, standardized
API.

Q1.2: Legacy Classes in Java Collections

[Repetitions: 3 times] [Marks: 10]


Question: Explain any four legacy classes of Java's Collection Framework with example.

Answer:
Legacy Classes are older collection classes that were part of Java before the Collection Framework was introduced. They are
now integrated into the framework.

1. Vector: Legacy List implementation, synchronized, similar to ArrayList. Slower than ArrayList due to synchronization.
Deprecated for new code.
Example: Vector v = new Vector<>();

2. Hashtable: Legacy Map implementation, synchronized, thread-safe. Similar to HashMap but older.
Example: Hashtable ht = new Hashtable<>();

3. Stack: LIFO (Last-In-First-Out) data structure, extends Vector. Methods: push(), pop(), peek(), search().
Example: Stack stack = new Stack<>();

4. Properties: Subclass of Hashtable for handling properties. Stores String key-value pairs from property files.
Example: Properties props = new Properties();

Comparison with Modern Classes:


Vector → ArrayList (faster, unsynchronized)
Hashtable → HashMap (faster, unsynchronized)
Stack is still used as it's specialized
Note: Legacy classes are synchronized but slower. Use modern alternatives unless thread-safety is critical.
Q1.3: ArrayList and List Operations

[Repetitions: 2 times] [Marks: 10]


Question: Create a class STUDENT with USN and Name using LinkedList. Write a program to add at least 3 objects and
display.

Answer:
LinkedList is a doubly-linked list implementation providing O(1) insertion/deletion at ends but O(n) access time for elements.

class Student { private String USN; private String Name; Student(String USN, String Name) { [Link] = USN;
[Link] = Name; } public String getUSN() { return USN; } public String getName() { return Name; } public void
display() { [Link]("USN: " + USN + ", Name: " + Name); } } public class StudentManagement { public
static void main(String[] args) { LinkedList list = new LinkedList<>(); // Add 3+ students [Link](new
Student("USN001", "Raj Kumar")); [Link](new Student("USN002", "Priya Singh")); [Link](new
Student("USN003", "Amit Patel")); [Link](new Student("USN004", "Neha Sharma")); [Link]("=====
Student List ====="); for(Student s : list) { [Link](); } [Link]("Total: " + [Link]());
[Link]("First: " + [Link]().getName()); [Link]("Last: " +
[Link]().getName()); } }

LinkedList Methods: add(), addFirst(), addLast(), getFirst(), getLast(), removeFirst(), removeLast(), size(), iterator().

Q1.4: NavigableSet Methods

[Repetitions: 1 time] [Marks: 10]


Question: Explain the methods of NavigableSet class with a sample program.

Answer:
NavigableSet extends SortedSet and provides methods to navigate the set in both directions. TreeSet is the main
implementation of NavigableSet.

Key Methods:
1. lower(E e) - Returns greatest element less than e
2. floor(E e) - Returns greatest element less than or equal to e
3. ceiling(E e) - Returns least element greater than or equal to e
4. higher(E e) - Returns least element greater than e
5. pollFirst() - Retrieves and removes first element
6. pollLast() - Retrieves and removes last element
7. descendingIterator() - Returns iterator in reverse order
8. descendingSet() - Returns view in reverse order

TreeSet set = new TreeSet<>(); [Link](10); [Link](20); [Link](30); [Link](40); [Link](50);


[Link]("Floor of 35: " + [Link](35)); // 30 [Link]("Ceiling of 35: " +
[Link](35)); // 40 [Link]("Lower of 30: " + [Link](30)); // 20 [Link]("Higher
of 30: " + [Link](30)); // 40 [Link]("Descending: " + [Link]()); //
[50,40,30,20,10]

Q1.5: Iterator Access in Collections

[Repetitions: 1 time] [Marks: 10]


Question: Explain how collectors can be accessed using an iterator with example.

Answer:
Iterator provides a way to traverse through collection elements sequentially without exposing underlying structure. It is the most
common way to iterate over collections.

Iterator Interface Methods:


1. hasNext() - Returns true if more elements exist
2. next() - Returns next element
3. remove() - Removes current element

ListIterator Methods (extends Iterator):


1. hasPrevious() - Check previous element
2. previous() - Get previous element
3. add(E e) - Insert element
4. set(E e) - Replace current element

ArrayList list = new ArrayList<>(); [Link]("Java"); [Link]("Python"); [Link]("C++"); // Using Iterator


Iterator itr = [Link](); while([Link]()) { [Link]([Link]()); } // Using ListIterator
(forward & backward) ListIterator litr = [Link](); while([Link]()) {
[Link]("Forward: " + [Link]()); } while([Link]()) { [Link]("Backward: " +
[Link]()); } // Using enhanced for loop (simplest) for(String s : list) { [Link](s); }

Advantages of Iterator: Safe removal, works with all collections, memory efficient, no element access required.
MODULE - 2: STRING HANDLING

Q2.1: String Constructors

[Repetitions: 3 times] [Marks: 10]


Question: What is String in Java? Write a program demonstrating any six constructors of String class.

Answer:
String is an immutable sequence of characters in Java. Once created, its value cannot be changed. Strings are stored in the
String Pool for memory efficiency.

Properties of String:
• Immutable: Cannot be modified after creation
• Thread-safe: Safe for concurrent access
• String Pool: Strings stored in special memory region
• Comparable: Supports comparison operations
• Hashable: Can be used as HashMap key

public class StringConstructorsDemo { public static void main(String[] args) { // Constructor 1: Empty String
String s1 = new String(); [Link]("1. Empty: '" + s1 + "'"); // Constructor 2: From String Literal
String s2 = new String("Hello World"); [Link]("2. From Literal: " + s2); // Constructor 3: From
Character Array char[] chars = {'J', 'a', 'v', 'a'}; String s3 = new String(chars); [Link]("3. From
Char Array: " + s3); // Constructor 4: From Byte Array byte[] bytes = {72, 101, 108, 108, 111}; String s4 = new
String(bytes); [Link]("4. From Byte Array: " + s4); // Constructor 5: Substring from Character
Array String s5 = new String(chars, 0, 2); [Link]("5. Char Array Subset: " + s5); // Constructor 6:
From StringBuffer StringBuffer sb = new StringBuffer("Content"); String s6 = new String(sb);
[Link]("6. From StringBuffer: " + s6); } } Output: 1. Empty: '' 2. From Literal: Hello World 3.
From Char Array: Java 4. From Byte Array: Hello 5. Char Array Subset: Ja 6. From StringBuffer: Content

Q2.2: String Comparison Methods

[Repetitions: 3 times] [Marks: 10]


Question: List and explain the various String comparison methods.

Answer:
String Comparison Methods:

1. equals(Object obj): Compares exact string content. Returns true if content is same. Case-sensitive.
Example: 'java'.equals('java') → true

2. equalsIgnoreCase(String s): Compares ignoring case. Useful for case-insensitive comparison.


Example: 'Java'.equalsIgnoreCase('java') → true

3. == operator: Compares reference, not content. Checks if both strings point to same object in memory.
Example: s1 == s2 checks reference, not value

4. compareTo(String s): Lexicographic comparison. Returns 0 if equal, negative if less, positive if greater.
Example: 'abc'.compareTo('abd') → -1

5. compareToIgnoreCase(String s): Lexicographic comparison ignoring case.


Example: 'ABC'.compareToIgnoreCase('abc') → 0

6. startsWith(String prefix): Checks if string starts with given prefix.


Example: 'Hello World'.startsWith('Hello') → true

7. endsWith(String suffix): Checks if string ends with given suffix.


Example: 'Hello World'.endsWith('World') → true

8. contains(CharSequence seq): Checks if string contains given sequence.


Example: 'Hello World'.contains('lo Wo') → true

String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); [Link](s1 == s2); // true
(same reference) [Link](s1 == s3); // false (diff reference) [Link]([Link](s3)); //
true (same content) [Link]("JAVA".equalsIgnoreCase(s1)); // true
[Link]([Link](s2)); // 0 (equal) [Link]("abc".compareTo("abd")); // -1 (less)

Q2.3: StringBuffer Methods

[Repetitions: 4 times] [Marks: 10]


Question: Explain StringBuffer methods: append(), insert(), reverse(), replace(). Write suitable example code.

Answer:
StringBuffer is a mutable, thread-safe class for dynamic string manipulation. Unlike String, it can be modified after creation.

1. append(String s): Adds string at END. Returns StringBuffer for chaining.


Syntax: [Link](str);

2. insert(int offset, String s): Inserts string at specified INDEX. Shifts existing characters forward.
Syntax: [Link](index, str);

3. reverse(): REVERSES the character sequence. Modifies original buffer.


Syntax: [Link]();

4. replace(int start, int end, String str): REPLACES characters in range. Characters from start (inclusive) to end (exclusive)
are replaced.
Syntax: [Link](start, end, str);

StringBuffer sb = new StringBuffer("Hello"); // append() [Link](" World"); [Link](sb); // Hello


World // insert() StringBuffer sb2 = new StringBuffer("Hello"); [Link](5, " Java");
[Link](sb2); // Hello Java // reverse() StringBuffer sb3 = new StringBuffer("Java");
[Link](); [Link](sb3); // avaJ // replace() StringBuffer sb4 = new StringBuffer("Hello
World"); [Link](0, 5, "Hi"); [Link](sb4); // Hi World // Method Chaining StringBuffer sb5 =
new StringBuffer("A"); [Link]("B").append("C").reverse(); [Link](sb5); // CBA

StringBuffer vs String: StringBuffer is mutable (changeable), synchronized (thread-safe), slower. Use for frequent
modifications. String is immutable, not thread-safe, faster.

Q2.4: Character Extraction Methods

[Repetitions: 2 times] [Marks: 10]


Question: Explain any two character extraction methods of String class.

Answer:
Character Extraction Methods:

1. charAt(int index): Returns character at specified index. Index is 0-based. Throws StringIndexOutOfBoundsException if
invalid.
Syntax: char c = [Link](index);
Example: 'Hello'.charAt(1) → 'e'

2. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Copies characters from string to character array.
Parameters: srcBegin (inclusive), srcEnd (exclusive)
Syntax: [Link](0, 5, charArray, 0);

3. toCharArray(): Converts entire string to character array.


Returns: char[] array containing all characters
Example: char[] arr = 'Hello'.toCharArray();
4. codePointAt(int index): Returns Unicode code point at index.
Returns: int representing Unicode value
Example: 'A'.codePointAt(0) → 65

String str = "Hello"; // charAt() [Link]([Link](0)); // H [Link]([Link](4));


// o // toCharArray() char[] arr = [Link](); for(char c : arr) { [Link](c); } //
getChars() char[] dest = new char[5]; [Link](0, 5, dest, 0); [Link](new String(dest)); //
Hello // codePointAt() [Link]([Link](0)); // 72 (H)
[Link]([Link](1)); // 101 (e)

Q2.5: Duplicate Character Removal

[Repetitions: 2 times] [Marks: 10]


Question: Write a program to remove duplicate characters from a given String and display the result.

Answer:
Duplicate removal maintains the order of first occurrence while removing repeated characters.

Approach 1: Using Boolean Array (Most Efficient)


public class RemoveDuplicates { public static String removeDuplicates(String str) { StringBuilder result = new
StringBuilder(); boolean[] seen = new boolean[256]; // ASCII table for(char c : [Link]()) {
if(!seen[c]) { [Link](c); seen[c] = true; } } return [Link](); } public static void
main(String[] args) { String input = "programming"; String output = removeDuplicates(input);
[Link]("Input: " + input); [Link]("Output: " + output); // Output: progamin } } Time
Complexity: O(n) Space Complexity: O(1) [fixed array of 256]

Approach 2: Using LinkedHashSet (Preserves Order)


import [Link].*; public class RemoveDuplicatesHashSet { public static String removeDuplicates(String str) {
Set set = new LinkedHashSet<>(); for(char c : [Link]()) { [Link](c); } StringBuilder result = new
StringBuilder(); for(char c : set) { [Link](c); } return [Link](); } public static void
main(String[] args) { [Link](removeDuplicates("hello")); // helo
[Link](removeDuplicates("aabbcc")); // abc } }
MODULE - 3: SWING & GUI

Q3.1: Swing Features & Components

[Repetitions: 3 times] [Marks: 10]


Question: Explain the key features of Swing with a sample program.

Answer:
Swing is a lightweight GUI toolkit for Java providing pure Java implementation of GUI components built on top of AWT.

Key Features of Swing:


1. Lightweight: Implemented entirely in Java, no native peers
2. Platform Independent: Consistent look across all platforms
3. Rich Components: JButton, JLabel, JTextField, JTable, JTree, etc.
4. Pluggable Look & Feel: Change UI theme dynamically
5. MVC Architecture: Separates data from presentation
6. Advanced Features: Drag-drop, double-buffering, tooltips
7. Better Performance: Optimized rendering and event handling
8. Thread Safety: Uses Event Dispatch Thread (EDT)

import [Link].*; import [Link].*; public class SwingDemo extends JFrame { private JLabel label;
private JTextField textField; private JButton submitBtn, clearBtn; public SwingDemo() { setTitle("Swing
Application"); setSize(400, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel panel = new JPanel();
[Link](null); label = new JLabel("Enter Name:"); [Link](50, 30, 100, 30); textField = new
JTextField(); [Link](150, 30, 150, 30); submitBtn = new JButton("Submit");
[Link](100, 100, 80, 30); [Link](e -> { String name = [Link]();
[Link](this, "Hello " + name); }); clearBtn = new JButton("Clear");
[Link](200, 100, 80, 30); [Link](e -> [Link](""));
[Link](label); [Link](textField); [Link](submitBtn); [Link](clearBtn); add(panel);
setVisible(true); } public static void main(String[] args) { new SwingDemo(); } }

Q3.2: JButton, JToggleButton, Icons

[Repetitions: 2 times] [Marks: 10]


Question: Write a program demonstrating icons using JButton and JToggleButton.

Answer:
JButton: A component for creating push buttons with optional icons. Fires action event when clicked.

JToggleButton: A button that can be toggled on/off. Useful for buttons with two states.

import [Link].*; import [Link].*; public class ButtonDemo extends JFrame { public ButtonDemo() {
setTitle("Button Icons Demo"); setSize(400, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel panel = new
JPanel(); // JButton with icon ImageIcon icon = new ImageIcon("[Link]"); JButton btn = new JButton("Click
Me", icon); [Link](e -> [Link](this, "Button Clicked!")); //
JToggleButton JToggleButton toggleBtn = new JToggleButton("On/Off"); [Link](e -> {
if([Link]()) { [Link]("ON"); } else { [Link]("OFF"); } }); [Link](btn);
[Link](toggleBtn); add(panel); setVisible(true); } public static void main(String[] args) { new
ButtonDemo(); } }

Q3.3: Simple Swing Application

[Repetitions: 2 times] [Marks: 10]


Question: Write a program to create a simple swing application with buttons and event handling.

Answer:
This demonstrates basic Swing application with buttons, labels, and event handling.
import [Link].*; import [Link].*; public class SimpleApp extends JFrame { private JLabel label;
private int count = 0; public SimpleApp() { setTitle("Counter App"); setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); JPanel panel = new JPanel();
[Link](null); label = new JLabel("Count: 0"); [Link](50, 30, 200, 30);
[Link]([Link]().deriveFont(16f)); JButton incBtn = new JButton("Increment");
[Link](50, 80, 100, 30); [Link](e -> { count++; [Link]("Count: " + count);
}); JButton decBtn = new JButton("Decrement"); [Link](160, 80, 100, 30); [Link](e
-> { count--; [Link]("Count: " + count); }); JButton resetBtn = new JButton("Reset");
[Link](100, 130, 100, 30); [Link](e -> { count = 0; [Link]("Count: 0");
}); [Link](label); [Link](incBtn); [Link](decBtn); [Link](resetBtn); add(panel); setVisible(true);
} public static void main(String[] args) { [Link](() -> new SimpleApp()); } }

Q3.4: Swing vs AWT

[Repetitions: 2 times] [Marks: 10]


Question: Compare Swing and AWT. Explain differences.

Answer:

Feature AWT Swing

Components Heavyweight Lightweight

Implementation Uses native OS Pure Java

Look & Feel Platform-dependent Platform-independent

Pluggable L&F No Yes (Metal, Nimbus)

Performance Faster Slightly slower

Components Limited (~30) Extensive (>100)

Double Buffering Manual Built-in

Drag & Drop Limited Full support

Recommended Legacy apps only All new applications

Why Swing over AWT: Swing provides better functionality, platform independence, richer components, better performance, and
modern features like drag-drop.

Q3.5: MVC Architecture

[Repetitions: 2 times] [Marks: 10]


Question: Explain MVC Connector Architecture in Swing.

Answer:
MVC (Model-View-Controller) is an architectural pattern separating an application into three components.

1. Model: Represents data and business logic. Independent of UI. Notifies Views of data changes.

2. View: Displays data to user. Does not modify data directly. Represents current state of Model.

3. Controller: Handles user input and interactions. Updates Model based on user actions. Translates user input to Model
updates.

Flow: User interacts with View → Controller updates Model → Model notifies View → View displays updated data

// Model class Student { private String name; private int marks; public Student(String name, int marks) {
[Link] = name; [Link] = marks; } public String getName() { return name; } public int getMarks() { return
marks; } } // View class StudentView { public void displayStudent(String name, int marks) {
[Link]("Name: " + name); [Link]("Marks: " + marks); } } // Controller class
StudentController { private Student model; private StudentView view; public StudentController(Student m,
StudentView v) { [Link] = m; [Link] = v; } public void updateView() {
[Link]([Link](), [Link]()); } }
MODULE - 4: SERVLETS & JSP

Q4.1: Servlet Life Cycle

[Repetitions: 4 times] [Marks: 10]


Question: Explain the life cycle of Servlets with a neat diagram.

Answer:
Servlet Lifecycle describes the process from servlet creation to destruction, managed by Servlet Container.

Phase 1: Initialization (Loading & Instantiation)


• Container loads servlet class
• Creates instance using no-argument constructor
• Calls init(ServletConfig config) method
• Initialization occurs ONCE during servlet lifetime
• Use this phase to load resources (database, cache, etc.)

Phase 2: Service (Handling Requests)


• Container creates new thread for each request
• service() method is invoked
• service() identifies HTTP method and calls appropriate handler
• Handlers: doGet(), doPost(), doPut(), doDelete(), etc.
• This phase REPEATS for every request
• Thread-safe design required for shared resources

Phase 3: Destruction (Cleanup)


• Called when servlet needs to be unloaded
• destroy() method is invoked
• Servlet instance is garbage collected
• Occurs ONCE during lifetime
• Close connections, release resources

Lifecycle Diagram: [HTTP Request] ↓ [Servlet Container loads servlet] ↓ [init() called - ONCE] ↓ [Request 1] →
[service()] → [doGet()/doPost()] → [Response] ↓ [Request 2] → [service()] → [doGet()/doPost()] → [Response]
↓ [Request N] → [service()] → [doGet()/doPost()] → [Response] ↓ [Server shutdown or redeploy] ↓ [destroy()
called - ONCE] ↓ [Servlet unloaded] Code Example: public class MyServlet extends HttpServlet { public void
init(ServletConfig config) throws ServletException { [Link](config); // Initialize resources } protected
void doGet(HttpServletRequest req, HttpServletResponse res) { // Handle GET request } public void destroy() {
// Cleanup resources } }

Key Characteristics: Single instance handles multiple requests (threading required), init() and destroy() called once, service()
called multiple times, persistent objects.

Q4.2: Core Interfaces in [Link] Package

[Repetitions: 3 times] [Marks: 10]


Question: List and explain the core interfaces that are provided in [Link] package.

Answer:
Core Interfaces in [Link] Package:

1. Servlet Interface:
• Main interface for all servlets
• Methods: init(), service(), destroy(), getServletConfig(), getServletInfo()
• Typically extended by GenericServlet or HttpServlet

2. ServletRequest Interface:
• Encapsulates client request information
• Methods: getParameter(), getParameterValues(), getAttribute(), getInputStream()
• Provides access to request data like form parameters, headers

3. ServletResponse Interface:
• Encapsulates response sent to client
• Methods: getOutputStream(), getWriter(), setContentType(), sendError()
• Used to send data back to client

4. ServletConfig Interface:
• Provides servlet configuration information
• Methods: getInitParameter(), getInitParameterNames(), getServletContext()
• Contains init parameters from [Link]

5. ServletContext Interface:
• Represents servlet's environment
• Methods: getAttribute(), setAttribute(), getInitParameter(), getRealPath()
• Shared across all servlets in web application

6. HttpServletRequest Interface:
• Extends ServletRequest for HTTP protocol
• Methods: getMethod(), getHeader(), getCookies(), getSession(), getParameter()
• Provides HTTP-specific information

7. HttpServletResponse Interface:
• Extends ServletResponse for HTTP protocol
• Methods: addCookie(), setHeader(), setStatus(), sendRedirect(), getWriter()
• Handles HTTP-specific responses

Q4.3: JSP Tags & Types

[Repetitions: 3 times] [Marks: 10]


Question: Explain different JSP tags with a program demonstrating all tags.

Answer:
JSP (JavaServer Pages) Tags allow embedding Java code in HTML.

1. Declaration Tag (<%! %>): Declares variables and methods


Scope: Page-wide, persists across requests
Example: <%! int count = 0; %>

2. Scriptlet Tag (<% %>): Contains Java code executed for each request
Scope: Request-specific, variables local
Example: <% String name = [Link]('name'); %>

3. Expression Tag (<%= %>): Evaluates expression and outputs result


No semicolon needed
Example: <%= 2 + 3 %> outputs 5

4. Page Directive (<%@ page %>): Specifies page properties


Example: <%@ page language='java' contentType='text/html' %>

5. Include Directive (<%@ include %>): Includes other JSP files


Example: <%@ include file='[Link]' %>

6. Taglib Directive (<%@ taglib %>): Declares custom tag library


Example: <%@ taglib uri='...' prefix='c' %>

7. Comment Tag (<%-- --%>): Server-side comments


Not sent to client
Example: <%-- This is a comment --%>
Q4.4: Cookie Handling in Servlet

[Repetitions: 3 times] [Marks: 10]


Question: What are cookies? Write a program to create cookie with name 'User_name' and value 'xyz'. Display stored cookie in
webpage.

Answer:
Cookies are small text files stored on client browser. Sent automatically with every HTTP request to server.

Cookie Characteristics:
• Stored on client-side (browser)
• Limited size: 4KB per cookie, ~180 cookies per domain
• Domain and path specific
• Can be persistent or session-based
• User can enable/disable or delete
• Security risks if not encrypted

// Servlet to create and read cookies public class CookieServlet extends HttpServlet { protected void
doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
[Link]("text/html"); PrintWriter out = [Link](); // Create cookie Cookie cookie =
new Cookie("User_name", "xyz"); [Link](24 * 60 * 60); // 24 hours [Link]("/");
[Link](false); [Link](cookie); // Read cookies [Link](""); [Link]("Cookie
Handling"); Cookie[] cookies = [Link](); if(cookies != null) { [Link]("Stored Cookies:");
for(Cookie c : cookies) { [Link]("Name: " + [Link]() + ""); [Link]("Value: " + [Link]() + "");
[Link]("MaxAge: " + [Link]() + ""); } } else { [Link]("No cookies found"); } // Create form to
set new cookie [Link](""); [Link]("Username: "); [Link](""); [Link](""); [Link]("");
} protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{ String user = [Link]("user"); if(user != null && ![Link]()) { Cookie cookie = new
Cookie("User_name", user); [Link](7 * 24 * 60 * 60); // 7 days [Link](cookie); } doGet(req,
res); } } // HTML Form

Deleting Cookie: Set maxAge to 0: [Link](0);

Q4.5: HTTP Requests & Responses

[Repetitions: 2 times] [Marks: 10]


Question: With code, explain how to handle HTTP GET and POST requests.

Answer:
HTTP GET Request: Requests data from server. Parameters visible in URL. Insecure for sensitive data. Limited data size
(~2000 characters).

HTTP POST Request: Submits data to server. Parameters in request body. Secure for sensitive data. No size limit.

public class HttpServlet extends HttpServlet { // Handle GET request protected void doGet(HttpServletRequest
request, HttpServletResponse response) throws ServletException, IOException { // Get form parameters String
name = [Link]("name"); String email = [Link]("email"); // Set response type
[Link]("text/html"); PrintWriter out = [Link](); // Send response
[Link](""); [Link]("GET Request Received"); [Link]("Name: " + name + ""); [Link]("Email: "
+ email + ""); // Get headers String userAgent = [Link]("User-Agent"); String accept =
[Link]("Accept"); [Link]("User-Agent: " + userAgent + ""); [Link](""); } // Handle POST
request protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { String username = [Link]("username"); String password =
[Link]("password"); [Link]("text/html"); PrintWriter out =
[Link](); [Link](""); [Link]("POST Request Received"); // Validate (secure in POST)
if(username != null && password != null) { [Link]("Username: " + username + ""); [Link]("Password
received (hidden)"); [Link]("Login Successful"); } else { [Link]("Invalid credentials"); }
[Link](""); } } // HTML Form Name: Email: Username: Password:
MODULE - 5: JDBC

Q5.1: JDBC Drivers (Types)

[Repetitions: 4 times] [Marks: 10]


Question: Explain the four types of JDBC drivers with advantages and disadvantages.

Answer:
JDBC Drivers are interfaces enabling Java programs to communicate with databases. Four types based on implementation
approach:

Type 1: JDBC-ODBC Bridge Driver


• Converts JDBC calls to ODBC calls via bridge
• Flow: Java → JDBC → ODBC → Database
• Advantages: Simple, works with any ODBC database
• Disadvantages: Performance overhead, not thread-safe, ODBC required on client
• Status: DEPRECATED, not recommended

Type 2: Native-API Driver


• Partially Java, uses native database library
• Flow: Java → JDBC → Native API → Database
• Advantages: Better performance than Type 1, direct DB interaction
• Disadvantages: Native library required on client, platform-dependent
• Usage: Less common, legacy systems

Type 3: Net-Protocol Driver (Middleware)


• Pure Java, communicates with middleware server
• Flow: Java → JDBC → Net Protocol → Middleware → Native API → Database
• Advantages: No native library on client, platform-independent, centralized
• Disadvantages: Extra network hop, middleware required, potential bottleneck
• Usage: Enterprise applications

Type 4: Pure Java Driver (Thin Driver)


• 100% Java implementation, direct database communication
• Flow: Java → JDBC → Database-Specific Protocol → Database
• Advantages: Pure Java, platform-independent, excellent performance, no middleware
• Disadvantages: Database-specific, complex implementation
• Status: RECOMMENDED for modern applications
• Examples: MySQL Connector/J, PostgreSQL JDBC

Type Language Performance Platform Native Code

Type 1 Java+C Low Dependent Yes (ODBC)

Type 2 Java+C Medium Dependent Yes (Native)

Type 3 Pure Java Medium Independent No

Type 4 Pure Java High Independent No

Q5.2: JDBC Process Steps

[Repetitions: 3 times] [Marks: 10]


Question: Explain the different steps involved in JDBC process with code snippets.

Answer:
JDBC process involves 6 sequential steps for database interaction:

Step 1: Load & Register Driver


Dynamically loads driver class into memory
Code: [Link]("[Link]");
Step 2: Establish Connection
Creates connection object using URL, username, password
Code: Connection conn = [Link](url, user, pass);

Step 3: Create Statement


Creates Statement or PreparedStatement object
Code: Statement stmt = [Link]();

Step 4: Execute Query


Executes SQL query and returns result
Code: ResultSet rs = [Link](sql);

Step 5: Process Result


Retrieves data from ResultSet using getter methods
Code: while([Link]()) { getData... }

Step 6: Close Resources


Closes ResultSet, Statement, Connection in reverse order
Code: [Link](); [Link](); [Link]();

import [Link].*; public class JDBCExample { public static void main(String[] args) { Connection conn = null;
PreparedStatement pstmt = null; ResultSet rs = null; try { // Step 1: Load Driver
[Link]("[Link]"); [Link]("Driver loaded"); // Step 2: Create Connection
String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "pass123"; conn =
[Link](url, user, password); [Link]("Connection established"); // Step 3:
Create Statement String sql = "SELECT id, name, marks FROM student WHERE marks > ?"; pstmt =
[Link](sql); [Link](1, 50); // Step 4: Execute Query rs = [Link](); // Step
5: Process Result [Link]("ID Name Marks"); while([Link]()) { int id = [Link]("id"); String
name = [Link]("name"); int marks = [Link]("marks"); [Link](id + " " + name + " " + marks);
} } catch(ClassNotFoundException e) { [Link]("Driver not found: " + e); } catch(SQLException e) {
[Link]("Database error: " + e); } finally { try { // Step 6: Close Resources (reverse order) if(rs
!= null) [Link](); if(pstmt != null) [Link](); if(conn != null) [Link]();
[Link]("Resources closed"); } catch(SQLException e) { [Link](); } } } }

Q5.3: Statement Objects (Callable & Prepared)

[Repetitions: 3 times] [Marks: 10]


Question: What is statement object in JDBC? Explain Callable and PreparedStatement objects.

Answer:
Statement Object is used to execute SQL queries against database. Three types based on functionality:

1. Statement:
• Simple SQL query execution
• Methods: executeQuery(), executeUpdate(), execute()
• Vulnerable to SQL injection
• Best for static queries
• Example: [Link]("SELECT * FROM student");

2. PreparedStatement:
• Pre-compiled SQL queries with placeholders (?)
• More secure (prevents SQL injection)
• Better performance with repeated queries
• Methods: setInt(), setString(), setDouble(), setDate(), etc.
• Example:
String sql = "SELECT * FROM student WHERE id = ?";
PreparedStatement pstmt = [Link](sql);
[Link](1, 5);
ResultSet rs = [Link]();
3. CallableStatement:
• Executes stored procedures and functions
• Can have input and output parameters
• Methods: registerOutParameter(), setInt(), setString(), etc.
• Example:
String sql = "{call addStudent(?, ?, ?)}";
CallableStatement cstmt = [Link](sql);
[Link](1, 100);
[Link](2, "Raj");
[Link](3, 85);
[Link]();

// PreparedStatement Example (RECOMMENDED) String sql = "INSERT INTO student (id, name, marks) VALUES (?, ?,
?)"; PreparedStatement pstmt = [Link](sql); [Link](1, 101); [Link](2, "Priya");
[Link](3, 90); [Link](); // Executes INSERT // CallableStatement Example String sql =
"{call getStudentName(?, ?)}"; CallableStatement cstmt = [Link](sql); [Link](1, 101);
[Link](2, [Link]); [Link](); String name = [Link](2); // Output
parameter

Q5.4: Database Connection & Syntax

[Repetitions: 2 times] [Marks: 10]


Question: Write any two syntax of establishing a connection to database.

Answer:
Syntax 1: Using [Link]()

// Method 1: Using DriverManager try { [Link]("[Link]"); String url =


"jdbc:mysql://localhost:3306/mydb"; String username = "root"; String password = "password123"; Connection conn
= [Link](url, username, password); if(conn != null) { [Link]("Connection
established successfully"); } } catch(ClassNotFoundException e) { [Link]("Driver not found"); }
catch(SQLException e) { [Link]("Connection failed: " + [Link]()); } URL Format:
jdbc:mysql://hostname:port/database Example: jdbc:mysql://localhost:3306/mydb

Syntax 2: Using Connection Pool (HikariCP)

// Method 2: Using Connection Pool (Recommended for production) import [Link]; import
[Link]; HikariConfig config = new HikariConfig();
[Link]("jdbc:mysql://localhost:3306/mydb"); [Link]("root");
[Link]("password123"); [Link](10); HikariDataSource ds = new
HikariDataSource(config); Connection conn = [Link](); // Use connection PreparedStatement pstmt =
[Link]("SELECT * FROM student"); ResultSet rs = [Link](); // Resources auto-close
with try-with-resources try(Connection c = [Link]()) { // Use connection }

Q5.5: Transaction Processing

[Repetitions: 2 times] [Marks: 10]


Question: Explain transaction processing in JDBC.

Answer:
Transaction is a sequence of SQL statements executed as a single unit. Either all succeed (commit) or none execute (rollback).

ACID Properties:
• Atomicity: All operations succeed or none (no partial updates)
• Consistency: Database transitions from valid state to valid state
• Isolation: Concurrent transactions don't interfere
• Durability: Committed changes are permanent

Methods:
• commit(): Permanently saves all changes
• rollback(): Undoes all changes in transaction
• setAutoCommit(false): Disables automatic commits, enables manual control

public class TransactionExample { public static void main(String[] args) { Connection conn = null; try {
[Link]("[Link]"); conn = [Link](
"jdbc:mysql://localhost:3306/bank", "root", "password"); // Start Transaction [Link](false);
[Link]("Transaction started"); Statement stmt = [Link](); // Transfer money: Debit
from Account A int result1 = [Link]( "UPDATE accounts SET balance = balance - 1000 WHERE accno =
101"); [Link]("Debited: " + result1 + " row(s)"); // Check for insufficient funds if(result1 == 0)
{ throw new SQLException("Account A not found"); } // Credit to Account B int result2 = [Link](
"UPDATE accounts SET balance = balance + 1000 WHERE accno = 102"); [Link]("Credited: " + result2 +
" row(s)"); if(result2 == 0) { throw new SQLException("Account B not found"); } // Commit if all successful
[Link](); [Link]("Transaction committed"); } catch(ClassNotFoundException e) {
[Link]("Driver not found"); } catch(SQLException e) { try { // Rollback on error if(conn != null) {
[Link](); [Link]("Transaction rolled back"); } } catch(SQLException ex) {
[Link](); } [Link]("Error: " + [Link]()); } finally { try { if(conn != null) {
[Link](true); // Reset to auto-commit [Link](); } } catch(SQLException e) {
[Link](); } } } } Output: Transaction started Debited: 1 row(s) Credited: 1 row(s) Transaction
committed

Q5.6: Connection Pooling

[Repetitions: 2 times] [Marks: 10]


Question: Explain connection pooling with neat diagram and code snippets.

Answer:
Connection Pooling maintains a pool of pre-established database connections that can be reused, improving application
performance.

Benefits of Connection Pooling:


• Performance: Reuses connections, avoids overhead of creating new ones
• Resource Management: Controls maximum concurrent connections
• Scalability: Efficient handling of multiple requests
• Reduced Latency: No connection creation delay

Connection Pool Diagram:


Application → Pool Manager → Idle Pool [Conn1, Conn2, Conn3, ...]
→ Active Pool [Conn4, Conn5, ...]
→ Max Pool Size, Timeout, Eviction

Popular Implementations:
• HikariCP (fastest, recommended)
• Apache DBCP
• C3P0
• Tomcat JDBC Pool

// HikariCP Example (Recommended) import [Link]; import


[Link]; public class DatabasePool { private static HikariDataSource dataSource;
static { HikariConfig config = new HikariConfig(); [Link]("jdbc:mysql://localhost:3306/mydb");
[Link]("root"); [Link]("password"); [Link](10); // Max 10
connections [Link](5); // Minimum 5 idle [Link](30000); // 30 seconds
[Link](600000); // 10 minutes dataSource = new HikariDataSource(config); } public static
Connection getConnection() { try { return [Link](); } catch(SQLException e) { throw new
RuntimeException(e); } } public static void closePool() { if(dataSource != null) { [Link](); } } } //
Usage try(Connection conn = [Link]()) { // Use connection Statement stmt =
[Link](); ResultSet rs = [Link]("SELECT * FROM student"); while([Link]()) {
[Link]([Link](1)); } } // Connection automatically returned to pool

Q5.7: Database Exceptions


[Repetitions: 2 times] [Marks: 10]
Question: List and explain three kinds of exceptions occurred in JDBC.

Answer:
JDBC Exceptions: Most JDBC methods throw SQLException or its subclasses.

1. SQLException:
• Base exception for database errors
• Thrown when database operation fails
• Contains error code and SQL state
• Methods: getMessage(), getErrorCode(), getSQLState()
• Example: Invalid SQL syntax, connection failure, constraint violation

2. SQLFeatureNotSupportedException:
• Thrown when unsupported feature is used
• Driver doesn't support requested operation
• Example: Some drivers don't support scrollable ResultSet

3. ClassNotFoundException:
• Thrown when JDBC driver class not found
• Driver JAR not in classpath
• Class name spelling error
• Example: [Link]("[Link]") fails

// Exception Handling Example try { // Step 1: Load Driver (ClassNotFoundException)


[Link]("[Link]"); // Step 2: Create Connection (SQLException) Connection conn =
[Link]( "jdbc:mysql://localhost:3306/db", "root", "pass"); // Step 3: Execute Query
(SQLException) Statement stmt = [Link](); ResultSet rs = [Link]("SELECT * FROM
student"); // Process results while([Link]()) { [Link]([Link](1)); } [Link]();
[Link](); [Link](); } catch(ClassNotFoundException e) { [Link]("JDBC Driver not found!");
[Link]("Add MySQL JDBC JAR to classpath"); [Link](); } catch(SQLException e) {
[Link]("Database Error!"); [Link]("Error Code: " + [Link]());
[Link]("SQL State: " + [Link]()); [Link]("Message: " + [Link]()); //
Check specific error if([Link]() == 1045) { [Link]("Authentication failed"); } else
if([Link]() == 1049) { [Link]("Unknown database"); } } catch(Exception e) {
[Link]("Unexpected error!"); [Link](); }
SUMMARY OF MOST REPEATED QUESTIONS

Module Topic Repetitions Importance

Module 1 Collection Framework Methods 4 Critical

Module 2 StringBuffer Methods 4 Critical

Module 3 Swing Features 3 High

Module 4 Servlet Life Cycle 4 Critical

Module 5 JDBC Drivers 4 Critical

Module 2 String Constructors 3 High

Module 4 JSP Tags 3 High

Module 5 JDBC Process 3 High

Study Tips:
1. Focus on topics repeated 4 times (Collection Framework, StringBuffer, Servlet Life Cycle, JDBC Drivers)
2. Understand concepts before memorizing code
3. Practice writing programs for each topic
4. Refer diagrams for visual understanding
5. Use proper error handling in all code
6. Time management: 2 hours per module
7. Solve previous years papers

===== END OF COMPLETE VTU ANSWERS =====

You might also like