0% found this document useful (0 votes)
6 views25 pages

Java 1

The document covers various topics related to Java programming, including definitions of key concepts like Collection, JDBC, Servlets, and multithreading. It also explains the differences between List and Set interfaces, the life cycle of JSP, and synchronization in Java, along with examples. Additionally, it includes sample Java and JSP programs for practical understanding, as well as an overview of the Spring Framework and its advantages.

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)
6 views25 pages

Java 1

The document covers various topics related to Java programming, including definitions of key concepts like Collection, JDBC, Servlets, and multithreading. It also explains the differences between List and Set interfaces, the life cycle of JSP, and synchronization in Java, along with examples. Additionally, it includes sample Java and JSP programs for practical understanding, as well as an overview of the Spring Framework and its advantages.

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 Collection.
A Collection in Java is a framework that provides architecture to store
and manipulate a group of objects.
It is part of the [Link] package and includes interfaces such as List,
Set, and Queue.

Example: ArrayList, HashSet, LinkedList.

b) Give the name of JDBC API.


JDBC stands for Java Database Connectivity.

It is a Java API used to connect and execute queries with databases.

Main packages of JDBC API:


[Link]

[Link]

c) What is interthread
communication?
Interthread communication is a mechanism in Java that allows multiple
threads to communicate with each other and coordinate their execution.

It is achieved using:
wait()

notify()

notifyAll()

These methods are available in the Object class.


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

It is mainly used to create dynamic web applications.

Servlets are part of the [Link] package.

e) How to represent expression in


JSP?
In JSP (Java Server Pages), an expression is written using:

<%= expression %>

Example:

<%= 5 + 5 %>

This prints the result directly to the browser.

f) List modules in Spring.


Main modules in Spring Framework:

Core Container

Spring AOP

Spring JDBC

Spring ORM

Spring Web

Spring MVC

Spring Security
Spring Boot

g) Which interface is implemented by


HashSet class?
HashSet implements the Set interface.

It is part of the Java Collection Framework and does not allow duplicate
elements.

h) What is use of getConnection()?


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

Example:

Connection con = [Link](url,


username, password);

i) Define multithreading.
Multithreading is a process of executing multiple threads
simultaneously within a single program.

It improves CPU utilization and performance.

j) What is session?
A Session is a mechanism used in web applications to store user-specific
data across multiple requests.

In Java, it is handled using:


HttpSession interface.

It helps maintain user state in web applications.


Q2) Attempt any four of the
following

a) Differentiate between List and Set


Interface
List
Feature Set Interface
Interface
Package [Link] [Link]
Does not
Maintains maintain
Order insertion insertion order
order (except
LinkedHashSet)
Duplicate Allows Does not allow
Elements duplicates duplicates
Elements
can be No index-based
Indexing
accessed access
using index
Allows
Allows only one
Null Values multiple null
null value
values
Common ArrayList, HashSet,
Implementati LinkedList, LinkedHashSet,
ons Vector TreeSet
When order
When unique
and
Use Case elements are
duplicates
required
matter
b) What is ResultSet Interface? List any
two fields of it.
ResultSet Interface

ResultSet is an interface in JDBC used to store and manipulate the data retrieved
from a database after executing a SQL query.

It represents a table of data returned by:

executeQuery()

Any Two Fields (Constants) of ResultSet

TYPE_FORWARD_ONLY – Cursor moves only forward

CONCUR_READ_ONLY – Result set cannot be updated

(Other examples: TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE)

c) Write the Syntax of doGet()


The doGet() method is used in a servlet to handle HTTP GET requests.

Syntax:

protected void
doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException {
// code to handle GET request
}

d) What are the Advantages of JSP over


Servlet?
JSP Servlet
Easy to write Complex and lengthy
JSP Servlet
HTML and Java
Java code only
together
Automatically
Manually compiled
compiled
Better for business
Better for UI design
logic
Implicit objects
No implicit objects
available
Advantages:

Less code compared to servlets

Easy maintenance

Faster development

Separation of presentation and logic

Readable and user-friendly

e) How to Create a Thread in


Multithreading?
There are two ways to create a thread in Java:

1. By Extending Thread Class

class MyThread extends Thread {


public void run() {
[Link]("Thread is running");
}
}

public class Main {


public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
}
}

2. By Implementing Runnable Interface

class MyRunnable implements Runnable {


public void run() {
[Link]("Thread is running");
}
}

public class Main {


public static void main(String[] args) {
Thread t = new Thread(new
MyRunnable());
[Link]();
}
}

Comparison

Thread Class Runnable Interface


Cannot extend another Can extend another
class class
Less flexible More flexible
Less preferred More preferred
Q3) Attempt any two of the
following .
a) Write a java program to accept N integer
from user store them into suitable collection
and display only even integers.
import [Link].*;

public class EvenNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<Integer> list = new ArrayList<>();

[Link]("Enter number of integers


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

[Link]("Enter " + n + " integers:");

for (int i = 0; i < n; i++) {


[Link]([Link]());
}

[Link]("Even numbers are:");

for (Integer num : list) {


if (num % 2 == 0) {
[Link](num);
}
}

[Link]();
}
}

b) Write a Java program to accept


details of teacher (Tid, Tname,
Tsubject), store it into database and
display it.
CREATE TABLE Teacher(
Tid INT PRIMARY KEY,
Tname VARCHAR(50),
Tsubject VARCHAR(50)
);
import [Link].*;
import [Link];

public class TeacherDB {


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

try {
[Link]("[Link]");

Connection con = [Link](


"jdbc:mysql://localhost:3306/college",
"root",
"password"
);

[Link]("Enter Teacher ID: ");


int tid = [Link]();
[Link]();

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


String tname = [Link]();

[Link]("Enter Teacher Subject: ");


String tsubject = [Link]();

PreparedStatement ps = [Link](
"INSERT INTO Teacher VALUES (?, ?, ?)"
);

[Link](1, tid);
[Link](2, tname);
[Link](3, tsubject);

[Link]();
[Link]("Record inserted successfully!");
ResultSet rs =
[Link]().executeQuery("SELECT * FROM
Teacher");

[Link]("\nTeacher Records:");
while ([Link]()) {
[Link](
[Link]("Tid") + " " +
[Link]("Tname") + " " +
[Link]("Tsubject")
);
}

[Link]();
} catch (Exception e) {
[Link](e);
}

[Link]();
}
}

c) Write a JSP program to accept user


name and greets the user according to
time of system.
<html>
<body>
<form action="[Link]" method="post">
Enter Your Name:
<input type="text" name="username"
required>
<input type="submit" value="Submit">
</form>
</body>
</html>

<%@ page import="[Link],


[Link]" %>

<html>
<head>
<title>Greeting Page</title>
</head>
<body>
<%
// Get username from form
String name = [Link]("username");

// Get current system time


Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH");
int hour = [Link]([Link](date));

String greeting;

if (hour >= 0 && hour < 12) {


greeting = "Good Morning";
}
else if (hour >= 12 && hour < 17) {
greeting = "Good Afternoon";
}
else if (hour >= 17 && hour < 20) {
greeting = "Good Evening";
}
else {
greeting = "Good Night";
}
%>

<h2>
<%= greeting %>, <%= name %>!
</h2>

</body>
</html>

Q4) Attempt any two of the


following .
a) Explain Life Cycle of JSP
The JSP (JavaServer Pages) Life Cycle describes the phases through which a JSP
page passes from creation to execution and destruction. A JSP page is ultimately
converted into a Servlet, and its life cycle is managed by the web container (like
Tomcat).
🔹 Phases of JSP Life Cycle

1) Translation Phase

The JSP file (.jsp) is translated into a Servlet (.java file).

Happens only once, when JSP is first requested or modified.

2) Compilation Phase

The generated servlet source code is compiled into a .class file.

If there are syntax errors, compilation fails.

3) Loading and Instantiation

The servlet class is loaded into memory.

An object (instance) of the servlet is created by the container.

4) Initialization – jspInit()

Called once during the JSP life cycle.

Used for initialization tasks like database connection.

public void jspInit() {


// initialization code
}

5) Request Processing – _jspService()

Called every time a client requests the JSP page.

Handles request and generates response.

This method is automatically generated and cannot be overridden.

public void _jspService(HttpServletRequest request,


HttpServletResponse response) {
// request handling code
}

6) Destruction – jspDestroy()

Called once when JSP is removed from memory.

Used to release resources.


public void jspDestroy() {
// cleanup code
}

📌 JSP Life Cycle Order

Translation

Compilation

Loading & Instantiation

jspInit()

_jspService() (multiple times)

jspDestroy()

b) Explain Synchronization with an


Example
What is Synchronization?

Synchronization in Java is a mechanism used to control access to shared resources in


a multithreaded environment. It prevents data inconsistency when multiple threads
try to access or modify the same resource simultaneously.

Without synchronization, race conditions may occur.

Why Synchronization is Needed?

To ensure thread safety

To maintain data consistency

To avoid incorrect results

Types of Synchronization

Method-level synchronization

Block-level synchronization
Static synchronization

Example of Synchronization
❌ Without Synchronization (Problem)

class Counter {
int count = 0;

void increment() {
count++;
}
}
Multiple threads may update count incorrectly.

✅ With Synchronization (Solution)

class Counter {
int count = 0;

synchronized void increment() {


count++;
}
}

Multithreading Test Program

class MyThread extends Thread {


Counter c;

MyThread(Counter c) {
this.c = c;
}

public void run() {


for (int i = 0; i < 1000; i++) {
[Link]();
}
}
}

public class SyncDemo {


public static void main(String[] args) throws
Exception {
Counter c = new Counter();

MyThread t1 = new MyThread(c);


MyThread t2 = new MyThread(c);

[Link]();
[Link]();

[Link]();
[Link]();

[Link]("Final Count: " + [Link]);


}
}

🔎 Explanation

synchronized keyword allows only one thread at a time to execute the


method.

Other threads wait until the lock is released.

Final output is correct and consistent.

✅ Advantages of Synchronization
Prevents data corruption

Ensures thread safety

Controls shared resource access

❌ Disadvantages
Reduces performance (threads wait)

Can cause deadlock if not used carefully

✨ Conclusion
JSP Life Cycle explains how JSP pages are converted and executed as
servlets.

Synchronization ensures safe execution of multiple threads accessing shared


resources.

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 [Link].*;

import [Link];

public class UpdateEmployeeSalary {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

try {

// 1. Load JDBC Driver

[Link]("[Link]");

// 2. Establish Connection

Connection con = [Link](

"jdbc:mysql://localhost:3306/company",

"root",

"password"

);

// 3. Accept input from user

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

int eno = [Link]();

[Link]("Enter New Salary: ");

double esal = [Link]();

// 4. Create PreparedStatement

String sql = "UPDATE Emp SET Esal = ? WHERE Eno = ?";


PreparedStatement ps = [Link](sql);

[Link](1, esal);

[Link](2, eno);

// 5. Execute Update

int rows = [Link]();

if (rows > 0) {

[Link]("Salary updated successfully.");

} else {

[Link]("Employee not found.");

// 6. Close connection

[Link]();

catch (Exception e) {

[Link](e);

[Link]();

}
}

Q5) Attempt any One of the


following .
a) What is Spring Framework?
Explain its Advantages.
Introduction
The Spring Framework is an open-source Java framework used to develop
enterprise-level applications. It provides comprehensive infrastructure support for
developing Java applications easily and efficiently.
Spring was developed by Rod Johnson and is widely used for building web
applications, REST APIs, microservices, and enterprise systems.

Definition
Spring Framework is a lightweight framework that provides:

Dependency Injection (DI)

Aspect-Oriented Programming (AOP)

Transaction management

MVC architecture

Integration with databases and other technologies

Core Features of Spring


Inversion of Control (IoC)

Dependency Injection (DI)

Aspect-Oriented Programming (AOP)

Spring MVC

Transaction Management

Security Support

Architecture / Modules of Spring


Core Container

Data Access / Integration

Web Module

AOP Module

Security Module
Spring Boot

Advantages of Spring Framework


1. Lightweight

Uses POJO (Plain Old Java Object)

Small in size and easy to use

2. Loose Coupling

Uses Dependency Injection

Reduces dependency between classes

3. Easy Integration

Integrates with Hibernate, JDBC, JPA, etc.

4. Transaction Management

Declarative transaction management

Reduces boilerplate code

5. MVC Architecture

Separates business logic and presentation layer

6. Test Friendly

Supports unit testing

Easy to mock objects

7. Security

Spring Security provides authentication and authorization

8. Reduces Boilerplate Code

With Spring Boot, configuration becomes simple


Applications of Spring
Web Applications

RESTful APIs

Enterprise Applications

Banking and E-commerce Systems

Conclusion
Spring Framework simplifies enterprise Java development by providing modular
architecture, loose coupling, and powerful integration features.

b) Explain Execution Process


of Servlet Application
Introduction
A Servlet is a Java program that runs on a web server and handles client requests. The
execution process of a servlet is managed by the Servlet Container (like Apache
Tomcat).

Steps in Servlet Execution Process


1. Client Request

User sends request through browser (HTTP Request).

Example: [Link]

2. Servlet Container Receives Request

The web server forwards request to the servlet container.

Container checks [Link] or annotations for servlet mapping.


3. Loading and Instantiation

If servlet is not loaded:

Container loads servlet class.

Creates an object (instance).

(This happens only once.)

4. Initialization – init() Method

public void init() throws ServletException {


// initialization code
}

Called only once.

Used to initialize resources (DB connection, etc.).

5. Service Method

public void service(ServletRequest req, ServletResponse res)

Called every time a request is made.

It determines whether request is:

doGet()

doPost()

doPut()

doDelete()

6. doGet() / doPost()

Example:

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// process request
}

Handles client request.

Generates response.

7. Sending Response

Servlet sends response back to browser.

Browser displays output.

8. Destruction – destroy() Method

public void destroy() {


// cleanup code
}

Called only once.

Used to release resources.

Servlet Life Cycle Order


Loading

Instantiation

init()

service()

destroy()

Diagrammatic Flow (Text Form)


Client → Web Server → Servlet Container
→ init() → service() → doGet()/doPost() → Response → Client
Conclusion
Spring Framework simplifies enterprise Java development.

Servlet execution process includes loading, initialization, request handling,


and destruction.

Understanding servlet life cycle is important for web application development.

You might also like