Java Question Paper
Java Question Paper
The <canvas> tag in HTML is used to draw graphics on a web page using JavaScript. It can
be used to draw paths, boxes, texts, gradients, and adding images. By default, it does not
contain borders and text.
Syntax:<canvas id = "script"> Contents... </canvas>
JavaScript uses an if–else condition to check time and print “Good Day” if–else condition:
HTML
<script>
let hour = new Date().getHours();
GET is used to retrieve data and sends it in the URL, while POST is used to send data
securely in the request body.
Web Container (also called Servlet Container) is a part of a web server that manages and runs
Java Servlets in Java [Link] and executes servlets Handles client requests and
responses Manages servlet life cycle
JSP Scripting Tags In JavaServer Pages, there are three main scripting tags: Scriptlet Tag JSP
Used to write Java code inside JSP Expression Tag JSP <%= expression %>
Used to display output on the web page Declaration Tag JSP<%! declaration %>
JavaBeans in Java are reusable software components (classes) that follow certain rules to
make them easy to use in applications .Features
Must have a no-argument constructor
Properties are accessed using getters and setters Should be serializable
Database Management System (DBMS) is software used to store, manage, and retrieve data
efficiently in a database.
12. Define the term Sockets.
Socket is an endpoint of communication between two computers over a network, used to send
and receive data.
PART B — (5 × 5 = 25 marks)
Answer any FIVE questions.
Distributed System
A distributed system is a collection of independent computers that work together to achieve a
common goal. These systems communicate and share resources as a single system.
Examples include social media systems, banking systems, and cloud platforms.
Autoplay Designates that the audio file will play immediately after it loads controls.
HTML Video
The <video> element in HTML is used to show video content on web pages. It supports
various video formats, including MP4, WebM, and Ogg. It is introduced in HTML5.
Scroll down to the End, there is a Tutorial Video which is a live example of the Video
Element displaying on this webpage.
Syntax:
<video src="" controls> </video>
or
<video controls="controls">
<source src="video_filename" type="video_type">
</video>
Generally, we prefer the syntax with the <source> tag wrapped between the video tag
because:
It allows you to specify multiple <source> elements for different formats of the video
(e.g., MP4, WebM, Ogg), improving cross-browser compatibility.
By including the type attribute, you can tell the browser the exact MIME type of the
video file, helping it determine whether it can play the file.
Key Attributes of the <video> Element
The following attributes can be used with the <video> tag to enhance video playback:
Attribute Description
autopla
Automatically starts playing the video when it's loaded.
y
<!DOCTYPE html>
<html>
<head>
<title>Sum of First N Even Numbers</title>
</head>
<body>
<h2>Sum of First N Even Numbers</h2>
Enter value of n: <input type="number" id="num">
<button onclick="findSum()">Calculate</button>
<p id="result"></p>
<script>
function findSum() {
let n = parseInt([Link]("num").value);
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += 2 * i; // generates even numbers: 2, 4, 6, ...
}
[Link]("result").innerHTML =
"Sum of first " + n + " even numbers is: " + sum;
}
</script>
</body>
</html>
Sum of first n even numbers is: <calculated value>
HTML is the standard markup language used for creating and structuring web pages on the
internet. It defines the structure of web content using elements and tags. HTML is not a
programming language but a markup language that describes how content should be
displayed in a web browser.
HTML allows developers to organize text, images, links, tables, and multimedia content in a
structured format. It works together with CSS for styling and JavaScript for adding
interactivity to web pages.
HTML documents are made up of elements such as headings, paragraphs, links, images, and
forms. These elements are represented using tags enclosed within angle brackets.
Each module is independent and can be developed, tested, and maintained separately.
Modules communicate with each other through well-defined interfaces. This modular
approach is widely used in system design and programming to improve efficiency and
reliability.
Modules help in breaking down complex problems into smaller manageable parts, making
development easier. They also support reusability, as the same module can be used in
multiple programs.
Cookies :
A cookie is a small piece of information that is persisted between the multiple client requests.
How Cookie works:
• By default, each request is considered as a new request.
• In cookies technique, we add cookie with response from the servlet.
• So cookie is stored in the cache of the browser.
• After that if request is sent by the user, cookie is added with request by default.
• Thus, we recognize the user as the old user.
A cookie is a small text file stored in the user’s browser by a web server. It contains
information in the form of key-value pairs such as user ID, session ID, preferences, and login
details.
Whenever a user visits a website, the server sends a cookie to the browser. The browser
stores this cookie and sends it back to the server with every subsequent request. This helps
the server recognize the user and maintain continuity.
Cookies are widely used in web applications for tracking user sessions, storing preferences,
and improving user experience.
Types of Cookies
Session Cookies
Session cookies are temporary cookies that are stored only for the duration of a session.
They are deleted automatically when the browser is closed. These are mainly used for
session tracking.
Persistent Cookies
Persistent cookies are stored in the browser for a fixed period of time. They remain even
after the browser is closed and are used to remember user preferences and login details.
Working of Cookies
When a user visits a website, the server creates a cookie.
The cookie is sent to the browser and stored on the client side.
The browser sends the cookie back to the server with every request.
The server reads the cookie and identifies the user.
This process allows the server to maintain state and track user activity.
Session Management Using Cookies
Session management is the process of maintaining user state across multiple requests.
Cookies are commonly used for this purpose.
Steps Involved
User Authentication
The user logs into the website by providing credentials.
Session Creation
The server creates a unique session ID for that user.
Cookie Generation
The session ID is stored in a cookie and sent to the user’s browser.
Storage at Client Side
The browser stores the cookie automatically.
Request with Cookie
For every new request, the browser sends the cookie to the server.
Session Validation
The server checks the session ID and identifies the user.
Session Maintenance
The user continues to interact with the system without logging in again until the session
expires or the cookie is deleted.
Uses of Cookies in Session Management
User authentication (login sessions)
Tracking user activity
Personalization (language, theme, preferences)
Maintaining shopping cart in e-commerce websites
Advantages of Cookies
Maintains session in stateless HTTP protocol
Improves user experience by avoiding repeated logins
Easy to implement and widely supported
Enables personalization of web applications
Disadvantages of Cookies
Security risks such as cookie theft and hacking
Limited storage capacity
Can be disabled by the use
Types of Cookie :
• There are 2 types of cookies in servlets.
– Non-persistent cookie
• It is valid for single session only. It is removed each time when user closes the browser.
– Persistent cookie
• It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
• Ex: gmail uses persistent cookie for login
• Advantage of Cookies
– Simplest technique of maintaining the state.
– Cookies are maintained at client side.
• Disadvantage of Cookies
– It will not work if cookie is disabled from the browser.
– Only textual information can be set in Cookie object.
Remote Method Invocation (RMI) is an API that allows an object to invoke a method on an
object that exists in another address space, which could be on the same machine or on a
remote machine. Through RMI, an object running in a JVM present on a computer (Client-
side) can invoke methods on an object present in another JVM (Server-side). RMI creates a
public remote server object that enables client and server-side communications through
simple method calls on the server object.
Stub Object: The stub object on the client machine builds an information block and sends
this information to the server.
The block consists of
An identifier of the remote object to be used
Method name which is to be invoked
Parameters to the remote JVM
Skeleton Object: The skeleton object passes the request from the stub object to the remote
object. It performs the following tasks
It calls the desired method on the real object present on the server.
It forwards the parameters received from the stub object to the method.
Working of RMI
The communication between client and server is handled by using two intermediate objects:
Stub object (on client side) and Skeleton object (on server-side) as also can be depicted from
below media as follows:
These are the steps to be followed sequentially to implement Interface as defined below
as follows:
1. Defining a remote interface
2. Implementing the remote interface
3. Creating Stub and Skeleton objects from the implementation class using rmic
(RMI compiler)
4. Start the rmiregistry
5. Create and execute the server application program
6. Create and execute the client application program.
7. Step 1: Defining the remote interface
8. The first thing to do is to create an interface that will provide the description of the
methods that can be invoked by remote clients. This interface should extend the
Remote interface and the method prototype within the interface should throw the
RemoteException.
9. Example:
10. // Creating a Search interface
11. import [Link].*;
12. public interface Search extends Remote
13. {
14. // Declaring the method prototype
15. public String query(String search) throws RemoteException;
}
Step 2: Implementing the remote interface
The next step is to implement the remote interface. To implement the remote interface, the
class should extend to UnicastRemoteObject class of [Link] package. Also, a default
constructor needs to be created to throw the [Link] from its parent
constructor in class.
// Java program to implement the Search interface
import [Link].*;
import [Link].*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
// Default constructor to throw RemoteException
// from its parent constructor
SearchQuery() throws RemoteException
{
super();
}
Step 3: Creating Stub and Skeleton objects from the implementation class using rmic
The rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton objects.
Its prototype is rmic classname. For above program the following command need to be
executed at the command prompt
rmic SearchQuery.
import [Link].*;
// Establish connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/", "root",
"password");
// Create statement
Statement stmt = [Link]();
// Execute query
[Link]("CREATE DATABASE CollegeDB");
[Link]("Database created
successfully!");
// Close connection
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
Explanation
Advantages of JDBC
Platform independent
Supports multiple databases
Enables dynamic SQL execution
Widely used in enterprise applications
PART C — (4 × 10 = 40 marks)
Answer any FOUR questions.
HTML5 is the fifth version of Hypertext Markup Language (HTML), a standard language
used to structure webpages. It defines how content on a webpage should be structured and
displayed. Here are some key points of HTML5.
New Added Elements in HTML 5
HTML5 introduced several new elements that help structure a webpage better and make it
more interactive. These elements not only improve the design but also make the code more
readable and accessible. Here are some key elements of HTML5:
<article>: The <article> tag represents independent, self-contained content like
articles or posts.
<aside>: The <aside> tag holds secondary or related information supporting the main
content.
<figcaption>: The <figcaption> tag provides a caption or description for a <figure>
element.
<figure>: The <figure> tag groups self-contained media such as images, diagrams, or
code.
<header>: The <header> tag contains introductory content like headings or
navigation links.
<footer>: The <footer> tag includes closing content such as author info or copyright
notes.
<main>: The <main> tag defines the central, most important content of the webpage.
<mark>: The <mark> tag highlights or emphasizes specific text.
<nav>: The <nav> tag groups navigation links for moving around the site.
<section>: The <section> tag organizes related content into thematic blocks.
<details>: The <details> tag creates expandable or collapsible content sections.
<summary>: The <summary> tag provides the clickable heading for a <details>
element.
<time>: The <time> tag represents dates or times in a readable and machine-usable
format.
<bdi>: The <bdi> tag isolates text with unknown or mixed text direction.
<wbr>: The <wbr> tag adds an optional line-break position in long words.
<datalist>: The <datalist> tag provides autocomplete suggestions for an <input>
element.
<keygen>: The <keygen> tag generates key pairs for secure authentication
(deprecated).
<output>: The <output> tag displays results of calculations or script actions.
<progress>: The <progress> tag visually represents the progress of a task.
<svg>: The <svg> tag embeds scalable vector graphics into a webpage.
<canvas>: The <canvas> tag draws dynamic graphics using JavaScript.
<audio>: The <audio> tag embeds audio content like music or sound effects.
<embed>: The <embed> tag inserts external resources such as media players or apps.
<source>: The <source> tag defines media sources for <audio> and <video>
elements.
<track>:The <track> tag provides captions or subtitles for videos.
<video>: The <video> tag embeds video content directly into a webpage.
HTML5 Advantages
HTML5 offers several benefits that enhance modern web development like:
Works on all major browsers and devices (cross-platform).
Lets websites access user location (geolocation).
Supports offline use through Web Storage or AppCache.
Uses semantic tags for cleaner, simpler code.
Optimized for smooth performance on mobile devices.
HTML5 Disadvantages
Despite its strengths, HTML5 comes with some drawbacks:
Older browsers may not support all HTML5 features (browser inconsistencies).
Some older mobile devices struggle with HTML5 (mobile compatibility issues).
Web Storage and similar features can pose security risks if misused.
Advanced APIs introduce complexity for beginners.
IE 8 and below show poor support for HTML5.
The Object is the most basic JavaScript structure used to store data in key–value pairs.
Example:
let person = {
name: "John",
age: 25
};
[Link]([Link]); // John
2. Array Object
Example:
3. String Object
Example:
Example:
5. Boolean Object
Example:
6. Date Object
Example:
7. Math Object
Example:
[Link]([Link](16)); // 4
[Link]([Link]()); // random number between 0 and 1
8. RegExp Object
Example:
9. Function Object
function greet(name) {
return "Hello " + name;
}
Example:
try {
throw new Error("Something went wrong");
} catch (e) {
[Link]([Link]);
}
The JSON object is used to parse and convert data in JSON format.
Example:
Summary
Object
Array
String
Number
Boolean
Date
Math
RegExp
Function
Error
JSON
A Servlet is a Java program that runs on a server to handle client requests and generate
dynamic responses. The Servlet life cycle is entirely managed by the Servlet container, which
uses the [Link] interface to manage Servlet objects. Understanding the life
cycle helps in writing efficient and resource-safe web applications.
2. Initializing a Servlet
After instantiation, the container initializes the Servlet using the init() method.
init(ServletConfig config) method is called once in the Servlet’s lifetime.
It prepares the Servlet to handle requests (e.g., database connection setup).
Called only once, unlike service() which is called per request.
Example:
@Override
public void init() throws ServletException {
// Initialization code (e.g., database connection)
}
3. Handling request
Once initialized, the Servlet is ready to handle client requests.
3.1 Request and Response Objects
ServletRequest and ServletResponse objects are created for each request.
For HTTP, HttpServletRequest and HttpServletResponse objects are used.
3.2 The service() Method
The container calls service(ServletRequest req, ServletResponse res) for each
request.
Determines the HTTP request type (GET, POST, PUT, DELETE).
Delegates the request to appropriate methods: doGet(), doPost(), etc.
Example:
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Handle request and generate response
}
4. Destroying a Servlet
When the Servlet container decides to remove the Servlet, it follows these steps
which are listed below
Allow Active Threads to Complete: The container ensures that all threads
executing the service() method complete their tasks.
Invoke the destroy() Method: The container calls the destroy() method to
allow the Servlet to release resources (e.g., closing database connections,
freeing memory).
Release Servlet Instance: After the destroy() method is executed, the Servlet
container releases all references to the Servlet instance, making it eligible for
garbage collection
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet:
init()
service()
destroy()
Life Cycle of Servlet
1. init() Method
Invoked once when the Servlet is instantiated.
Used to initialize resources (e.g., database connections).
Prefer the non-parameterized init() method for fewer redundant calls.
Example:
@Override
public void init() throws ServletException {
// Initialization code
}
Exception handling is possible in init().
Constructor is not recommended for initialization because it cannot throw
ServletException.
2. service() Method
Handles client requests and responses.
Determines HTTP request type (GET, POST, PUT, DELETE) and delegates
to doGet(), doPost(), etc.
Example:
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Request handling code
}
Connects client and server.
Accepts ServletRequest and ServletResponse objects.
3. destroy() Method
Called once at the end of the Servlet’s life cycle.
Cleans up resources (e.g., closes DB connections, releases memory).
init() Method: Initializes the output variable when the Servlet is first loaded.
doGet() Method: Responds to client GET requests and prints the output as
HTML.
Thread Safety: output is immutable, ensuring safe access by multiple threads.
destroy() Method: Invoked before Servlet removal to release resources or
perform cleanup.
23. Demonstrate the JSP architecture and explain its working principle.
Introduction to JSP
JavaServer Pages (JSP) is a server-side technology that creates
dynamic web applications. It allows developers to embed Java
code directly into HTML pages and it makes web development
more efficient. JSP is an advanced version of Servlets. It provides
enhanced capabilities for building scalable and platform-
independent web pages.
It is platform-independent; we can write once, run
anywhere.
It simplifies database interactions for dynamic content.
It contains predefined objects like request, response,
session and application, reducing development time.
It has built-in mechanisms for exception and error
management.
It supports custom tags and tag libraries.
JSP Architecture
JSP follows a three-layer architecture:
Client Layer: The browser sends a request to the server.
Web Server Layer: The server processes the request using a JSP
engine.
Database/Backend Layer: Interacts with the database and returns the
response to the client.
JSP Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container
is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache
which has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web application.
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements the
corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format. The output is
furthur passed on to the web server by the servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet. If the JSP is older than its
generated servlet, the JSP container assumes that the JSP hasn't changed and that the
generated servlet still matches the JSP's contents. This makes the process more efficient than
with the other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a
Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a
regular servlet.
A JSP (Java Server Pages) program can be used to accept marks of five subjects, calculate
the total and average, and display the corresponding grade.
Steps Involved
1. Create an HTML form to accept marks
2. Pass data to a JSP file
3. Retrieve marks using [Link]()
4. Calculate total and average
5. Assign grade based on average
6. Display the result
<!DOCTYPE html>
<html>
<head>
<title>Student Grade</title>
</head>
<body>
<h2>Enter Marks of Five Subjects</h2>
<%
// Get input values
int m1 = [Link]([Link]("m1"));
int m2 = [Link]([Link]("m2"));
int m3 = [Link]([Link]("m3"));
int m4 = [Link]([Link]("m4"));
int m5 = [Link]([Link]("m5"));
String grade;
// Determine grade
if (avg >= 90)
grade = "A+";
else if (avg >= 75)
grade = "A";
else if (avg >= 60)
grade = "B";
else if (avg >= 50)
grade = "C";
else
grade = "Fail";
%>
<h2>Student Result</h2>
Total Marks: <%= total %> <br>
Average: <%= avg %> <br>
Grade: <%= grade %> <br>
</body>
</html>
Sample Output
If the marks entered are:
80, 75, 90, 85, 70
Output:
Conclusion
This JSP program demonstrates how to:
Accept user input through an HTML form
Process data using JSP scripting elements
Calculate results and display grade dynamically
SQL (Structured Query Language) is used to manage and manipulate data in a database. The
most commonly used statements are SELECT, INSERT, and UPDATE.
1. SELECT Statement
Syntax:
Syntax:
3. UPDATE Statement
Syntax:
UPDATE table_name
SET column1 = value1
WHERE condition;
Example:
UPDATE Student
SET marks = 90
WHERE id = 101;
Explanation:
id name marks
100 Ravi 70
After INSERT
INSERT INTO Student VALUES (101, 'Divya', 85);
id name marks
100 Ravi 70
101 Divya 85
After UPDATE
UPDATE Student SET marks = 90 WHERE id = 101;
id name marks
100 Ravi 70
101 Divya 90
Using SELECT
SELECT * FROM Student;
Output:
id name marks
100 Ravi 70
101 Divya 90
Conclusion
These commands are fundamental for database operations and widely used in applications.