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

Java 3

The document provides a comprehensive overview of various Java concepts, including List Interface, JDBC, Servlets, JSP, Spring Framework, and multithreading. It includes definitions, examples, and comparisons of different Java components such as Iterator vs. ListIterator, and JSP vs. Servlet. Additionally, it contains Java programs demonstrating LinkedList usage, employee database interaction, and servlet lifecycle management.

Uploaded by

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

Java 3

The document provides a comprehensive overview of various Java concepts, including List Interface, JDBC, Servlets, JSP, Spring Framework, and multithreading. It includes definitions, examples, and comparisons of different Java components such as Iterator vs. ListIterator, and JSP vs. Servlet. Additionally, it contains Java programs demonstrating LinkedList usage, employee database interaction, and servlet lifecycle management.

Uploaded by

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

Q1) Attempt any EIGHT of the

following .
a) Define List Interface.
The List interface is part of the Java Collection Framework ([Link]) and is used
to store an ordered collection of elements.
It allows:

Duplicate elements

Null values

Index-based access

Examples: ArrayList, LinkedList, Vector.

b) What is JDBC?
JDBC (Java Database Connectivity) is an API in Java used to connect and interact
with databases.

It provides methods to:

Execute SQL queries

Retrieve data

Update database records

Main packages:

[Link]

[Link]

c) How to start a Thread?


A thread is started using the start() method.

Thread t = new Thread();


[Link]();

start() internally calls the run() method and begins execution of the thread.
d) List the types of Servlets.
There are two main types of Servlets:

GenericServlet (Protocol-independent)

HttpServlet (Used for web applications)

e) What is JSP?
JSP (JavaServer Pages) is a server-side technology used to create dynamic web
pages.

It allows embedding Java code within HTML and is converted into a servlet by the
web container.

f) What is Spring Framework?


Spring Framework is an open-source Java framework used for developing
enterprise-level applications.

It provides:

Dependency Injection (DI)

AOP (Aspect-Oriented Programming)

MVC architecture

Transaction management

g) Define Hashtable.
Hashtable is a class in Java that implements the Map interface and stores data in
key–value pairs.

Features:

No null key or null value allowed

Synchronized (thread-safe)
Does not allow duplicate keys

h) What is use of forName()?

[Link]() is used to load the JDBC driver class dynamically at runtime.

Example:

[Link]("[Link]");

i) Write the purpose of join().

join() method is used to pause the execution of the current thread until the
specified thread finishes execution.

Example:

[Link]();

j) How to activate Session in Servlet?

Session is activated using:

HttpSession session = [Link]();

This creates a new session if it does not exist, or returns the existing session.

Q2) Attempt any FOUR of the


following.
a) Differentiate between Iterator and
ListIterator
Feature Iterator ListIterator
Package [Link] [Link]
All
Applicable Only List
Collection
To implementations
classes
Traversal Forward Forward and
Direction only backward
hasNext(), next(),
hasNext(),
hasPrevious(),
Methods next(),
previous(), add(),
remove()
set()
Element
Can remove Can add, remove,
Modificatio
elements and update elements
n
Index No index Provides nextIndex()
Access information and previousIndex()
Starting Starts from Can start from any
Point beginning index

Conclusion

Iterator is used for simple forward traversal.

ListIterator is more powerful and supports bidirectional


traversal and modification.

b) What is ResultSet Interface?


List any two methods.
ResultSet Interface
ResultSet is an interface in JDBC that represents a table of data
returned by executing a SQL SELECT query.
It allows navigating through rows and retrieving column values.

It is obtained using:

ResultSet rs = [Link]("SELECT
* FROM table");

Any Two Methods of ResultSet

next() – Moves the cursor to the next row.

getString() – Retrieves string data from a column.

(Other methods: getInt(), getFloat(), previous(), first())

c) List the Parameters of


doPost() in Servlet
The doPost() method has two parameters:

protected void doPost(HttpServletRequest


request,
HttpServletResponse response)

Parameters:

HttpServletRequest request – Contains client request


data.

HttpServletResponse response – Used to send response


to client.

d) List Any Two Implicit Objects


in JSP
JSP implicit objects are automatically created by the JSP
container.

Any two are:

request – Holds client request information

response – Used to send output to the client

(Other implicit objects: session, application, out, config,


pageContext, exception)

e) State Any Two Methods of


Inter-Thread Communication
Inter-thread communication allows threads to communicate and
coordinate execution.

Any two methods are:

wait() – Causes the current thread to wait.

notify() – Wakes up a waiting thread.

(Another method: notifyAll())

Q3) Attempt any TWO of the


following.
a) Write a Java Program to accept n
characters from user, store them into
Linkedlist, remove duplicate characters &
display in sorted order.
import [Link].*;

public class LinkedListChar {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of characters:


");
int n = [Link]();

LinkedList<Character> list = new


LinkedList<>();

[Link]("Enter characters:");
for (int i = 0; i < n; i++) {
[Link]([Link]().charAt(0));
}

// Remove duplicates using Set


Set<Character> set = new HashSet<>(list);

// Convert back to list


List<Character> result = new
ArrayList<>(set);

// Sort characters
[Link](result);

[Link]("Sorted characters without


duplicates:");
for (char c : result) {
[Link](c + " ");
}
}
}
b) Write a Java Program to accept details of
employee (eno, ename, salary), store it into
database and display it.
CREATE TABLE employee (
eno INT PRIMARY KEY,
ename VARCHAR(50),
salary DOUBLE
);
import [Link].*;
import [Link];

public class EmployeeDB {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter Employee No: ");


int eno = [Link]();

[Link]("Enter Employee Name: ");


String ename = [Link]();

[Link]("Enter Salary: ");


double salary = [Link]();

try {
[Link]("[Link]");
Connection con =
[Link](
"jdbc:mysql://localhost:3306/test", "root",
"password");

PreparedStatement ps =
[Link](
"INSERT INTO employee VALUES
(?, ?, ?)");
[Link](1, eno);
[Link](2, ename);
[Link](3, salary);

[Link]();
[Link]("Record inserted
successfully.");

Statement st = [Link]();
ResultSet rs = [Link]("SELECT *
FROM employee");

[Link]("\nEmployee Details:");
while ([Link]()) {
[Link](
[Link](1) + " " +
[Link](2) + " " +
[Link](3)
);
}

[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
c) Write a JSP program to accept
a number from user and convert
it into words (eg 123 – o/p  One
Two Three).
<html>
<head>
<title>Number to Words</title>
</head>
<body>
<form action="[Link]">
Enter Number:
<input type="text" name="num">
<input type="submit" value="Convert">
</form>
</body>
</html>

<%
String num =
[Link]("num");

String[] words = {
"Zero", "One", "Two", "Three",
"Four",
"Five", "Six", "Seven", "Eight",
"Nine"
};

[Link]("Output: ");
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch)) {
[Link](words[ch - '0'] + " ");
}
}
%>

Q4) Attempt any TWO of the


following.
a) Life Cycle of a Servlet (In
Detail)
A Servlet is a Java program that runs on a web server and handles client requests
(usually HTTP).

The Servlet Life Cycle is managed entirely by the Servlet Container (e.g., Tomcat).

Stages of Servlet Life Cycle


1. Loading and Instantiation

When a servlet is requested for the first time, the servlet container:

Loads the servlet class

Creates only one object (instance) of the servlet

👉 Servlet object is created once, not per request.

2. Initialization – init() method

public void init(ServletConfig config) throws ServletException

Called only once after servlet object creation

Used to:

Initialize database connections

Load configuration parameters

Allocate resources

📌 After init() finishes, servlet is ready to serve requests.

3. Request Processing – service() method

public void service(ServletRequest req, ServletResponse res)

Called for every client request

Responsible for handling request and generating response

Internally calls:
doGet() for GET request

doPost() for POST request

Example:

protected void doGet(HttpServletRequest req,


HttpServletResponse res)

📌 Multithreaded: Multiple clients can access the servlet simultaneously.

4. Destruction – destroy() method

public void destroy()

Called only once before servlet is removed

Used to:

Close database connections

Release resources

Perform cleanup

After this, servlet object becomes eligible for garbage collection.

Servlet Life Cycle Flow


Load Servlet

Create Object

init()

service() → doGet() / doPost()

destroy()

Simple Servlet Example


import [Link].*;
import [Link].*;
import [Link].*;

public class DemoServlet extends HttpServlet {


public void init() {
[Link]("Servlet Initialized");
}

public void doGet(HttpServletRequest req,


HttpServletResponse res)
throws IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("Hello from Servlet");
}

public void destroy() {


[Link]("Servlet Destroyed");
}
}

b) Java Program Using


Multithreading to Blink Text
on Frame
Concept Used

Multithreading

AWT Frame

One thread shows text

Another thread hides text

Program Explanation
A Frame displays text

A separate thread repeatedly:


Shows text

Waits

Hides text

Creates blinking effect

Java Program
import [Link].*;

class BlinkText extends Frame implements


Runnable {
Label lbl;
Thread t;
boolean flag = true;

BlinkText() {
lbl = new Label("WELCOME TO JAVA",
[Link]);
add(lbl);

setSize(400, 200);
setVisible(true);

t = new Thread(this);
[Link]();
}

public void run() {


try {
while (true) {
if (flag)
[Link]("WELCOME TO JAVA");
else
[Link]("");

flag = !flag;
[Link](500);
}
} catch (Exception e) {
[Link](e);
}
}

public static void main(String[] args) {


new BlinkText();
}
}

Output
Text WELCOME TO JAVA blinks continuously on the frame.

c) JDBC Process Explained


with Example
JDBC (Java Database Connectivity) allows Java programs to interact with
databases.

Steps in JDBC Process


1. Import JDBC Packages

import [Link].*;

2. Load and Register Driver

[Link]("[Link]");

📌 Loads MySQL driver into memory.

3. Establish Connection

Connection con = [Link](


"jdbc:mysql://localhost:3306/test", "root", "password");
Creates a connection between Java and database.

4. Create Statement

Statement st = [Link]();

Used to send SQL queries.

5. Execute SQL Query

ResultSet rs = [Link]("SELECT * FROM employee");

executeQuery() → SELECT

executeUpdate() → INSERT, UPDATE, DELETE

6. Process Result

while ([Link]()) {
[Link]([Link](1) + " " +
[Link](2) + " " +
[Link](3));
}

7. Close Connection

[Link]();

Frees database resources.

Complete JDBC Example


import [Link].*;

public class JDBCExample {


public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con =
[Link](
"jdbc:mysql://localhost:3306/test", "root",
"password");

Statement st = [Link]();
ResultSet rs = [Link]("SELECT *
FROM employee");

while ([Link]()) {
[Link](
[Link]("eno") + " " +
[Link]("ename") + " " +
[Link]("salary")
);
}
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

Q5) Attempt any ONE of the


following .
a) Explain Any Three
Applications of Spring
Framework
The Spring Framework is a powerful Java framework used to develop enterprise-
level applications. It provides features like Dependency Injection (DI), Aspect-
Oriented Programming (AOP), transaction management, and web development
support.

Below are three important applications of Spring:


1) Web Application Development (Spring
MVC)
Spring is widely used to develop web applications using Spring MVC (Model-
View-Controller) architecture.

🔹 Features:

Separation of Model, View, and Controller

Easy form handling

RESTful web services support

Integration with JSP, Thymeleaf, etc.

🔹 How It Works:

Controller handles user request.

Model contains business logic.

View displays output.

🔹 Example Use:

Online shopping systems

College management systems

Banking web portals

🔹 Advantages:

Clean architecture

Easy maintenance

Reusable components

2) Enterprise Application Development


Spring is used to build large-scale enterprise applications.
🔹 Features:

Dependency Injection (reduces tight coupling)

Transaction management

Security integration (Spring Security)

Integration with Hibernate, JPA

🔹 Example Use:

Banking systems

ERP software

Insurance systems

🔹 Why Spring is Preferred:

Lightweight

Modular

Easy testing support

3) Microservices Development (Spring


Boot)
Spring Boot is used to create microservices-based applications.

🔹 Features:

Auto-configuration

Embedded Tomcat server

Fast development

REST API development

🔹 Example Use:

E-commerce backend services

Payment gateway services


Cloud-based applications

🔹 Advantages:

Faster deployment

Scalable architecture

Cloud-ready

✅ Conclusion
Spring framework is used for:

Web development

Enterprise applications

Microservices & REST APIs

It provides flexibility, scalability, and easy integration.

b) Differentiate Between JSP


and Servlet (In Detail)
Both JSP (JavaServer Pages) and Servlet are server-side technologies used to
develop web applications in Java.

🔹 Definition
Feature Servlet JSP
Java class that handles HTML page with
Definition
HTTP requests embedded Java code
Extension .java .jsp
Main
Business logic Presentation (UI)
Purpose

🔹 Detailed Comparison
Basis Servlet JSP
Programming
Pure Java code HTML + Java code
Style
Coding More complex for
Easy to design UI
Complexity UI
Compiled to
Execution Converted into Servlet internally
bytecode
Suitable For Controller logic View (presentation layer)
Slightly slower (first time
Performance Slightly faster
compilation)
Difficult for UI
Maintenance Easy to modify UI
changes
Implicit Not available Available (request, response,
Objects directly session, out, etc.)
MVC Role Controller View

🔹 How JSP Works Internally


When a JSP page is requested:

JSP is converted into a Servlet

Servlet is compiled

Servlet executes and generates response

So technically, JSP is a special type of Servlet.

🔹 Example Comparison
Servlet Example

protected void doGet(HttpServletRequest req,


HttpServletResponse res)
throws IOException {
PrintWriter out = [Link]();
[Link]("<h1>Hello World</h1>");
}

Here, HTML is written inside Java → difficult to manage.

JSP Example
<h1>Hello World</h1>

Here, HTML is written directly → easy for UI design.

🔹 Advantages of Servlet
Better for business logic

More control over request handling

Good for processing data

🔹 Advantages of JSP
Easy to design web pages

Good for dynamic content

Less Java code required

🔹 Conclusion
Servlet = Controller (Logic Layer)

JSP = View (Presentation Layer)

In modern applications, both are used together in MVC architecture.

You might also like