Advanced Java Complete VTU Answers
Advanced Java Complete VTU Answers
Prepared: 23-06-2026
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.
Advantages: Reusable components, type-safe (generics), optimized performance, reduced development effort, standardized
API.
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();
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().
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
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.
Advantages of Iterator: Safe removal, works with all collections, memory efficient, no element access required.
MODULE - 2: STRING HANDLING
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
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
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
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)
Answer:
StringBuffer is a mutable, thread-safe class for dynamic string manipulation. Unlike String, it can be modified after creation.
2. insert(int offset, String s): Inserts string at specified INDEX. Shifts existing characters forward.
Syntax: [Link](index, str);
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 vs String: StringBuffer is mutable (changeable), synchronized (thread-safe), slower. Use for frequent
modifications. String is immutable, not thread-safe, faster.
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);
Answer:
Duplicate removal maintains the order of first occurrence while removing repeated characters.
Answer:
Swing is a lightweight GUI toolkit for Java providing pure Java implementation of GUI components built on top of AWT.
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(); } }
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(); } }
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()); } }
Answer:
Why Swing over AWT: Swing provides better functionality, platform independence, richer components, better performance, and
modern features like drag-drop.
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
Answer:
Servlet Lifecycle describes the process from servlet creation to destruction, managed by Servlet Container.
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.
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
Answer:
JSP (JavaServer Pages) Tags allow embedding Java code in HTML.
2. Scriptlet Tag (<% %>): Contains Java code executed for each request
Scope: Request-specific, variables local
Example: <% String name = [Link]('name'); %>
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
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
Answer:
JDBC Drivers are interfaces enabling Java programs to communicate with databases. Four types based on implementation
approach:
Answer:
JDBC process involves 6 sequential steps for database interaction:
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](); } } } }
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
Answer:
Syntax 1: Using [Link]()
// 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 }
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
Answer:
Connection Pooling maintains a pool of pre-established database connections that can be reused, improving application
performance.
Popular Implementations:
• HikariCP (fastest, recommended)
• Apache DBCP
• C3P0
• Tomcat JDBC Pool
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
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