0% found this document useful (0 votes)
5 views30 pages

Java 2

The document covers various topics related to Java programming, including JDBC, servlets, JSP, thread management, and the Spring framework. It provides definitions, examples, and explanations of key concepts such as CallableStatement, thread life cycle, session tracking, and the architecture of the Spring framework. Additionally, it includes sample Java programs demonstrating the use of collections, database operations, and JSP for user authentication.

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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views30 pages

Java 2

The document covers various topics related to Java programming, including JDBC, servlets, JSP, thread management, and the Spring framework. It provides definitions, examples, and explanations of key concepts such as CallableStatement, thread life cycle, session tracking, and the architecture of the Spring framework. Additionally, it includes sample Java programs demonstrating the use of collections, database operations, and JSP for user authentication.

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 PDF, TXT or read online on Scribd

Q1) Attempt any EIGHT of the following

a) What is use of CallableStatement?

CallableStatement is used in JDBC to execute stored procedures in a


database.
It allows passing input, output, and input–output parameters.

b) What is thread?
A thread is the smallest unit of execution in a program.
It represents a single flow of control within a process and is used to
achieve multithreading.

c) How servlet is differ from CGI?


Servlet CGI
Runs inside JVM Runs as separate process
Faster performance Slower performance
Uses multithreading No multithreading
Platform independent Platform dependent
Efficient memory usage High memory usage

d) Define Set.
A Set is an interface in Java Collection Framework that does not allow
duplicate elements and stores unique values.

Example: HashSet, TreeSet


e) List any two parameters using scriptlet.
In JSP, parameters can be accessed using:
[Link]()

[Link]()

f) Define Spring.
Spring is an open-source Java framework used to develop enterprise
applications.
It provides features like dependency injection, AOP, and MVC
architecture.

g) Which interface is implemented by TreeSet class?

TreeSet implements the NavigableSet interface


(which extends SortedSet and Set).

h) List any two methods of Statement interface.

Any two methods are:


executeQuery()

executeUpdate()

i) Write the purpose of yield().

yield() method is used to pause the currently executing thread and


allow other threads of the same priority to execute.

j) What is cookie?
A cookie is a small piece of data stored on the client’s browser and is
used to maintain user information between requests.

Q2) Attempt any FOUR of the following

a) What is Map Interface and How


to Implement It?
Definition
The Map interface in Java is a part of the Java Collection Framework ([Link]
package). It is used to store data in the form of key–value pairs.

Each key is unique.

A key maps to exactly one value.

Duplicate keys are not allowed, but duplicate values are allowed.

Important Features of Map


Stores elements as key → value

No duplicate keys

Allows one null key (in HashMap)

Does not extend Collection interface

Common Classes that Implement Map


HashMap

LinkedHashMap

TreeMap

Hashtable
How to Implement Map?
Since Map is an interface, we create an object of its implementation class.

Example Using HashMap

import [Link].*;

public class MapExample {


public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

[Link](101, "Yash");
[Link](102, "Rahul");
[Link](103, "Priya");

for ([Link]<Integer, String> entry : [Link]()) {


[Link]([Link]() + " " +
[Link]());
}
}
}

Important Methods of Map


put(key, value)

get(key)

remove(key)

containsKey(key)

entrySet()

keySet()

values()

Applications
Storing student records
Caching data

Database result mapping

Configuration storage

b) What is Database MetaData?


Definition
DatabaseMetaData is an interface in JDBC that provides information about the
database, such as:

Database name

Database version

Driver name

Supported SQL features

Table information

It is used to get metadata (data about data).

How to Obtain DatabaseMetaData?


Connection con = [Link](url, user, pass);
DatabaseMetaData dbmd = [Link]();

Common Methods
getDatabaseProductName()

getDatabaseProductVersion()

getDriverName()

getTables()

getColumns()
Uses
Checking database capabilities

Getting table structure

Building dynamic applications

c) Give the Name of Directives in


JSP
JSP has three main directives:

page directive

<%@ page %>

include directive

<%@ include file="[Link]" %>

taglib directive

<%@ taglib uri="..." prefix="..." %>

d) State the Types of Servlet


There are two main types of Servlets:

1. Generic Servlet
Extends GenericServlet

Protocol-independent

Uses service() method

2. HTTP Servlet
Extends HttpServlet
Used for web applications

Supports doGet(), doPost(), etc.

e) What are the Thread Priorities?


In Java, thread priorities determine the order of thread execution.

Thread priority values range from:

1 (MIN_PRIORITY)

5 (NORM_PRIORITY) – Default

10 (MAX_PRIORITY)

Constants:

Thread.MIN_PRIORITY // 1
Thread.NORM_PRIORITY // 5
Thread.MAX_PRIORITY // 10

Setting Thread Priority


Thread t = new Thread();
[Link](8);

Purpose
Higher priority threads get more CPU time.

Used in scheduling tasks.

✅ Conclusion
Map interface stores key–value pairs.

DatabaseMetaData provides information about database structure.


JSP has page, include, and taglib directives.

Servlets are Generic and HTTP types.

Thread priorities range from 1 to 10.

Q3) Attempt any TWO of the following .


a) Write a java program to accept 'N' student name
from user, store them in Linked list collection and
display in reverse order.

import [Link].*;

public class StudentLinkedList {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

LinkedList<String> students = new LinkedList<>();

[Link]("Enter number of students (N): ");

int n = [Link]();

[Link](); // consume newline

[Link]("Enter student names:");

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

[Link]([Link]());

}
[Link]("\nStudents in Reverse Order:");

ListIterator<String> itr =
[Link]([Link]());

while ([Link]()) {

[Link]([Link]());

[Link]();

b) Write a java program to accept details of student


(rollno, name, percentage). Store it into database &
display it.

CREATE TABLE Student(

rollno INT PRIMARY KEY,

name VARCHAR(50),

percentage FLOAT

);

import [Link].*;

import [Link];

public class StudentDB {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

try {

// Load Driver

[Link]("[Link]");

// Create Connection

Connection con = [Link](

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

"root",

"password"

);

// Accept input

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

int rollno = [Link]();

[Link]();

[Link]("Enter Name: ");

String name = [Link]();


[Link]("Enter Percentage: ");

float per = [Link]();

// Insert record

PreparedStatement ps = [Link](

"INSERT INTO Student VALUES (?, ?, ?)"

);

[Link](1, rollno);

[Link](2, name);

[Link](3, per);

[Link]();

// Display records

ResultSet rs =
[Link]().executeQuery("SELECT * FROM
Student");

[Link]("\nStudent Records:");

while ([Link]()) {

[Link](

[Link]("rollno") + " " +


[Link]("name") + " " +

[Link]("percentage")

);

[Link]();

catch (Exception e) {

[Link](e);

[Link]();

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.

<html>

<body>

<h2>Login Page</h2>

<form action="[Link]" method="post">


Username: <input type="text" name="uname"
required><br><br>

Password: <input type="password" name="pass"


required><br><br>

<input type="submit" value="Login">

</form>

</body>

</html>

<html>

<body>

<%

String uname = [Link]("uname");

String pass = [Link]("pass");

if (uname != null && pass != null &&


[Link](pass)) {

%>

<h2>Login Successful</h2>

<%

} else {

%>
<h2>Login Failed</h2>

<%

%>

</body>

</html>
Q4) Attempt any TWO of the following

a) Explain Life Cycle of Thread


Introduction
A Thread is the smallest unit of execution in a Java program.
The Thread Life Cycle describes the different states a thread passes through from its
creation to termination.

Java provides the Thread class and defines thread states using the [Link]
enum.

Thread Life Cycle States


A thread goes through the following states:

1 New State

Thread is created but not yet started.

start() method is not called yet.

Thread t = new Thread();

State: NEW

2 Runnable State

When start() method is called.

Thread is ready to run and waiting for CPU scheduling.

[Link]();

State: RUNNABLE
Note:
Runnable includes both:

Ready to run

Running (when CPU executes it)

3 Running State

Thread is actively executing the run() method.

Selected by Thread Scheduler.

4 Blocked / Waiting State

Thread enters this state when:

Waiting for a resource (synchronized block)

Calling wait()

Calling sleep()

Calling join()

Types:

Blocked → Waiting for monitor lock

Waiting → Waiting indefinitely

Timed Waiting → Waiting for specific time

Example:

[Link](1000);

5 Terminated (Dead) State

When run() method finishes execution.

Thread cannot restart again.

State: TERMINATED
Thread Life Cycle Diagram (Text Form)
NEW
↓ start()
RUNNABLE
↓ scheduler
RUNNING
↓ sleep()/wait()/lock
WAITING/BLOCKED
↓ notify()/time over
RUNNABLE
↓ run() completes
TERMINATED

Example Program Demonstrating Thread


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

public class ThreadLifeCycle {


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

Important Methods Related to Thread


start()

run()

sleep()

wait()

notify()

join()
yield()

Conclusion
The thread life cycle consists of:
NEW → RUNNABLE → RUNNING → WAITING/BLOCKED → TERMINATED.

Understanding this helps in designing efficient multithreaded programs.

b) What is Session Tracking? How


to Implement It?
Introduction
HTTP is a stateless protocol, which means the server does not remember previous
client requests.

Session Tracking is a mechanism used to maintain user state across multiple requests
in a web application.

Why Session Tracking is Needed?


Example:

User logs in

Adds items to cart

Moves to payment page

Without session tracking, the server would forget the user after each request.

Methods of Session Tracking in Java


1 Cookies

Small text data stored on client browser.


Example:

Cookie ck = new Cookie("username", "Yash");


[Link](ck);

Retrieve cookie:

Cookie[] c = [Link]();

2 URL Rewriting

Data is appended to URL.

Example:

<a href="[Link]?username=Yash">Click</a>

Retrieve:

[Link]("username");

3 Hidden Form Fields

Data stored in hidden input fields.

<input type="hidden" name="username" value="Yash">

4 HttpSession (Most Common Method)

Server-side session management.

Create session:

HttpSession session = [Link]();

Store data:

[Link]("username", "Yash");

Retrieve data:

String user = (String) [Link]("username");

Invalidate session:
[Link]();

Example Using HttpSession


[Link]

<form action="[Link]" method="post">


Name: <input type="text" name="uname">
<input type="submit">
</form>

[Link]

<%
String name = [Link]("uname");
HttpSession session = [Link]();
[Link]("user", name);
%>

Welcome <%= [Link]("user") %>

Comparison of Session Tracking Methods


Method Stored At Secure Used When
Cookies Client Less secure Small data
URL Rewriting URL Less secure No cookies allowed
Hidden Fields Client Moderate Form-based apps
HttpSession Server More secure Most common

Conclusion
Thread Life Cycle explains states of thread execution.

Session Tracking maintains user state in web applications.

HttpSession is the most secure and commonly used method.


d) 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.
CREATE TABLE Teacher(

tid INT PRIMARY KEY,

tname VARCHAR(50),

subject VARCHAR(50)

);

import [Link].*;

import [Link];

public class DeleteTeacher {

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 to delete: ");

int tid = [Link]();

PreparedStatement ps = [Link](

"DELETE FROM Teacher WHERE tid = ?"

);

[Link](1, tid);

int rows = [Link]();

if (rows > 0) {

[Link]("Teacher record deleted


successfully.");

} else {

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

Statement st = [Link]();

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

[Link]("\nRemaining Teacher Records:");

while ([Link]()) {

[Link](

[Link]("tid") + " " +

[Link]("tname") + " " +

[Link]("subject")

);

[Link]();
}

catch (Exception e) {

[Link](e);

[Link]();

Q5) Attempt any ONE of the following .

a) Explain the Architecture of


Spring Framework
Introduction
The Spring Framework architecture is modular and layered, designed to support
enterprise Java application development.
Each module is independent, but they work together to provide a complete framework.

Spring follows:

Layered architecture

Inversion of Control (IoC)

Dependency Injection (DI)

High-Level Architecture of Spring


Spring architecture is divided into major modules, grouped into logical layers:

Presentation Layer
Web Layer
Service Layer
Data Access Layer
Core Container

1 Core Container (Foundation Layer)


This is the heart of Spring Framework.

Main Modules:

Core

Beans

Context

SpEL (Spring Expression Language)

Responsibilities:

Manages Bean lifecycle

Provides Dependency Injection

Handles Inversion of Control

Key Concepts:
ApplicationContext

BeanFactory

XML / Annotation based configuration

2 Data Access / Integration Layer


Used to interact with databases and persistence frameworks.

Modules:

JDBC

ORM (Hibernate, JPA)

OXM
JMS

Transactions

Features:

Simplifies database access

Reduces boilerplate JDBC code

Supports declarative transaction management

3 Web Layer
Supports development of web applications.

Modules:

Web

Web MVC

WebSocket

Responsibilities:

Request handling

Controller management

View resolution (JSP, Thymeleaf)

Spring MVC follows Model–View–Controller pattern.

4 AOP Layer (Aspect-Oriented Programming)


Purpose:

Separates cross-cutting concerns such as:

Logging

Security
Transactions

Benefits:

Cleaner code

Better modularity

Reduced code duplication

5 Security Layer
Provided by Spring Security.

Features:

Authentication

Authorization

Role-based access control

Protection against CSRF, XSS

6 Test Layer
Supports testing Spring applications.

Features:

Integration with JUnit & TestNG

Mock objects

Context testing

Advantages of Spring Architecture


Modular and lightweight

Easy integration with other frameworks


Loose coupling

Scalable and maintainable

Suitable for enterprise applications

Conclusion (Spring Architecture)


Spring architecture is layered, flexible, and modular, making it ideal for building
scalable and maintainable Java enterprise applications.

b) Explain the Components of JSP


(JavaServer Pages)
Introduction
JSP (JavaServer Pages) is a server-side technology used to create dynamic web
pages.
A JSP page consists of HTML + Java elements, which are translated into servlets by
the web container.

Major Components of JSP

1 JSP Directives
Directives provide instructions to the JSP container.

Types of Directives:

a) Page Directive

Defines page-level settings.

<%@ page import="[Link].*" %>

b) Include Directive
Includes another JSP file at translation time.

<%@ include file="[Link]" %>

c) Taglib Directive

Used to include custom tags or JSTL.

<%@ taglib uri="..." prefix="c" %>

2 JSP Scripting Elements


Used to embed Java code.

a) Scriptlet

Used to write Java statements.

<% int a = 10; %>

b) Expression

Used to display output.

<%= a %>

c) Declaration

Used to declare variables or methods.

<%! int count = 0; %>

3 JSP Implicit Objects


Automatically available objects created by JSP container.

Implicit Object Purpose


request Client request data
response Response to client
session Session management
application Application-wide data
out Output stream
config Servlet configuration
Implicit Object Purpose
pageContext Page-specific data
exception Error handling

4 JSP Actions
Standard tags used to control behavior at runtime.

Examples:

<jsp:include page="[Link]" />


<jsp:forward page="[Link]" />
<jsp:useBean id="obj" class="Student" />

5 JSP Expression Language (EL)


Used to access data easily without Java code.

${[Link]}

Benefits:

Simpler syntax

Less Java code

Improved readability

6 JSTL (JSP Standard Tag Library)


Provides predefined tags for:

Looping

Conditions

Formatting

Example:
<c:forEach var="i" begin="1" end="5">
${i}
</c:forEach>

Advantages of JSP Components


Easy page development

Separation of logic and presentation

Less Java code

Faster development

Conclusion (JSP Components)


JSP consists of directives, scripting elements, implicit objects, actions, EL, and
JSTL, which together simplify dynamic web page creation.

You might also like