0% found this document useful (0 votes)
9 views

java II

The document provides an overview of various Java concepts including the List Interface, JDBC, threading, Servlets, JSP, and the Spring Framework. It defines key terms, methods, and classes relevant to Java programming, such as ArrayList, Hashtable, and ResultSet, while also explaining concepts like multithreading and inter-thread communication. Additionally, it includes code examples and comparisons between different Java collections and interfaces.

Uploaded by

omkarparande22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

java II

The document provides an overview of various Java concepts including the List Interface, JDBC, threading, Servlets, JSP, and the Spring Framework. It defines key terms, methods, and classes relevant to Java programming, such as ArrayList, Hashtable, and ResultSet, while also explaining concepts like multithreading and inter-thread communication. Additionally, it includes code examples and comparisons between different Java collections and interfaces.

Uploaded by

omkarparande22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Java - II $$

a) Define List Interface.

The List Interface in Java is a part of the Collection Framework and represents an ordered
collection of elements. It allows duplicate elements and provides methods to access elements by
index. Example implementations include ArrayList and LinkedList.

b) What is JDBC?

JDBC (Java Database Connectivity) is an API in Java that helps in connecting and interacting
with databases. It allows Java programs to insert, update, delete, and retrieve data from a
database.

c) How to start a Thread?

A thread in Java can be started using the start() method after creating a thread using Thread class or
Runnable interface.

Example:

Thread t = new Thread(new MyRunnable());


t.start();

This will execute the run() method in a separate thread.

d) List the types of Servlets.

There are two types of Servlets:

1. Generic Servlet – Works with any protocol (not specific to HTTP).


2. HTTP Servlet – Specially designed for handling HTTP requests.

e) What is JSP?

JSP (JavaServer Pages) is a technology used to create dynamic web pages using Java. It allows
embedding Java code inside HTML using special tags like <% %>.

f) What is Spring Framework?

Spring Framework is a Java framework used for developing enterprise applications. It provides
features like dependency injection, MVC architecture, and security.

g) Define Hashtable.

A Hashtable is a Java collection that stores key-value pairs. It is similar to a HashMap, but it is
synchronized (thread-safe).

h) What is the use of forName()?

The Class.forName("classname") method is used to load a class dynamically at runtime. It is


commonly used in JDBC to load the database driver.
i) Write the purpose of join().

The join() method in Java is used to pause the execution of the current thread until another thread
finishes its execution.

j) How to activate a Session in Servlet?

A session in a Servlet can be activated using:

HttpSession session = request.getSession();

This method creates a new session or returns an existing one.

a) Define Map Interface.


A Map interface in Java stores key-value pairs where each key is unique. It helps in fast data
retrieval using keys.

b) What is use of wait()?


The wait() method pauses a thread until another thread calls notify(). It helps in thread
synchronization.

c) What is use of getConnection()?


The getConnection() method in JDBC is used to establish a connection between a Java application
and a database.

d) What is scriplet?
A scriptlet is Java code written inside a JSP page using <% and %>. It allows dynamic content
generation in web pages.

e) What is purpose of JSP directives?


JSP directives (<%@ ... %>) provide instructions to the JSP engine, such as importing packages and
defining page settings.

f) Define Spring Framework.


Spring Framework is a Java framework for building enterprise applications. It provides features like
dependency injection and MVC architecture.

g) Give the name of JDBC API.


JDBC API includes DriverManager, Connection, Statement, PreparedStatement, and ResultSet for
database operations.

h) Define Iterator Interface.


The Iterator interface allows traversing elements of a collection one by one in Java. It provides
methods like hasNext() and next().

i) What is ArrayList?
ArrayList is a dynamic array in Java that can grow or shrink as needed. It is part of the java.util
package.

j) Define Cookie.
A cookie is a small piece of data stored in a web browser. It helps in maintaining user sessions and
preferences.
a) Define Collection.
A Collection in Java is a framework that provides a way to store, manipulate, and process a group of
objects efficiently.

b) Give the name of JDBC API.


JDBC API includes DriverManager, Connection, Statement, PreparedStatement, and ResultSet for
database interactions.

c) What is interthread communication?


Interthread communication allows threads to communicate with each other using methods like
wait(), notify(), and notifyAll().

d) What is Servlet?
A Servlet is a Java program that runs on a web server and handles client requests, usually for web
applications.

e) How to represent an expression in JSP?


In JSP, an expression is represented using <%= expression %>, which evaluates and displays the
result on the webpage.

f) List modules in Spring.


Spring modules include Core, AOP (Aspect-Oriented Programming), JDBC, ORM, Web MVC, and
Security.

g) Which interface is implemented by HashSet class?


The HashSet class implements the Set interface in Java.

h) What is use of getConnection()?


The getConnection() method in JDBC is used to establish a connection between a Java application
and a database.

i) Define Multithreading.
Multithreading is a process where multiple threads run simultaneously to perform different tasks
within a single program.

j) What is a Session?
A session is a way to store user-specific data across multiple requests in a web application, using
mechanisms like HTTP sessions or cookies.

b) Define Thread Priority.


Thread priority determines the order in which threads are scheduled for execution. Higher priority
threads are executed before lower priority ones.

c) What is JDBC?
JDBC (Java Database Connectivity) is an API that allows Java applications to interact with
databases using SQL queries.

d) Define Session.
A session is a mechanism to store user data across multiple requests in a web application, usually
using HTTP sessions or cookies.
e) What is use of request object?
The request object in JSP and Servlets is used to get data sent by the client, such as form inputs and
parameters.

f) Write any one application of Spring.


Spring is used to develop enterprise web applications, such as banking or e-commerce platforms,
using Spring MVC.

g) What is use of join() method?


The join() method in Java makes a thread wait until another thread finishes its execution, ensuring
sequential execution.

h) Define HashTable.
A HashTable in Java is a data structure that stores key-value pairs and synchronizes access for
thread safety.

i) What is use of commit() method?


The commit() method in JDBC saves all changes made to the database in a transaction
permanently.

j) List any two implicit objects in JSP.


Two implicit objects in JSP are request (for handling client data) and response (for sending output
to clients).

a) What is use of CallableStatement?


CallableStatement is used in JDBC to call stored procedures in a database and execute SQL
queries with parameters.

b) What is Thread?
A thread is a lightweight process that runs independently within a program, allowing multitasking.

c) How Servlet is different from CGI?


Servlets are Java-based, platform-independent, and run within a server, whereas CGI (Common
Gateway Interface) creates a new process for each request, making it slower.

d) Define Set.
A Set in Java is a collection that stores unique elements and does not allow duplicates.

e) List any two parameters using Scriptlet.


Two parameters accessed in a scriptlet are request.getParameter("name") and
request.getParameter("email").

f) Define Spring.
Spring is a Java framework for building enterprise applications, providing features like dependency
injection and MVC architecture.

g) Which interface is implemented by TreeSet class?


The TreeSet class implements the NavigableSet and SortedSet interfaces.

h) List any two methods of Statement interface.


Two methods of the Statement interface are executeQuery() (for retrieving data) and
executeUpdate() (for updating data).
i) Write the purpose of yield().
The yield() method in Java pauses the current thread, allowing other threads with equal or higher
priority to execute.

j) What is Cookie?
A cookie is a small piece of data stored in a web browser to track user sessions and preferences.

Q2

Here are the answers with a little more explanation for better understanding:

a) Differentiate between Iterator and ListIterator

Feature Iterator ListIterator


Can traverse in both forward and
Traversal Can traverse only in forward direction
backward directions
Works on all collection classes like Works only on List interface (e.g.,
Applicable for
List, Set, and Map ArrayList, LinkedList)
Adding Cannot add new elements while
Can add elements using add() method
Elements iterating
hasNext(), next(), hasPrevious(),
Methods hasNext(), next(), remove()
previous(), add(), set()

b) What is ResultSet Interface? List any two methods.

ResultSet Interface in JDBC is used to store and retrieve the result of a SQL query execution. It
allows navigating through records in a database table row by row.

Two methods of ResultSet:

next() – Moves the cursor to the next row in the result set. Returns true if a row exists,
otherwise false.

ResultSet rs = stmt.executeQuery("SELECT * FROM students");


while(rs.next()) {
System.out.println(rs.getString("name"));
}
getString(int columnIndex) – Retrieves data from the specified column as a String.

d) List any two implicit objects in JSP.

JSP provides several implicit objects that can be used without explicit declaration.

1. request – Represents the HttpServletRequest object, which contains client request data
(e.g., form inputs, URL parameters).
2. <%= request.getParameter("name") %>
3. session – Represents HttpSession, which stores user session data across multiple requests.
4. <%= session.getAttribute("username") %>
c) List the parameters of doPost() in Servlet.

The doPost() method in a Servlet is used to handle POST requests from clients. It takes two
parameters:

1. HttpServletRequest request – Contains data sent by the client in the request body (e.g., form
data).
2. HttpServletResponse response – Used to send response back to the client.

Example:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {


String name = request.getParameter("username"); // Fetches data from form input
}

e) State any two methods of inter-thread communication.

Java provides inter-thread communication methods to allow threads to coordinate their execution.

wait() – Makes a thread pause execution until another thread notifies it using notify().

synchronized(obj) {
obj.wait(); // Makes the current thread wait
}
notify() – Wakes up a waiting thread that has called wait().
synchronized(obj) {
obj.notify(); // Wakes up a thread waiting on obj
}

These methods help in avoiding race conditions and ensuring proper synchronization between
threads.

a) How to create a thread?


A thread in Java can be created using two methods:

1. Extending the Thread class: Create a class that extends Thread, override the run() method,
and start the thread using start().
2. Implementing the Runnable interface: Implement Runnable, define the run() method, and
pass the instance to a Thread object before calling start().

b) List JDBC drivers.

1. JDBC-ODBC Bridge Driver – Connects Java applications to an ODBC database.


2. Native-API Driver – Uses the database’s native API to connect.
3. Network Protocol Driver – Uses a middleware server to communicate with databases.
4. Thin Driver – Directly interacts with the database using Java networking protocols.
c) Differentiate between Set & List interface.

List Set

1. The List is an indexed sequence. 1. The Set is an non-indexed sequence.

2. List allows duplicate elements 2. Set doesn't allow duplicate elements.

3. Elements by their position can be 3. Position access to elements is not


accessed. allowed.

d) Write any two methods of HttpSession.

1. setAttribute(String name, Object value) – Stores an attribute in the session for future use.
2. getAttribute(String name) – Retrieves the stored attribute from the session.

e) What are the applications of Spring?


Spring is used in various applications such as:

1. Web Applications – Spring MVC is widely used for building web applications.
2. Enterprise Applications – Spring Boot helps in developing scalable enterprise applications.
3. Microservices – Spring Cloud is used for developing distributed microservices.
4. Security – Spring Security is used for authentication and authorization in applications.

b) What is ResultSet interface? List any two fields of it.


The ResultSet interface in JDBC is used to store and manipulate the results of an SQL query. It
provides methods to traverse and retrieve data from a database.

Two fields of ResultSet:

1. TYPE_FORWARD_ONLY – Allows moving forward in the result set.


2. CONCUR_READ_ONLY – Prevents updating the result set.

c) Write a syntax of doGet().

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Code to handle GET request
}
d) What are advantages of JSP over Servlet?

1. Easier to Write – JSP allows embedding Java code in HTML, making it more readable than
Servlets.
2. Less Code Complexity – In Servlets, handling HTML with Java code is complex, while JSP
simplifies this.
3. Automatic Compilation – JSP pages are automatically compiled into Servlets, reducing
manual effort.
4. Built-in Implicit Objects – JSP provides objects like request, response, and session without
needing explicit creation.

e) How to create a thread in multithreading?


A thread can be created in Java using two methods:

1. By Extending Thread Class

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running");
}
}
MyThread t = new MyThread();
t.start();

2. By Implementing Runnable Interface

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running");
}
}
Thread t = new Thread(new MyRunnable());
t.start();

a) Write any two differences between ArrayList and LinkedList.

The key difference between ArrayList and LinkedList is that ArrayList uses an internal array to
store elements, leading to faster random access, while LinkedList uses a doubly linked list
structure, making it more efficient for insertions and deletions in the middle of the list, especially
when compared to ArrayList where such operations often require shifting elements within the
array.

b) Give any two fields of ResultSet Interface.

1. TYPE_SCROLL_INSENSITIVE – Allows scrolling through the result set without being


affected by database changes.
2. CONCUR_UPDATABLE – Allows modifying data in the result set
c) Give any two types of Servlet.

1. Generic Servlet – A protocol-independent servlet that can handle any type of request.
2. HTTP Servlet – A servlet designed specifically to handle HTTP requests like GET and
POST.

d) Differentiate between sleep() and interrupt().

Feature sleep() interrupt()


Function Pauses a thread for a specified time Stops or signals a sleeping/waiting thread
Throws InterruptedException if Does not throw an exception, just sets an
Exception
interrupted interrupt flag

e) Write a syntax of getCookies() method in Servlet.

Cookie[] cookies = request.getCookies();

This retrieves an array of cookies sent by the client in an HTTP request.

a) What is Map interface and how to implement it?


The Map interface in Java is used to store key-value pairs where each key is unique. It does not
allow duplicate keys but allows duplicate values.

Implementation Example:

import java.util.*;
class Example {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
System.out.println(map);
}
}

b) What is DatabaseMetaData?
DatabaseMetaData is an interface in JDBC that provides information about the database, such as
its version, tables, and supported SQL features.

Example:

DatabaseMetaData dbmd = connection.getMetaData();


System.out.println(dbmd.getDatabaseProductName());

c) Give the name of directives in JSP.

1. Page Directive (<%@ page ... %>) – Defines page-specific settings.


2. Include Directive (<%@ include ... %>) – Includes content from another file.
3. Taglib Directive (<%@ taglib ... %>) – Defines custom tag libraries.
d) State the type of Servlet.

1. Generic Servlet – A protocol-independent servlet.


2. HTTP Servlet – A servlet designed for HTTP requests (doGet(), doPost()).

e) What are the thread priorities?


Thread priority values range from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5
(NORM_PRIORITY) as the default.
Higher priority threads get more CPU time compared to lower priority ones.

Example:

thread.setPriority(Thread.MAX_PRIORITY);

Q3
a) Write a Java Program to accept n characters from user, store them into
Linkedlist, remove duplicate characters & display in sorted order.

import java.util.*;

public class UniqueSortedCharacters {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<Character> list = new LinkedList<>();
System.out.print("Enter number of characters: ");
int n = sc.nextInt();
System.out.println("Enter characters: ");
for (int i = 0; i < n; i++) {
list.add(sc.next().charAt(0));
}
TreeSet<Character> uniqueSortedSet = new TreeSet<>(list);
System.out.println("Unique sorted characters: " + uniqueSortedSet);
sc.close();
}
}
b) Write a Java Program to accept details of employee (eno, ename, salary),
store it into database and display it.
import java.sql.*;
import java.util.Scanner;

public class EmployeeDB {


public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in);
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB",
"root", "password");
PreparedStatement stmt = con.prepareStatement("INSERT INTO Employee VALUES (?, ?,
?)")) {

System.out.print("Enter Employee No: ");


stmt.setInt(1, sc.nextInt());
sc.nextLine();
System.out.print("Enter Name: ");
stmt.setString(2, sc.nextLine());
System.out.print("Enter Salary: ");
stmt.setDouble(3, sc.nextDouble());
stmt.executeUpdate();
System.out.println("Employee data inserted!");

} catch (Exception e) {
System.out.println(e);
}} }

a) Write a JDBC program to accept details of Book (B_id, B_name,


B_cost) from user & display it.

import java.sql.*;
import java.util.Scanner;

class BookJDBC {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root",
"password");
Scanner sc = new Scanner(System.in);

System.out.print("Enter Book ID: "); int id = sc.nextInt();


sc.nextLine();
System.out.print("Enter Book Name: "); String name = sc.nextLine();
System.out.print("Enter Book Cost: "); float cost = sc.nextFloat();

PreparedStatement pst = con.prepareStatement("INSERT INTO books VALUES (?, ?, ?)");


pst.setInt(1, id); pst.setString(2, name); pst.setFloat(3, cost); pst.executeUpdate();

ResultSet rs = con.createStatement().executeQuery("SELECT * FROM books");


while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getFloat(3));
sc.close(); con.close(); } }
c) Write a JSP program to accept a number from user and convert it into
words (eg 123 – o/p  One Two Three).
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-
8859-1"%>
<%@ page import="java.util.*" %>
<html>
<head>
<title>Number to Words</title>
</head>
<body>
<form method="post">
Enter Number: <input type="text" name="num">
<input type="submit" value="Convert">
</form>
<%
String num = request.getParameter("num");
if (num != null && !num.isEmpty()) {
String[] words = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine"};
out.print("Number in Words: ");
for (char c : num.toCharArray()) {
out.print(words[Character.getNumericValue(c)] + " ");
}
}
%>
</body>
</html>
b) Write a java program in multithreading to display all the alphabets between
‘A’ to ‘Z’. Each alphabet should display after two seconds.

class AlphabetThread extends Thread {


public void run() {
try {
for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.println(ch);
Thread.sleep(2000);
}
} catch (Exception e) {}
}
public static void main(String[] args) { new AlphabetThread().start(); }
}

c) Write a JSP script to check whether given number is perfect or not &
display the result in yellow colour.
<%@ page language="java" %>
<html>
<body style="background-color:yellow;">
<form method="post">Enter a Number: <input type="text" name="num">
<input type="submit" value="Check"></form>

<%
String numStr = request.getParameter("num");
if (numStr != null) {
int num = Integer.parseInt(numStr), sum = 0;
for (int i = 1; i < num; i++) if (num % i == 0) sum += i;
out.println("<h2>" + num + (sum == num ? " is" : " is NOT") + " a Perfect Number</h2>");
}
%>
</body>
</html>
a) Write a java program to accept N integer from user store them into suitable
collection and display only even integers.

import java.util.*;

class EvenNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();

System.out.print("Enter N: ");
int N = sc.nextInt();

System.out.println("Enter " + N + " numbers:");


for (int i = 0; i < N; i++) numbers.add(sc.nextInt());

System.out.println("Even Numbers:");
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);

sc.close();
}
}

b) Write a Java program to accept details of teacher (Tid, Tname, Tsubject),


store it into database and display it.

import java.sql.*;
import java.util.Scanner;

class TeacherJDBC {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root",
"password");
Scanner sc = new Scanner(System.in);

System.out.print("ID: "); int id = sc.nextInt();


sc.nextLine();
System.out.print("Name: "); String name = sc.nextLine();
System.out.print("Subject: "); String subject = sc.nextLine();

con.prepareStatement("INSERT INTO teacher VALUES (" + id + ", '" + name + "', '" + subject
+ "')").executeUpdate();

ResultSet rs = con.createStatement().executeQuery("SELECT * FROM teacher");


while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));

sc.close(); con.close();
}
}
c) Write a JSP program to accept user name and greets the user according
to time of system.
<%@ page language="java" %>
<html>
<body>
<form method="post">
Name: <input type="text" name="user">
<input type="submit" value="Greet">
</form>
<%
String user = request.getParameter("user");
if (user != null) {
int hour = new java.util.Date().getHours();
String greet = (hour < 12) ? "Good Morning" : (hour < 18) ? "Good Afternoon" : "Good
Evening";
out.println("<h2>" + greet + ", " + user + "!</h2>");
}
%>
</body>
</html>
b) Write a java program in multithreading to display all the numbers between
1 to 10. Each number should display after 2 seconds.

class NumberThread extends Thread {


public void run() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
Thread.sleep(2000);
}
} catch (Exception e) {}
}
public static void main(String[] args) { new NumberThread().start(); }
}
a) Write a jdbc program to accept details of student (RN, Name, percentage)
from user. Display that details.

import java.sql.*;
import java.util.Scanner;

class StudentJDBC {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "password");
Scanner sc = new Scanner(System.in);

System.out.print("Roll No: "); int rn = sc.nextInt();


sc.nextLine();
System.out.print("Name: "); String name = sc.nextLine();
System.out.print("Percentage: "); float perc = sc.nextFloat();

con.createStatement().executeUpdate("INSERT INTO student VALUES (" + rn + ", '" + name


+ "', " + perc + ")");

ResultSet rs = con.createStatement().executeQuery("SELECT * FROM student");


while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getFloat(3));

sc.close(); con.close();
}
}
c) Write a jsp script to check the given number is prime or not. Display the
result in blue color.
<%@ page language="java" %>
<html>
<body style="color:blue;">
<form method="post">Enter a Number: <input type="text" name="num">
<input type="submit" value="Check"></form>
<%
String numStr = request.getParameter("num");
if (numStr != null) {
int num = Integer.parseInt(numStr), i, flag = 0;
for (i = 2; i <= num / 2; i++) if (num % i == 0) { flag = 1; break; }
out.println("<h2>" + num + (flag == 0 && num > 1 ? " is" : " is NOT") + " Prime</h2>");
}
%>
</body> </html>
a) Write a java program to accept 'N' student name from user, store them in
Linked list collection and display in reverse order.

import java.util.*;

class ReverseStudents {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<String> students = new LinkedList<>();
System.out.print("Enter N: ");
for (int i = sc.nextInt(); i-- > 0; sc.nextLine()) students.addFirst(sc.nextLine());
students.forEach(System.out::println);
}
}

b) Write a java program to accept details of student (rollno, name,


percentage). Store it into database & display it.
import java.sql.*;
import java.util.Scanner;

class StudentJDBC {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "password");
Scanner sc = new Scanner(System.in);
System.out.print("Roll No: "); int rn = sc.nextInt();
sc.nextLine();
System.out.print("Name: "); String name = sc.nextLine();
System.out.print("Percentage: "); float perc = sc.nextFloat();
con.createStatement().executeUpdate("INSERT INTO student VALUES (" + rn + ", '" + name
+ "', " + perc + ")");
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM student");
while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getFloat(3));
}
}
c) Write a JSP program to accept username & password, if username &
password is same then display "Login sucessful" message on the browser
other - wise display "Login failed" message.
<%@ page language="java" %>
<form method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" value="Login">
</form>

<% if (request.getParameter("user") != null)


out.println("<h2>" + (request.getParameter("user").equals(request.getParameter("pass")) ?
"Login Successful" : "Login Failed") + "</h2>");
%>

Q4
a) Life Cycle of Servlet

The Servlet Life Cycle consists of five stages managed by the Servlet Container:

1. Loading & Instantiation – The servlet class is loaded, and an instance is created.
2. Initialization (init()) – Called only once when the servlet is first loaded.
3. Request Handling (service()) – Handles client requests (doGet(), doPost()).
4. Destruction (destroy()) – Called before removing the servlet from memory.
5. Garbage Collection – The servlet object is removed when not needed.

Servlet Life Cycle Methods

public class MyServlet extends HttpServlet {


public void init() { System.out.println("Servlet Initialized"); }
public void service(HttpServletRequest req, HttpServletResponse res) {
System.out.println("Request Processed"); }
public void destroy() { System.out.println("Servlet Destroyed"); }
}

Diagram Representation:

Loading → init() → service() (multiple times) → destroy() → Garbage Collection


b) Java Program using Multi-Threading to Blink Text on Frame

This program makes text blink using Threads in a GUI Frame.

import java.awt.*;
import javax.swing.*;

public class BlinkingText extends JFrame implements Runnable {


JLabel label;
boolean visible = true;

public BlinkingText() {
label = new JLabel("Blinking Text", JLabel.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 30));
add(label);
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
new Thread(this).start();
}

public void run() {


try {
while (true) {
visible = !visible;
label.setVisible(visible);
Thread.sleep(500);
}
} catch (InterruptedException e) {}
}

public static void main(String[] args) {


new BlinkingText();
}
}

Explanation:

1. JFrame is used to create a GUI window.


2. A JLabel displays the text.
3. A Thread toggles the label's visibility every 500 milliseconds to create a blinking effect.
c) JDBC Process with an Example

JDBC (Java Database Connectivity) Process:

JDBC allows Java programs to connect to a database and perform operations like inserting,
updating, and retrieving data.

JDBC Steps:

1. Load the Driver – Class.forName("com.mysql.cj.jdbc.Driver");


2. Establish Connection – DriverManager.getConnection()
3. Create Statement – Statement stmt = con.createStatement();
4. Execute Query – stmt.executeQuery("SELECT * FROM Employee");
5. Process Results – Using ResultSet
6. Close Connection – con.close();

JDBC Example Program:

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Employee");

while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getDouble(3));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation:

1. Loads JDBC Driver to connect Java with MySQL.


2. Connects to Database using DriverManager.getConnection().
3. Executes SQL Query using executeQuery().
4. Displays Employee Data from the database.
5. Closes Connection after execution.
a) Write a servlet program to count the number of times a servlet has been
invoked [use cookies].
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class VisitCounterServlet extends HttpServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
int count = 1;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if ("visitCount".equals(c.getName())) {
count = Integer.parseInt(c.getValue()) + 1;
break;
}
}
}
res.addCookie(new Cookie("visitCount", String.valueOf(count)));
res.getWriter().println("Visits: " + count);
}
}

b) Explain life cycle of thread.

1. New: A new thread begins its life cycle in the new state. It remains in this state until the program
starts the thread. It is also referred to as a born thread. The thread is in new state if you create an
instance of Thread class but before the invocation of start() method.
2. Runnable: The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3. Running: The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently not
eligible to run.
5. Terminated: A thread is in terminated or dead state when its run() method exits.
New

start() sleep done, I/O


complete, lock available,
resume, notify
Runnable

Non-Runnable
( Blocked )

Running
sleep, block on I/O, wait
run() method for lock, suspend, wait
exits

Terminated
c) Differentiate between statement & prepared statement interface.
Feature Statement PreparedStatement
SQL Compilation Compiled each time. Precompiled once, reused with parameters.
Performance Slower for repeated queries. Faster for multiple executions.
SQL Injection Safety Vulnerable (string concatenation). Safer (uses parameterized queries).
Syntax No placeholders. Uses ? placeholders for parameters.
Use Case Static SQL queries. Dynamic queries with parameters.

Example:

• Statement:
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM users WHERE id = " + userId);
• PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id =
?");
pstmt.setInt(1, userId);
pstmt.execute();

c) Write a Java program to update the salary of a given employee (use


prepared statement interface). Assume Emp table (Eno, Ename, Esal) is
already created.
import java.sql.*;
import java.util.Scanner;
public class UpdateSalary {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root",
"password");
PreparedStatement ps = con.prepareStatement("UPDATE Emp SET Esal=? WHERE
Eno=?");
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee No: ");
int eno = sc.nextInt();
System.out.print("Enter New Salary: ");
double sal = sc.nextDouble();
ps.setDouble(1, sal);
ps.setInt(2, eno);
int rows = ps.executeUpdate();
System.out.println(rows > 0 ? "Salary Updated" : "Employee Not Found");
con.close();
}}
a) Explain life cycle of JSP.
1. JSP Compilation:
• When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page.
• If the page has never been compiled, or if the JSP has been modified since it was last compiled,
the JSP engine compiles the page.
2. JSP Initialization:
• When a container loads a JSP it invokes the jspInit() method before servicing any requests.
• If we need to perform JSP-specific initialization, override the jspInit() method
3. JSP Execution:
• This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
• Whenever, a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
4. JSP Cleanup:
• The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.
• The jspDestroy() method is the JSP equivalent of the destroy method for servlets.

Initialization jsplnit()

request lifecycle

Request

Main logic _jspService()

Response

jspDestroy()
Shutdown
b) Explain synchronization with an example.
Synchronization in Java is a mechanism that allows only one thread to access a shared resource
at a time. It prevents race conditions and ensures data consistency when multiple threads try to
modify the same resource.

Need for Synchronization:

• If multiple threads access a shared resource (e.g., a bank account, file, or database), data
inconsistency may occur.
• Synchronization ensures that only one thread can execute a critical section at a time

Example -

class Counter {
synchronized void count() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}

public class SyncExample extends Thread {


Counter c;
SyncExample(Counter c) { this.c = c; }
public void run() { c.count(); }

public static void main(String[] args) {


Counter obj = new Counter();
new SyncExample(obj).start();
new SyncExample(obj).start();
}
}
a) Write a Servlet program to get information about the server such as
name, port number and version of server.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServerInfoServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

ServletContext ctx = getServletContext();


out.println("Server Name: " + req.getServerName());
out.println("<br>Port Number: " + req.getServerPort());
out.println("<br>Server Info: " + ctx.getServerInfo());
}
}

b) Methods to Implement Session Tracking:

Session tracking is a technique used to maintain user data across multiple requests in a web
application. Since HTTP is stateless, session tracking helps identify and manage user
interactions.

Cookies – Stores user session data in a small file on the client’s browser.
Hidden Fields – Stores data inside HTML forms, passed with each request.
URL Rewriting – Appends session ID to the URL.
HTTP Session (Best Method) – Uses HttpSession to store session data on the server.

Example Using HTTP Session:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

HttpSession session = req.getSession();


session.setAttribute("username", "John");

out.println("Session Created. User: " + session.getAttribute("username"));


}
}
a) Write a Java program to update the salary of a given employee (use
prepared statement interface). Assume Emp table (Eno, Ename, Esal) is
already created.
import java.sql.*;
import java.util.*;

class UpdateSalary {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",
"username", "password");
PreparedStatement pst = con.prepareStatement("UPDATE Emp SET Esal = ? WHERE
Eno = ?");
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee Number: ");
int eno = sc.nextInt();
System.out.print("Enter New Salary: ");
double sal = sc.nextDouble();
pst.setDouble(1, sal);
pst.setInt(2, eno);
int rows = pst.executeUpdate();
if (rows > 0) System.out.println("Salary updated successfully.");
else System.out.println("Employee not found.");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
c) Write a java program to delete the details of given teacher & display
remaining records from Teacher Table. Assume teacher table (tid, tname,
subject) already created.

import java.sql.*;

public class DeleteTeacher {


public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db",
"root", "password");
PreparedStatement ps = con.prepareStatement("DELETE FROM Teacher WHERE
tid=?");
Statement stmt = con.createStatement();
ResultSet rs;

ps.setInt(1, 101); // Example TID to delete


int rows = ps.executeUpdate();
System.out.println(rows > 0 ? "Teacher Deleted" : "Teacher Not Found");

rs = stmt.executeQuery("SELECT * FROM Teacher");


while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
}

con.close();
}
}

Q5

a) Three Applications of Spring (3 Marks)

Spring Framework is widely used in enterprise applications due to its flexibility and modular
architecture. Here are three key applications:

1. Web Applications – Spring MVC helps develop dynamic web applications with features
like form handling, validation, and security. Example: E-commerce websites.
2. Microservices Development – Spring Boot simplifies building microservices, making
applications lightweight, fast, and scalable. Example: Cloud-based applications.
3. Enterprise Applications – Used in banking, healthcare, and finance for handling large-
scale data and secure transactions. Example: Banking systems for loan processing.
b) Difference Between JSP & Servlet (3 Marks)

Feature JSP (JavaServer Pages) Servlet


A web page with embedded Java A Java class that handles HTTP
Definition
code requests
Compiled into Servlet before
Execution Directly runs on the server
execution
Best for presentation layer (UI Best for processing logic & business
Usage
design) layer
Code Easier to write as it mixes Java & Harder as it requires writing full Java
Complexity HTML code
Performance Slightly slower due to compilation Faster as it runs directly as Java code

Example Use Case:

• JSP: Displaying user interface (Login form, tables).


• Servlet: Processing user input (Login validation, database operations).

a) Explain JDBC Architecture

JDBC (Java Database Connectivity) is an API that allows Java applications to interact with
databases. It has four main components:

1. JDBC Driver – Connects Java applications to databases.


2. Connection – Establishes a link between Java and the database.
3. Statement – Executes SQL queries.
4. ResultSet – Stores and retrieves query results.

JDBC works in two ways:

• Two-tier Architecture – Java application directly connects to the database.


• Three-tier Architecture – Uses an intermediate server between the Java application and the
database.

b) Write a java program to accept ‘n’ numbers from user, store them into LinkedList
collection. Display only odd numbers.
import java.util.*;

class OddNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<Integer> list = new LinkedList<>();
System.out.print("Enter n: ");
int n = sc.nextInt();
System.out.println("Enter numbers:");
while (n-- > 0) list.add(sc.nextInt());
list.stream().filter(x -> x % 2 != 0).forEach(x -> System.out.print(x + " "));
}
}
a) What is Spring Framework? Explain its Advantages.

Spring Framework is a Java-based framework used for building enterprise applications. It provides
support for dependency injection, aspect-oriented programming, and integration with various
technologies like Hibernate and JDBC.

Advantages of Spring Framework:

1. Lightweight – Uses minimal memory and is fast.


2. Modular – Can use only needed modules instead of the entire framework.
3. Dependency Injection (DI) – Reduces tight coupling between components.
4. Transaction Management – Simplifies database transactions.
5. Integration Support – Works with Hibernate, JPA, Struts, etc.

b) Execution Process of Servlet Application

1. Client Request – A web browser sends a request to the server for a servlet.
2. Servlet Container – The server passes the request to the servlet container (like Tomcat).
3. Servlet Loading – The container loads the servlet if it is not already loaded.
4. Servlet Initialization – Calls the init() method once when the servlet is created.
5. Request Handling – The container calls the service() method to process requests.
6. Response Generation – The servlet generates an HTML response and sends it back to the
client.
7. Servlet Destruction – When no longer needed, destroy() is called before removing the
servlet.

b) Write a java program to accept 'n' names from user store them into Array
List, sort them in ascending order and display it.
import java.util.*;

class SortNames {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> names = new ArrayList<>();
System.out.print("Enter n: ");
int n = sc.nextInt();
sc.nextLine();
System.out.println("Enter names:");
for (int i = 0; i < n; i++) names.add(sc.nextLine());
Collections.sort(names);
System.out.println("Sorted names: " + names);
}
}
a) Architecture of Spring

The Spring Framework follows a layered architecture, consisting of multiple modules that provide
various functionalities:

1. Core Container – Manages beans and dependency injection (DI).


2. AOP (Aspect-Oriented Programming) – Handles cross-cutting concerns like logging and
security.
3. Data Access Layer – Provides integration with databases using JDBC, Hibernate, JPA, etc.
4. Web Layer – Supports MVC (Model-View-Controller) architecture for web applications.
5. Security Module – Manages authentication and authorization.
6. Spring Boot – Simplifies application development with built-in configurations.

This layered structure makes Spring flexible and modular.

b) Components of JSP (JavaServer Pages)

JSP consists of the following components:

1. Directives – Provide global settings for the JSP page. Example: <%@ page language="java"
%>.
2. Declarations – Declare variables and methods using <%! ... %>.
3. Scriptlets – Contain Java code inside <% ... %>.
4. Expressions – Output values dynamically using <%= ... %>.
5. Implicit Objects – Predefined objects like request, response, session, etc.
6. Standard Actions – Built-in tags like <jsp:include> and <jsp:forward>.

You might also like