a) Explain the purpose of $this variable.
In PHP, $this is a special variable used within a class to refer to the current object. It
allows access to the object’s properties and methods from within the class.
b) Name any two functions to extract basic information about classes in PHP.
1. get_class() – Returns the name of the class of an object.
2. get_class_methods() – Returns an array of class method names
c) What is SOAP?
SOAP (Simple Object Access Protocol) is a protocol used for exchanging structured
information in web services using XML. It allows communication between applications over
HTTP or other protocols.
d) What is Web Services?
Web services are standardized ways of integrating web-based applications using open
standards such as HTTP, XML, SOAP, and WSDL. They allow different applications from
various sources to communicate with each other.
e) List any two PHP HTTP functions.
1. header() – Sends a raw HTTP header to a client.
2. get_headers() – Fetches all the headers sent by the server in response to an HTTP request.
f) What is setcookie() function?
The setcookie() function in PHP is used to send a cookie from the server to the client.
Cookies are small data files stored on the user's browser to store information across multiple
pages.
g) Enlist the PHP DOM functions.
Some PHP DOM functions include:1. DOMDocument::load() – Loads XML from a file.
2. DOMDocument::getElementsByTagName() – Returns a list of elements with a given tag
name.
h) What is XML parser?
An XML parser is a software library or tool that reads and interprets XML data. It breaks down
the XML document into readable elements for programs to manipulate or extract data.
i) Which are the parts of XML-RPC?
XML-RPC consists of:
1. Client – Sends the request.
2. Server – Receives the request and sends back a response.
3. Method Call – The XML-based request that includes method name and parameters.
4. Method Response – The XML-based response containing the result or error.
1
j) Give any two applications of AJAX.1. Auto-suggest in search boxes – Like Google's search
suggestions.
2. Live content updates – Such as updating a news feed or chat without refreshing the page.
(a) What is Thread? How to set the priority of Thread?
A Thread in Java is a lightweight process used to perform multiple tasks simultaneously. You
can create a thread by extending the Thread class or implementing the Runnable interface.
Setting priority:
Thread t = new Thread();
[Link](Thread.MAX_PRIORITY); // or MIN_PRIORITY, NORM_PRIORIT
(b) What is RMI Registry?
RMI Registry is a server-side application that allows clients to look up remote objects (via
names) in Java RMI (Remote Method Invocation). It helps locate remote objects running on
different JVMs.
(c) What is the role of PreparedStatement?
A PreparedStatement in JDBC is used to execute parameterized SQL queries. It helps prevent
SQL injection, improves performance by precompiling the query, and allows reuse.
(d) Explain the types of Servlet.
There are two main types:
1. GenericServlet: A protocol-independent servlet, usually extended for non-HTTP protocols.
2. HttpServlet: A subclass of GenericServlet specifically for handling HTTP requests like GET,
POST, etc.
(e) What is the use of forName() method?
[Link]("className") is used to dynamically load a class at runtime. It's commonly
used in JDBC to load the database driver class.
(f) Write names of JSP Directives.
Three main JSP directives are:
1. <%@ page ... %>
2. <%@ include ... %>
3. <%@ taglib ... %>
(g) What is Cookie?
2
A Cookie is a small piece of data stored on the client side, used to maintain session state and
track user activity across multiple requests.
(h) What is the use of [Link] file?
[Link] (or [Link]) is used in Java JAR files to define metadata like main class
name, version, and classpath. It allows executing the JAR with java -jar.
(1) What is the use of setMaxInactiveInterval() method?
This method sets the timeout (in seconds) for a session in a servlet. After this time of
inactivity, the session is invalidated. Example:
[Link](300); // 5 minutes
(3) What is the use of getLocalHost() method?
[Link]() returns the IP address of the local machine (host). Example:
InetAddress addr = [Link]();
[Link]([Link]());
a) Write down 2 packages of JDBC API.
1. [Link]
2. [Link]
b) What is yield() method?
The yield() method in Java is used to pause the currently executing thread to allow other
threads of the same priority to execute. It’s a hint to the thread scheduler that the current
thread is willing to yield its current use of the CPU.
c) What is JDBC?
JDBC (Java Database Connectivity) is an API that enables Java applications to interact with
databases. It provides methods for querying and updating data in a database.
d) What is scriptlet tag?
Scriptlet tag <% ... %> is used in JSP (JavaServer Pages) to embed Java code within HTML
pages. Example:<% int a = 10; %>
e) What is wait() and notify() in multithreading?
wait(): Causes the current thread to wait until another thread invokes notify() or notifyAll() on
the same object.
notify(): Wakes up a single thread that is waiting on the object's monitor.
f) What is Networking?
Networking in Java refers to the communication between two or more computers over a
network using classes from the [Link] package.
3
g) What is DriverManager class?
DriverManager is a class in JDBC that manages a list of database drivers. It is used to
establish a connection to the database using the getConnection() method.
h) What is ORM?
ORM (Object-Relational Mapping) is a technique that maps Java objects to database tables. It
allows developers to work with data using objects instead of SQL. Example framework:
Hibernate.
i) What is Session?
In Hibernate, a Session is an interface that represents a single unit of work with the database.
It is used to create, read, and delete persistent objects.
j) What is the role of PreparedStatement?
A PreparedStatement is used in JDBC to execute parameterized SQL queries. It helps prevent
SQL injection and improves performance for repeated queries.
Q2) Attempt any of the following
a) What is Introspection? Explain any two introspective functions.
Introspection in PHP refers to the ability of a program to examine the type or properties of an
object at runtime.
Two introspective functions:
1. get_class() – Returns the name of the class of an object.
echo get_class($object);
2. method_exists() – Checks if a method exists in the specified class.
if (method_exists($object, 'methodName')) {
echo "Method exists.";}
b) What is a sticky form? Explain with example.
A sticky form retains the user's input even after form submission (especially when there are
errors).
Example:
<form method="post">
Name: <input type="text" name="name" value="<?php echo $_POST['name'] ?? ' ; ?>">
<input type="submit" value="Submit">
</form>
c) Explain how to create and select database using PHP.
$mysqli = new mysqli("localhost", "username", "password");
4
// Create database
$mysqli->query("CREATE DATABASE myDB");
// Select database
$mysqli->select_db("myDB");
d) Explain AJAX web application model.
AJAX (Asynchronous JavaScript and XML) allows web pages to update asynchronously by
exchanging data with a server behind the scenes.
Flow:
1. User triggers event.
2. JavaScript sends HTTP request to the server.
3. Server processes request and returns data.
4. JavaScript updates part of the web page without reloading.
e) How to handle file upload in PHP?
if ($_FILES["file"]["error"] == 0) {
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
echo "Uploaded!";}
Q3) Attempt any of the following
a) Create an XML file for xyz Bookstore
<?xml version="1.0"?>
<bookstore>
<category name="Technical">
<book title="Learning PHP" author="John Doe"/>
</category>
<category name="General Knowledge">
<book title="World Facts" author="Jane Smith"/>
</category>
<category name="Fitness">
<book title="Yoga for Life" author="Emily Clark"/>
</category>
</bookstore>
b) PHP Script to create CD catalog using XML
5
$xml = simplexml_load_file("[Link]");
foreach($xml->cd as $cd) {
echo "Title: {$cd->title} - Artist: {$cd->artist}<br>";}
b)
c)
d) Sticky Form for Student Registration
<form method="post">
Name: <input type="text" name="name" value="<?php echo $_POST['name'] ?? ' ; ?>"><br>
Age: <input type="text" name="age" value="<?php echo $_POST['age'] ?? ' ; ?>"><br>
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Student Info:<br>Name: {$_POST['name']}<br>Age: {$_POST['age']}";}?>
d) AJAX to select student details from student table
HTML + JS:
<select onchange="getStudent([Link])">
<option value="">Select Student</option>
<option value="1">John</option>
</select>
<div id="result"></div>
<script>
function getStudent(id) {
let xhr = new XMLHttpRequest();
[Link]("GET", "get_student.php?id=" + id, true);
[Link] = function() {
[Link]("result").innerHTML = [Link]; };
[Link]();}</script>
get_student.php:
$con = new mysqli("localhost", "user", "pass", "dbname");
$id = $_GET['id'];
6
$res = $con->query("SELECT * FROM student WHERE sno=$id");
$row = $res->fetch_assoc();
echo "Name: {$row['sname']}<br>Percentage: {$row['per']}";
e) PHP Class with Inheritance
class Employee { private $id, $name, $department, $salary;
function __construct($id, $name, $dept, $sal) { $this->id = $id;
$this->name = $name;
$this->department = $dept;
$this->salary = $sal; } function getTotalSalary() {
return $this->salary; }
function display() {
echo "ID: $this->id, Name: $this->name, Dept: $this->department, Salary: $this
->salary<br>";}}
class Clerk extends Employee {
private $bonus;
function __construct($id, $name, $dept, $sal, $bonus) {
parent::__construct($id, $name, $dept, $sal);
$this->bonus = $bonus; }
function getTotalSalary() {
return parent::getTotalSalary() + $this->bonus; }
function display() {
parent::display();
echo "Bonus: $this->bonus, Total: " . $this->getTotalSalary() . "<br>"; }}$clerk1 = new
Clerk(1, "Amit", "Admin", 30000, 5000);
$clerk1->display();
2(b) RMI Architecture with Suitable Diagram:
RMI (Remote Method Invocation) allows an object to invoke methods on an object running in
another JVM.
Architecture Components:
1. Client – Invokes remote methods.
2. Stub – Client-side proxy for the remote object.
3. Skeleton – Server-side entity that dispatches call to actual object (deprecated in Java 2).
7
4. Remote Reference Layer – Manages references made from clients to remote objects.
5. Transport Layer – Manages actual network connections.
Diagram:
Client JVM Server JVM
----------- -----------
| Client | | Remote |
| ---> Stub ---> RemoteRef ---> | Object |
| | | |
----------- -----------
| |
| Network (TCP/IP) Communication |
---------------------------------------
(d) JDBC Program to Insert Customer Details Using PreparedStatement:
import [Link].*;
import [Link];
public class InsertCustomer {
public static void main(String[] args) { try {
Scanner sc = new Scanner([Link]);
[Link]("Enter CID: ");
int cid = [Link]();
[Link](); // consume newline
[Link]("Enter Name: ");
String cname = [Link]();
[Link]("Enter Address: ");
String address = [Link]();
[Link]("Enter Phone No: ");
String phone = [Link]();
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb",
"root""password");
String query = "INSERT INTO customer (cid, cname, address, ph_no) VALUES (?, ?, ?, ?)";
8
PreparedStatement ps = [Link](query);
[Link](1, cid);
[Link](2, cname);
[Link](3, address);
[Link](4, phone);
int rows = [Link]();
[Link](rows + " record(s) inserted.");
[Link]();
} catch (Exception e) {
[Link](); } }}
(e) Multithreading Java Program Using Runnable to Display Numbers 1 to 100:
import [Link].*;
import [Link].*;
public class NumberThreadGUI extends Frame implements Runnable {
TextField tf;
Button btn;
Thread t;
public NumberThreadGUI() {
tf = new TextField();
[Link](50, 50, 200, 30);
btn = new Button("Start");
[Link](50, 100, 100, 30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
t = new Thread([Link]);
[Link](); } });
add(tf);
add(btn);
setSize(300, 200);
setLayout(null);
9
setVisible(true) }
public void run() {
for (int i = 1; i <= 100; i++) {
[Link]([Link](i));
try { [Link](100);
} catch (InterruptedException e) {} }
public static void main(String[] args) {
new NumberThreadGUI(); }
(a) What is Thread? Explain Thread Life Cycle with Diagram:
Thread: A thread is a lightweight subprocess, a smallest unit of processing in a program.
Thread Life Cycle Stages:
1. New – Thread object is created.
2. Runnable – After start(), ready to run.
3. Running – Thread is executing.
4. Blocked/Waiting – Thread is waiting for a resource or signal.
5. Terminated – Thread has completed execution.
Diagram:
New
|
start()
|
Runnable
|
Running
/\
Blocked Terminated
(b) JSP Tags with Example:
JSP Tags:
1. Directive tag: <%@ %> – Provides global information (e.g., import classes)
<%@ page language="java" contentType="text/html" %>
10
2. Scriptlet tag: <% %> – Contains Java code
<% int a = 5; [Link]("Value: " + a); %>
3. Expression tag: <%= %> – Prints value
<%= new [Link]() %>
4. Declaration tag: <%! %> – Declares variables or methods
<%! int square(int x) { return x*x; } %>
3(c) Servlet Life Cycle with Diagram:
Stages:
1. Loading – Container loads servlet class.
2. Instantiation – Creates instance using no-arg constructor.
3. Initialization – init() method called once.
4. Request Handling – service() called for each request.
5. Destruction – destroy() called once before unloading.
Diagram:
Load --> Instantiate --> init()
| | |
+----> service() <-------+
|
destroy()
3(d) Java Multithreading Program to Execute Threads Sequentially:
class PrintThread {
synchronized void printNumbers(String threadName) {
for (int i = 1; i <= 5; i++) {
[Link](threadName + ": " + i);
try {
[Link](500);
} catch (InterruptedException e) {} } }}
class MyThread extends Thread {
PrintThread pt;
String name;
11
MyThread(PrintThread pt, String name) {
[Link] = pt;
[Link] = name; }
public void run() {
[Link](name); }}
public class SequentialThreads {
public static void main(String[] args) {
PrintThread pt = new PrintThread();
MyThread t1 = new MyThread(pt, "Thread 1");
MyThread t2 = new MyThread(pt, "Thread 2");
[Link]();
try { [Link](); } catch (Exception e) {}
[Link](); }}
3(e) JDBC Program to Update Address and Display Updated Details:
import [Link].*;
import [Link];
public class UpdateCustomer {
public static void main(String[] args) { try {
Scanner sc = new Scanner([Link]);
[Link]("Enter CID: ");
int cid = [Link]();
[Link]();
[Link]("Enter New Address: ");
String address = [Link]();
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb",
"root", "password");
String updateQuery = "UPDATE customer SET address=? WHERE cid=?";
PreparedStatement ps = [Link](updateQuery);
[Link](1, address);
[Link](2, cid);
12
int rows = [Link]();
[Link](rows + " record(s) updated.");
String selectQuery = "SELECT * FROM customer WHERE cid=?";
ps = [Link](selectQuery);
[Link](1, cid);
ResultSet rs = [Link]();
while ([Link]()) {
[Link]("CID: " + [Link]("cid"));
[Link]("Name: " + [Link]("cname"));
[Link]("Address: " + [Link]("address"));
[Link]("Phone: " + [Link]("ph_no")); }
[Link]();
} catch (Exception e) {
[Link](); } }}
a) Life Cycle of Servlet
The life cycle of a servlet is managed by the servlet container (e.g., Tomcat) and involves the
following stages:
1. Loading and Instantiation: The servlet class is loaded into memory by the servlet container
and an instance is created.
2. Initialization (init() method): Called once after instantiation to initialize the servlet. Used to
set up resources.
3. Request Handling (service() method): Called for every request. It determines the request
type (GET, POST, etc.) and calls the appropriate method (doGet(), doPost(), etc.).
4. Destruction (destroy() method): Called once before the servlet is removed from memory.
Used to release resources.
c) Inter Thread Communication in Multithreading
Inter-thread communication is a mechanism that allows synchronized threads to
communicate with each other using methods like:
wait(): Causes the current thread to wait until another thread invokes notify() or notifyAll().
notify(): Wakes up a single thread that is waiting on the object’s monitor.
notifyAll(): Wakes up all threads that are waiting on the object’s monitor.
Use case: Producer-Consumer problem, where one thread (producer) produces data and
13
another (consumer) consumes it. Communication ensures synchronization.
d) JSP Architecture
JSP (Java Server Pages) architecture works in the following way:
1. JSP Page: Written with HTML and JSP tags.
2. JSP Translator: Converts the JSP page into a servlet.
3. Servlet Compilation: The generated servlet is compiled into bytecode.
4. Servlet Execution: The servlet handles the client request, generates a response (usually
HTML), and sends it back to the client.
Phases:
Translation phase
Compilation phase
Execution phase
It follows the Model-View-Controller (MVC) architecture where:
JSP is used for the View
Servlets act as the Controller
Java Beans/POJOs or backend logic represent the Model
e) JDBC Program to Insert Record into Patient Table (Using PreparedStatement)
import [Link].*;
public class InsertPatientRecord {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/hospital"; // DB name: hospital
String user = "root";
String password = "yourpassword";
try {
// Load driver
[Link]("[Link]");
// Connect to DB
Connection conn = [Link](url, user, password);
// Prepare statement
String sql = "INSERT INTO patient (id, name, age, disease) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = [Link](sql);
14
// Set values
[Link](1, 101);
[Link](2, "John Doe");
[Link](3, 35);
[Link](4, "Flu");
// Execute
int rows = [Link]();
[Link](rows + " record inserted.");
// Close connection
[Link]();
[Link]();
} catch (Exception e) {
[Link]() } }}
a) Explain JDBC Drivers with a suitable diagram.
JDBC (Java Database Connectivity) Drivers are used to connect a Java application with a
databaseThere are four types of JDBC drivers:
1. Type 1: JDBC-ODBC Bridge Driver
Converts JDBC calls to ODBC calls.
Requires ODBC driver installed.
Platform-dependent and not recommended.
2. Type 2: Native-API Driver
Converts JDBC calls to database-specific native calls.
Requires native database library.
Faster than Type 1, but still platform-dependent.
3. Type 3: Network Protocol Driver
Uses a middle-tier server to convert JDBC calls to DB-specific protocol.
Platform-independent.
4. Type 4: Thin Driver (Pure Java Driver)
Directly converts JDBC calls to database protocol.
100% Java, platform-independent.
Most commonly used.
15
Diagram:
Java Application
|
v
JDBC API
|
v
JDBC Driver (Type 1/2/3/4)
|
v
Database
b) Write the use of InetAddress class with suitable Example.
InetAddress Class is used to represent an IP address in Java. It can be used to get IP address
and hostname.
Example:
import [Link].*;
public class InetExample {
public static void main(String[] args) throws Exception {
InetAddress address = [Link]("[Link]");
[Link]("Host Name: " + [Link]());
[Link]("IP Address: " + [Link]()); }}
Output:
Host Name: [Link]
IP Address: [Link] (example)
d) Write a JDBC program to delete the records of students whose names are starting with
' m' .
Example JDBC Program:
import [Link].*;
public class DeleteStudents {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root";
16
String password = "yourpassword";
String query = "DELETE FROM students WHERE name LIKE 'm%'";
try {
Connection con = [Link](url, user, password);
Statement stmt = [Link]();
int rowsAffected = [Link](query);
[Link](rowsAffected + " rows deleted.");
[Link]();
} catch (Exception e) {
[Link](); }}
e) Write a JSP program to display all the prime numbers between i to n.
JSP Code:
<%@ page import="[Link].*" %>
<html>
<body>
<%
int i = 10; // Example start
int n = 50; // Example end
[Link]("Prime numbers between " + i + " and " + n + ":<br>");
for (int num = i; num <= n; num++) {
boolean isPrime = true;
if (num <= 1) continue;
for (int j = 2; j <= [Link](num); j++) {
if (num % j == 0) {
isPrime = false;
break; } }
if (isPrime) {
[Link](num + " "); }%>
</body>
</html>
: <body>
17
<form method="post">
Enter a number: <input type="text" name="num">
<input type="submit" value="Calculate"> </form> <%
String numStr = [Link]("num");
if (numStr != null) {
int num = [Link](numStr);
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i; } [Link]("Factorial of " + num + " is: " + fact); %>
</body>
</html>
e) Servlet Program to Display Employee Details in a Table
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class EmployeeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link](); try {
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/dbname", "username", "password");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM employee");
[Link]("<html><body>");
[Link]("<h2>Employee Details</h2>");
[Link]("<table
border='1'><tr><th>Eno</th><th>Ename</th><th>Salary</th><th>Designation</th></tr>")
;
while ([Link]()) {
18
[Link]("<tr><td>" + [Link]("eno") + "</td><td>" +
[Link]("ename") + "</td><td>" +
[Link]("sal") + "</td><td>" +
[Link]("design") + "</td></tr>") }
[Link]("</table></body></html>");
[Link]();
} catch (Exception e) {
[Link]("Error: " + [Link]());
b) Cookies in Java Servlet
Definition: A cookie is a small piece of data stored on the client side and sent back to the
server with every request.
Usage: To store user preferences, session ID, etc.
Creating and Adding a Cookie:
Cookie c = new Cookie("username", "john");
[Link](3600); // 1 hour
[Link](c);
Retrieving Cookies:
Cookie[] cookies = [Link]();
for (Cookie cookie : cookies) {
if ([Link]().equals("username")) {
[Link]("Welcome " + [Link]()) }
c) ResultSet Interface
Definition: The ResultSet interface in JDBC is used to retrieve and manipulate the results of a
SQL query.
Common Methods:
next() – Moves the cursor to the next row.
getString(columnLabel) – Gets the value of a column as a String.
getInt(columnLabel) – Gets the value of a column as an int.
close() – Closes the ResultSet.
Example:
ResultSet rs = [Link]("SELECT * FROM employee");
while ([Link]()) {
19
int id = [Link]("eno");
String name = [Link]("ename");
[Link](id + " " + name);
20