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

603_CA

The document provides a comprehensive overview of various Java concepts including servlets, protocols, sockets, JDBC, and JSP. It explains key components such as the servlet lifecycle, JDBC interfaces, and thread management, along with examples and comparisons of different Java classes and methods. Additionally, it discusses advantages and disadvantages of frameworks like Spring and multithreading, as well as practical code snippets for database operations and web applications.

Uploaded by

Santosh Gobhe
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)
16 views

603_CA

The document provides a comprehensive overview of various Java concepts including servlets, protocols, sockets, JDBC, and JSP. It explains key components such as the servlet lifecycle, JDBC interfaces, and thread management, along with examples and comparisons of different Java classes and methods. Additionally, it discusses advantages and disadvantages of frameworks like Spring and multithreading, as well as practical code snippets for database operations and web applications.

Uploaded by

Santosh Gobhe
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
You are on page 1/ 37

a) What is a servlet?

A servlet is a Java program that runs on a server and handles requests and responses in a web
application. It is part of the Java EE (Jakarta EE) platform and is used to create dynamic web
content. Servlets extend the capabilities of servers and are commonly used to process form
data, manage sessions, and control web page flow.

b) What is a protocol?
A protocol is a set of rules or standards that define how data is transmitted and received over a
network. It ensures proper communication between devices. Examples include HTTP, FTP, and
TCP/IP.

c) What is a socket?
A socket is an endpoint for communication between two machines over a network. It allows
programs to communicate using standard protocols. In Java, the Socket and ServerSocket
classes are used for client-server communication.

d) What is TCP/IP?
TCP/IP (Transmission Control Protocol/Internet Protocol) is a suite of communication protocols
used to interconnect network devices on the internet.

• TCP ensures reliable and ordered delivery of data.

• IP handles addressing and routing the packets.

e) What is the sleep() method?


The sleep() method in Java is used to pause the execution of the current thread for a specified
period of time. It is a static method of the Thread class.
Syntax:

Thread.sleep(milliseconds);

f) List types of ResultSet.


The types of ResultSet in JDBC are:

pg. 1
1. TYPE_FORWARD_ONLY

2. TYPE_SCROLL_INSENSITIVE

3. TYPE_SCROLL_SENSITIVE

g) List any 4 implicit objects of JSP.

1. request – represents the HTTP request

2. response – represents the HTTP response

3. session – represents the session between client and server

4. out – used to send content to the client

h) What is Hibernate?
Hibernate is an open-source Java framework for object-relational mapping (ORM). It simplifies
database interactions by mapping Java classes to database tables. It eliminates the need for
manual SQL queries in most cases.

i) What is a port?
A port is a logical access channel through which data is sent and received between a computer
and a network. Ports are identified by numbers (e.g., HTTP uses port 80, HTTPS uses port 443).

j) What is a session?
A session is a way to store information (state) about a user across multiple requests in a web
application. It helps maintain user data like login status, preferences, etc., while they interact
with the site.

a) List types of ResultSet.

In JDBC, the ResultSet object has three types:

1. TYPE_FORWARD_ONLY – The cursor can only move forward.

2. TYPE_SCROLL_INSENSITIVE – The cursor can move forward and backward, but changes
made to the database after the ResultSet was created are not visible.

pg. 2
3. TYPE_SCROLL_SENSITIVE – The cursor can move in both directions and reflects changes
made to the database while the ResultSet is open.

b) What is IP Address?

An IP Address (Internet Protocol Address) is a unique string of numbers separated by periods


(IPv4) or colons (IPv6) that identifies each device connected to a network using the Internet
Protocol.

c) What is JDBC?

JDBC (Java Database Connectivity) is an API in Java that allows applications to interact with
databases. It provides methods for querying and updating data in a database using SQL
commands.

d) What is servlet?

A Servlet is a Java class used to handle HTTP requests and generate dynamic web content. It
runs on a web server or application server and follows the Java EE (Jakarta EE) specification.

e) What is cookies?

Cookies are small pieces of data stored on the client-side (browser) by the server. They are used
to maintain session state, store user preferences, and track user activity on websites.

f) What is UDP?

UDP (User Datagram Protocol) is a connectionless transport protocol used for sending short
messages called datagrams. It does not guarantee delivery, ordering, or error checking, making
it faster but less reliable than TCP.

g) What is thread?

pg. 3
A Thread is the smallest unit of a process that can be executed independently. In Java, threads
are used to perform multiple tasks concurrently (multithreading), enhancing performance and
responsiveness.

h) What is socket?

A Socket is an endpoint for communication between two machines over a network. In Java,
sockets are used for client-server communication using TCP or UDP protocols.

i) List the directives in JSP.

JSP (JavaServer Pages) supports three main directives:

1. page – Defines page-level instructions (e.g., importing classes).

2. include – Includes a file during the translation phase.

3. taglib – Declares a tag library for custom tags.

j) What is networking?

Networking refers to the practice of connecting computers and other devices to share resources
and information. In computing, it involves hardware, software, and protocols that enable data
communication between devices.

a) What is the use of cookies?

Cookies are used to store information on the client-side to maintain session state between the
client and server. They help in tracking user activity, storing user preferences, and managing
login sessions across multiple pages.

b) What is the use of Runnable interface?

The Runnable interface is used to define a task that can be executed by a thread. It provides a
run() method, which contains the code that runs in the thread. It is commonly used for creating
threads without subclassing the Thread class.

pg. 4
c) Explain thread priority.

Thread priority in Java determines the order in which threads are scheduled for execution. Each
thread is assigned a priority between:

• MIN_PRIORITY (1)

• NORM_PRIORITY (5) (default)

• MAX_PRIORITY (10)
Threads with higher priority are more likely to be executed before lower-priority
threads, although exact behavior depends on the thread scheduler.

d) What is the use of HQL?

HQL (Hibernate Query Language) is an object-oriented query language used in Hibernate. It


allows querying and manipulating data using Java class and property names instead of table and
column names, making it database-independent.

e) What are the directives in JSP?

JSP supports three main directives:

1. page – Defines page-level settings (e.g., imports, error pages).

2. include – Includes static resources at translation time.

3. taglib – Declares and uses custom tag libraries in JSP.

f) What is networking?

Networking refers to connecting computers and devices to share data and resources. In
programming, it involves using protocols and APIs to enable communication between systems
over a network (e.g., using sockets in Java).

g) Write the method for creating connection.

In JDBC, a database connection can be created using:

Connection con = DriverManager.getConnection(url, username, password);

pg. 5
• url – JDBC URL of the database

• username – Database username

• password – Database password

h) What is the yield() method?

The yield() method is a static method of the Thread class that temporarily pauses the currently
executing thread, allowing other threads of the same priority to execute. It does not stop the
thread but gives a chance to others.

i) What is the use of Socket class?

The Socket class in Java is used to create a client-side socket that establishes a connection with a
server socket over TCP. It enables two-way communication between client and server programs.

j) What is servlet?

A Servlet is a Java class that handles HTTP requests and responses in web applications. It runs
on a server and is used to build dynamic web pages by generating content based on client
requests.

Q2

a) Explain in detail directives in JSP.

Directives in JSP provide global information about the JSP page and control how the JSP engine
processes the page. There are three types:

1. Page Directive

o Syntax: <%@ page attribute="value" %>

o Used to define attributes like import packages, session control, error handling,
etc.

o Example:

o <%@ page language="java" import="java.util.*" session="true" %>

pg. 6
2. Include Directive

o Syntax: <%@ include file="relativeURL" %>

o Includes the content of another file during translation phase.

o Example:

o <%@ include file="header.jsp" %>

3. Taglib Directive

o Syntax: <%@ taglib uri="tagLibraryURI" prefix="prefix" %>

o Used to include custom tag libraries like JSTL.

o Example:

o <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

b) Explain inter-thread communication with an example.

Inter-thread communication allows threads to cooperate rather than compete. It is


implemented using:

• wait()

• notify()

• notifyAll()

Example:

class Shared {

synchronized void print(int x) throws InterruptedException {

System.out.println("Waiting...");

wait();

System.out.println("Received: " + x);

synchronized void signal() {

pg. 7
System.out.println("Notifying...");

notify();

public class InterThreadExample {

public static void main(String[] args) {

Shared obj = new Shared();

new Thread(() -> {

try { obj.print(10); } catch (InterruptedException e) {}

}).start();

new Thread(() -> {

try {

Thread.sleep(1000);

obj.signal();

} catch (InterruptedException e) {}

}).start();

c) Difference between Statement and PreparedStatement

Feature Statement PreparedStatement

Query Type Static Dynamic (Parameterized)

pg. 8
Feature Statement PreparedStatement

Compilation Compiled every time Compiled once, reused

Performance Slower for repeated queries Faster due to pre-compilation

SQL
Prone Prevents SQL Injection
Injection

stmt.execute("SELECT * FROM pst = con.prepareStatement("SELECT * FROM emp


Example
emp"); WHERE id=?");

d) Life Cycle of Thread

1. New – Thread object is created.

2. Runnable – start() method is called; ready to run.

3. Running – Scheduler picks the thread to run.

4. Blocked/Waiting – Thread is inactive, waiting for resources or signal.

5. Terminated – Thread finishes execution or is stopped.

Thread t = new Thread(() -> System.out.println("Running"));

t.start(); // Runnable → Running

e) Methods of ServerSocket class

Used for server-side socket communication.

Common Methods:

Method Description

accept() Listens and accepts incoming client requests

close() Closes the server socket

getInetAddress() Returns the local IP address

getLocalPort() Returns the port number the socket is bound to

pg. 9
Syntax Example:

ServerSocket ss = new ServerSocket(5000);

Socket s = ss.accept(); // Waits for client

Q3

a) Difference: execute(), executeQuery(), executeUpdate()

Method Returns Use Case

execute() boolean (true for ResultSet) Used for any SQL statement

executeQuery() ResultSet Used for SELECT queries

executeUpdate() int (rows affected) Used for INSERT, UPDATE, DELETE

b) Architecture of Hibernate

1. Configuration – Reads hibernate.cfg.xml

2. SessionFactory – Creates Sessions

3. Session – Provides methods for CRUD

4. Transaction – For ACID operations

5. Query – For HQL/SQL queries

6. Mapping – Maps Java classes to DB tables using XML or Annotations

c) Methods of Socket class with example

Common Methods:

• getInputStream(), getOutputStream() – For data transfer

• getInetAddress() – Returns remote IP

• close() – Closes socket

Example:

pg. 10
Socket s = new Socket("localhost", 1234);

DataInputStream dis = new DataInputStream(s.getInputStream());

String str = dis.readUTF();

s.close();

d) JSP Program to check voter eligibility

<%@ page language="java" %>

<html>

<body>

<%

String name = request.getParameter("name");

int age = Integer.parseInt(request.getParameter("age"));

%>

<%

if(age >= 18){

%>

<h2>Hello <%= name %>, You are eligible to vote.</h2>

<%

} else {

%>

<h2>Sorry <%= name %>, You are not eligible to vote.</h2>

<%

%>

</body>

</html>

pg. 11
e) JDBC Program to delete employees starting with ‘A’

Connection con = DriverManager.getConnection(url, user, pass);

PreparedStatement ps = con.prepareStatement("DELETE FROM employee WHERE name LIKE


'A%'");

int count = ps.executeUpdate();

System.out.println(count + " records deleted.");

con.close();

Q4

a) Advantages and Disadvantages of Spring

Advantages:

• Loose coupling via Dependency Injection

• Simplifies enterprise development

• Supports multiple modules (Spring MVC, ORM)

• Integration with other frameworks (Hibernate, JPA)

Disadvantages:

• Steep learning curve

• Heavy configuration in XML (older versions)

• Can be complex for small applications

b) JSP Tags with Example

Types of JSP Tags:

1. Scripting Tags: <% %>, <%= %>, <%! %>

2. Directive Tags: <%@ %>

3. Action Tags: <jsp:include>, <jsp:useBean>

pg. 12
Example:

<jsp:useBean id="emp" class="Employee" />

<jsp:setProperty name="emp" property="name" value="John" />

c) Advantages and Disadvantages of Multithreading

Advantages:

• Efficient CPU usage

• Better resource sharing

• Improved app responsiveness

Disadvantages:

• Complex to design and debug

• Risk of deadlock, race conditions

• Context switching overhead

d) Servlet program to accept two numbers and print sum in blue

@WebServlet("/AddServlet")

public class AddServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int a = Integer.parseInt(request.getParameter("num1"));

int b = Integer.parseInt(request.getParameter("num2"));

int sum = a + b;

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<h2 style='color:blue'>Sum: " + sum + "</h2>");

pg. 13
}

e) JDBC Program to display employees in "Computer Application" department

Connection con = DriverManager.getConnection(url, user, pass);

PreparedStatement ps = con.prepareStatement("SELECT eno, ename, department, sal FROM


employee WHERE department = ?");

ps.setString(1, "Computer Application");

ResultSet rs = ps.executeQuery();

while(rs.next()) {

System.out.println("Emp No: " + rs.getInt("eno"));

System.out.println("Name: " + rs.getString("ename"));

System.out.println("Dept: " + rs.getString("department"));

System.out.println("Salary: " + rs.getDouble("sal"));

con.close();

Q2

a) List & explain all the interfaces used in JDBC.

1. Driver – Loads the JDBC driver class. Interfaces connect Java applications to a database.

2. Connection – Establishes a connection with a database.

3. Statement – Used to execute SQL queries (static SQL).

4. PreparedStatement – Used for precompiled SQL statements; provides better


performance and security.

5. CallableStatement – Executes stored procedures in the database.

6. ResultSet – Maintains a cursor to a row of data retrieved by a query.


pg. 14
7. ResultSetMetaData – Retrieves information about the types and properties of columns.

8. DatabaseMetaData – Provides information about the database like its version,


supported features.

9. RowSet – Interface that extends ResultSet and allows JavaBeans style usage.

10. SQLData – Used for mapping SQL user-defined types (UDTs).

b) Differentiate between HTTP servlet and Generic servlet.

Feature GenericServlet HttpServlet

Protocol Independent of protocol Designed for HTTP protocol

Methods Requires overriding service() Overrides doGet(), doPost() etc.

Use case Non-HTTP protocols like FTP Web-based applications

Convenience Less convenient for HTTP Provides useful HTTP-specific methods

c) Explain life cycle of JSP with suitable diagram.

JSP Lifecycle Phases:

1. Translation: JSP is converted into Servlet.

2. Compilation: Translated Servlet is compiled into bytecode.

3. Loading: The servlet class is loaded into memory.

4. Instantiation: Servlet object is created.

5. Initialization (jspInit()): Called once, like init().

6. Request Processing (_jspService()): Called for each request.

7. Destruction (jspDestroy()): Cleanup process.

Diagram:

JSP Page

Translation (JSP → Servlet)


pg. 15

Compilation (.java → .class)

Class Loading

Object Instantiation

Initialization (jspInit())

Request Handling (_jspService())

Destruction (jspDestroy())

d) What is synchronization? Explain.

Synchronization is a mechanism that ensures only one thread can access a resource at a time.
It's essential in multithreading to prevent race conditions.

class Counter {

int count = 0;

public synchronized void increment() {

count++;

• Synchronized Method: Entire method is locked.

• Synchronized Block: Locks only a part of the code.

e) Write a Java program to count number of records in a table.

pg. 16
import java.sql.*;

public class CountRecords {

public static void main(String[] args) {

try {

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",


"root", "password");

Statement stmt = con.createStatement();

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

if(rs.next()) {

System.out.println("Total Records: " + rs.getInt(1));

con.close();

} catch(Exception e) {

e.printStackTrace();

Q3

a) Explain statement interface in detail.

• Used to execute static SQL statements.

• Created via: Statement stmt = con.createStatement();

• Methods:

o execute(): Executes any SQL.

o executeQuery(): Executes SELECT queries, returns ResultSet.

pg. 17
o executeUpdate(): Executes INSERT, UPDATE, DELETE, returns rows affected.

b) Explain Thread priority in detail.

• Each thread has a priority (1 to 10).

• Constants: MIN_PRIORITY (1), NORM_PRIORITY (5), MAX_PRIORITY (10).

• Higher priority threads are scheduled before lower ones.

Thread t1 = new Thread();

t1.setPriority(Thread.MAX_PRIORITY);

c) Differentiate between TCP socket and UDP socket.

Feature TCP Socket UDP Socket

Connection Connection-oriented Connectionless

Reliability Reliable, ensures delivery Not reliable

Speed Slower due to overhead Faster

Use Cases File transfer, emails Streaming, VoIP

d) Java program to print “Hello Java” message 10 times.

public class HelloJava {

public static void main(String[] args) {

for(int i = 1; i <= 10; i++) {

System.out.println("Hello Java");

pg. 18
e) Java program to delete salary column from Emp table.

import java.sql.*;

public class DeleteColumn {

public static void main(String[] args) {

try {

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",


"root", "password");

Statement stmt = con.createStatement();

stmt.executeUpdate("ALTER TABLE Emp DROP COLUMN salary");

System.out.println("Column deleted.");

con.close();

} catch(Exception e) {

e.printStackTrace();

Q4

a) Java program to display IP Address of a Machine.

import java.net.*;

public class IPAddress {

public static void main(String[] args) throws Exception {

InetAddress ip = InetAddress.getLocalHost();

System.out.println("IP Address: " + ip.getHostAddress());

pg. 19
}

b) Explain Architecture of Hibernate.

Hibernate Architecture Layers:

1. Configuration – Reads XML or annotations.

2. SessionFactory – Factory for Session objects.

3. Session – Represents a connection to DB.

4. Transaction – Used for transaction management.

5. Query – Allows HQL or SQL querying.

6. ORM Layer – Maps Java objects to DB tables.

c) Explain life cycle of servlet with suitable diagram.

1. Loading and Instantiation

2. Initialization (init())

3. Request Handling (service() → doGet(), doPost())

4. Destruction (destroy())

Client Request → service() → doGet()/doPost()

↑ ↓

init() destroy()

d) What is multithreading? Explain.

Multithreading is the ability of a CPU to execute multiple threads concurrently. Java uses Thread
class or Runnable interface.

Benefits:

• Better CPU utilization.

pg. 20
• Non-blocking UI.

e) Java servlet to accept name & display on browser using HTML.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class NameServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

String name = request.getParameter("name");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body><h2>Hello, " + name + "!</h2></body></html>");

HTML Form:

<form action="NameServlet" method="post">

Enter your name: <input type="text" name="name">

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

</form>

Great! Let's go through each question one by one with detailed explanations and code
examples where required.

Q2)

a) JSP Life Cycle with Diagram

JSP (JavaServer Pages) goes through several phases during its lifecycle:
pg. 21
1. Translation: The JSP file is translated into a Servlet by the JSP engine.

2. Compilation: The generated Servlet is compiled into a class file.

3. Loading and Instantiation: The class file is loaded into memory and an instance is
created.

4. Initialization: The JSP's jspInit() method is called.

5. Request Processing: For each request, _jspService() is called.

6. Destruction: jspDestroy() is called when the JSP is removed from service.

Diagram:

┌──────────────┐

│ JSP File │

└────┬─────────┘

┌─────────────────────┐

│ Translation Phase │ -> Converts to Servlet

└────────┬────────────┘

┌─────────────────────┐

│ Compilation Phase │ -> Compiles Servlet to .class

└────────┬────────────┘

┌─────────────────────────────┐

│ Loading, Instantiation, │

│ Initialization (jspInit) │

└────────┬────────────────────┘

┌───────────────────────┐

pg. 22
│ Request Handling │ -> _jspService()

└────────┬──────────────┘

┌──────────────────────┐

│ Destruction (jspDestroy) │

└──────────────────────┘

b) List & Explain JDBC Drivers

JDBC drivers are used to connect Java applications with databases. Four types of drivers exist:

1. Type 1: JDBC-ODBC Bridge Driver

o Uses ODBC driver to connect to the database.

o Slow and platform-dependent.

o Example: sun.jdbc.odbc.JdbcOdbcDriver (deprecated)

2. Type 2: Native-API Driver

o Uses native DB libraries.

o Requires native code on the client system.

o Faster than Type 1.

3. Type 3: Network Protocol Driver

o Communicates with middleware server using a DB-independent protocol.

o Middleware translates to DB-specific calls.

4. Type 4: Thin Driver (Pure Java Driver)

o Directly connects to the DB using Java.

o Platform-independent and fastest.

o Most widely used (e.g., MySQL Connector/J).

c) doGet( ) vs doPost( )

pg. 23
Feature doGet() doPost()

Visibility Parameters in URL (visible) Parameters in body (not visible)

Data Size Limited (URL size limit) Unlimited

Use Case Fetch data Send data

Caching Cached by browser Not cached

Bookmarkable Yes No

Security Less secure More secure

d) Java Program: Odd numbers with 2 seconds delay

public class OddPrinter extends Thread {

public void run() {

for (int i = 1; i <= 100; i += 2) {

System.out.println(i);

try {

Thread.sleep(2000); // 2 seconds

} catch (InterruptedException e) {

System.out.println(e);

public static void main(String[] args) {

OddPrinter t1 = new OddPrinter();

t1.start();

pg. 24
}

e) Servlet: Display "Hello Java"

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<h1>Hello Java</h1>");

Configure in web.xml or use annotation:

<servlet>

<servlet-name>HelloServlet</servlet-name>

<servlet-class>HelloServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloServlet</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

pg. 25
Q3)

a) Thread Synchronization with Example

Thread synchronization is the process of controlling access to shared resources by multiple


threads. It ensures that only one thread accesses the critical section at a time.

Why needed?
To avoid data inconsistency when multiple threads modify shared data simultaneously.

Using synchronized keyword:

class Table {

synchronized void printTable(int n) { // synchronized method

for (int i = 1; i <= 5; i++) {

System.out.println(n * i);

try {

Thread.sleep(400);

} catch (Exception e) {}

class MyThread1 extends Thread {

Table t;

MyThread1(Table t) {

this.t = t;

public void run() {

t.printTable(5);

}
pg. 26
class MyThread2 extends Thread {

Table t;

MyThread2(Table t) {

this.t = t;

public void run() {

t.printTable(100);

public class SyncExample {

public static void main(String args[]) {

Table obj = new Table(); // only one object

MyThread1 t1 = new MyThread1(obj);

MyThread2 t2 = new MyThread2(obj);

t1.start();

t2.start();

b) Cookies and Session Tracking with Example

Cookies are small pieces of information stored on the client’s machine by the browser. They
help in session tracking by maintaining state between requests.

Creating and reading cookies:

// Setting a cookie

pg. 27
Cookie c = new Cookie("username", "John");

response.addCookie(c);

// Reading cookies

Cookie[] cookies = request.getCookies();

for (Cookie ck : cookies) {

out.println(ck.getName() + " = " + ck.getValue());

Use in session tracking: Cookies store session ID or user data to identify returning users and
keep the session alive.

c) JSP Directives in Detail

JSP Directives provide global information about the JSP page.

1. Page Directive

Used to define page-level settings.

<%@ page language="java" contentType="text/html" import="java.util.*" %>

Attributes:

• language

• contentType

• import

• errorPage

• isErrorPage

2. Include Directive

Includes a static resource at compile time.

<%@ include file="header.jsp" %>

3. Taglib Directive

pg. 28
Declares tag libraries.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

d) JSP Script to Display Factorial

<%@ page import="java.io.*" %>

<%

int num = 5; // You can get this from request too

int fact = 1;

for (int i = 1; i <= num; i++) {

fact *= i;

%>

<h2>Factorial of <%= num %> is <%= fact %></h2>

e) Java Program: Display Server Date on Client

<%@ page import="java.util.Date" %>

<%

Date date = new Date();

%>

<h2>Server Date & Time: <%= date.toString() %></h2>

Q4)

a) JDBC Statement Interfaces (Statement, PreparedStatement, CallableStatement)

1. Statement

Used for executing simple SQL queries.

Statement stmt = con.createStatement();

pg. 29
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

2. PreparedStatement

Used for precompiled SQL queries (faster, secure).

PreparedStatement ps = con.prepareStatement("INSERT INTO student VALUES(?, ?, ?)");

ps.setInt(1, 101);

ps.setString(2, "Rahul");

ps.setDouble(3, 89.5);

ps.executeUpdate();

3. CallableStatement

Used for calling stored procedures.

CallableStatement cs = con.prepareCall("{call getStudent(?)}");

cs.setInt(1, 101);

cs.execute();

b) 4 Thread Lifecycle Methods

1. start() – Starts the thread.

2. run() – Contains the code executed by the thread.

3. sleep(ms) – Temporarily halts the thread.

4. join() – Waits for a thread to finish before continuing.

c) JDBC Program to Insert Record into Student Table

import java.sql.*;

public class InsertStudent {

public static void main(String[] args) {

try {

pg. 30
Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection(

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

PreparedStatement ps = con.prepareStatement("INSERT INTO student VALUES (?, ?, ?)");

ps.setInt(1, 1);

ps.setString(2, "Amit");

ps.setDouble(3, 92.5);

ps.executeUpdate();

System.out.println("Record inserted.");

con.close();

} catch (Exception e) {

System.out.println(e);

d) Java Program: Print "Hello Java" 500 times using Threads

class HelloThread extends Thread {

public void run() {

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

System.out.println("Hello Java");

pg. 31
public static void main(String[] args) {

HelloThread t = new HelloThread();

t.start();

e) ServerSocket and Socket Explanation

• Socket: Represents a client-side connection.

• ServerSocket: Listens for incoming connections on a port.

Server Code (ServerSocket):

import java.io.*;

import java.net.*;

public class MyServer {

public static void main(String[] args) throws IOException {

ServerSocket ss = new ServerSocket(6666);

Socket s = ss.accept(); // waits for client

DataInputStream dis = new DataInputStream(s.getInputStream());

String str = dis.readUTF();

System.out.println("Message: " + str);

ss.close();

Client Code:

import java.io.*;

import java.net.*;

pg. 32
public class MyClient {

public static void main(String[] args) throws IOException {

Socket s = new Socket("localhost", 6666);

DataOutputStream dout = new DataOutputStream(s.getOutputStream());

dout.writeUTF("Hello Server");

dout.flush();

dout.close();

s.close();

Q5 – Short Notes

a) run() Method

• The run() method in Java is defined in the Runnable interface.

• It contains the code that a thread will execute after it is started.

• It is called automatically when we invoke start() on a thread.

Example:

public class MyThread extends Thread {

public void run() {

System.out.println("Thread is running");

public static void main(String args[]) {

MyThread t1 = new MyThread();

pg. 33
t1.start(); // This calls run() internally

b) Statement Interface (JDBC)

• Used to send static SQL queries to the database.

• Created by Connection object using:


Statement stmt = con.createStatement();

• Suitable when the query does not contain parameters.

Example:

Statement stmt = con.createStatement();

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

c) HttpServlet

• HttpServlet is an abstract class in javax.servlet.http package.

• It is the base class for all servlets that handle HTTP requests.

• It provides methods like doGet(), doPost(), doPut(), doDelete() for handling different
HTTP operations.

Basic structure:

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.getWriter().print("Hello from Servlet");

a) notify(), notifyAll() & wait() Methods

pg. 34
These methods are used for inter-thread communication and are defined in the Object class.

• wait() – Makes the current thread release the monitor and go to waiting state.

• notify() – Wakes up a single thread waiting on the object's monitor.

• notifyAll() – Wakes up all threads waiting on the object's monitor.

Example:

synchronized(obj) {

obj.wait(); // thread waits

obj.notify(); // resumes one waiting thread

obj.notifyAll(); // resumes all

b) Applications of Spring Framework

• Enterprise Applications – Large-scale Java applications using Spring Boot.

• Web Applications – Using Spring MVC for REST APIs and full-stack development.

• Microservices – Spring Boot + Spring Cloud for scalable microservices.

• Security – Secure apps with Spring Security.

• Data Access – Simplified JDBC and ORM with Spring Data JPA.

c) Connection Interface (JDBC)

• Represents a connection (session) with a specific database.

• Provided by the DriverManager.getConnection() method.

• Used to create Statement, PreparedStatement, and CallableStatement.

Common Methods:

• createStatement()

• prepareStatement(String sql)

• setAutoCommit(boolean)

pg. 35
• commit() / rollback()

Example:

Connection con = DriverManager.getConnection(

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

a) Hibernate (ORM Framework)

• Hibernate is a Java-based ORM (Object Relational Mapping) framework.

• It maps Java classes to database tables.

• Eliminates boilerplate JDBC code.

• Supports automatic table creation, caching, and lazy loading.

Advantages:

• Transparent persistence

• HQL (Hibernate Query Language)

• Database independence

b) Connection Interface

(Same as earlier – quick recap)

• Interface in java.sql package.

• Manages the session between Java app and DB.

• Allows transaction handling and statement creation.

c) Thread Priorities

• In Java, each thread has a priority between 1 and 10.

• Defined using constants:

o Thread.MIN_PRIORITY = 1

o Thread.NORM_PRIORITY = 5

pg. 36
o Thread.MAX_PRIORITY = 10

• Priority helps Thread Scheduler decide execution order (not guaranteed).

Example:

Thread t1 = new Thread();

t1.setPriority(Thread.MAX_PRIORITY);

pg. 37

You might also like