Web Technology
106609Module III: Basics of Web Programming
Q1(a). What is scriptlet?20232m
Module III: Basics of Web Programming
View this question on its own page →What is scriptlet?
Worked SolutionA scriptlet is a block of Java code embedded directly inside a JSP (JavaServer Pages) page, written between
<%and%>. The code runs on the server each time the page is requested, and its output becomes part of the HTML sent to the browser.<% int count = 5; for (int i = 1; i <= count; i++) { out.println("Line " + i + "<br>"); } %>Related JSP elements: declaration
<%! ... %>, expression<%= ... %>, and directive<%@ ... %>.Q1(c). What are interfaces in JAVA.20232m
Module III: Basics of Web Programming
View this question on its own page →What are interfaces in JAVA.
Worked SolutionAn interface in Java is a reference type that declares abstract methods (and constants) without providing a full implementation. A class that
implementsthe interface must define all its methods.interface Shape { double area(); // implicitly public abstract } class Circle implements Shape { double r; Circle(double r) { this.r = r; } public double area() { return Math.PI * r * r; } }Key points:
- Achieves 100% abstraction (before Java 8) and supports multiple inheritance of type, since a class can implement many interfaces.
- Since Java 8 an interface can also contain
defaultandstaticmethods. - Fields are implicitly
public static final.
Q1(d). Explain cookies.20232m
Module III: Basics of Web Programming
View this question on its own page →Explain cookies.
Worked SolutionA cookie is a small piece of data (name=value, up to ~4 KB) that a server sends to the browser, which stores it and returns it with every later request to the same site. It is used to make the stateless HTTP protocol remember a user.
Uses: session management (login state), personalization (theme, language), and tracking (analytics, ads).
Attributes:
Expires/Max-Age,Path,Domain,Secure,HttpOnly,SameSite.Set-Cookie: theme=dark; Max-Age=86400; Path=/; HttpOnly; SecureQ1(e). Which method is used in JavaScript to send a request to the server asynchronously? (i) fetch() (ii) XMLHttpRequest() (iii) $.get() (iv) send()20242m
Module III: Basics of Web Programming
View this question on its own page →Which method is used in JavaScript to send a request to the server asynchronously? (i) fetch() (ii) XMLHttpRequest() (iii) $.get() (iv) send()
Worked SolutionAnswer: (i) fetch()
fetch()is the modern, Promise-based API for asynchronous HTTP requests:const res = await fetch('/api/data'); const data = await res.json();XMLHttpRequestis the older async mechanism, and$.get()is a jQuery library wrapper. The built-in native method to prefer isfetch().Q1(e). What is the role of query string in web communication?20232m
Module III: Basics of Web Programming
View this question on its own page →What is the role of query string in web communication?
Worked SolutionThe query string is the part of a URL after
?that carries data to the server asname=valuepairs joined by&.https://example.com/search?q=web+tech&page=2Role in web communication:
- Passes parameters from client to server in HTTP GET requests (form input, search terms, filters, pagination).
- Lets the same resource return different content based on the parameters.
- The server reads it (e.g.
$_GET['q']in PHP,req.query.qin Express). - URLs with query strings can be bookmarked and shared.
Limitation: data is visible in the URL and logs and length-limited, so never send passwords through it.
Q1(f). In JavaScript, what is the result of the following expression: typeof null? (i) null (ii) object (iii) undefined (iv) boolean20242m
Module III: Basics of Web Programming
View this question on its own page →In JavaScript, what is the result of the following expression: typeof null? (i) null (ii) object (iii) undefined (iv) boolean
Worked SolutionAnswer: (ii) object
typeof nullreturns"object". This is a long-standing bug from the first version of JavaScript, wherenullwas represented with the object type tag, and it was kept for backward compatibility. To test for null, usevalue === null.Q1(f). A web application validates a form directly in the user's browser before submitting it to the server. Which technology is most directly suited for this task? (i) JavaScript (ii) PHP (iii) Servlet (iv) EJB20262m
Module III: Basics of Web Programming
View this question on its own page →A web application validates a form directly in the user's browser before submitting it to the server. Which technology is most directly suited for this task?
(i) JavaScript
(ii) PHP
(iii) Servlet
(iv) EJBWorked SolutionCorrect answer: (i) JavaScript. It can validate forms in the browser and give immediate feedback. Server-side validation is still essential because client-side checks can be bypassed.
Q1(f). What are advantages of a content management system?20232m
Module III: Basics of Web Programming
View this question on its own page →What are advantages of a content management system?
Worked SolutionA Content Management System (CMS) lets users create, edit, organize, and publish web content without writing code (e.g. WordPress, Drupal, Joomla).
Advantages:
- No coding needed: non-technical users can update content through a WYSIWYG editor.
- Separation of content and design: themes and templates control layout, so content can be changed independently.
- Multi-user workflow: roles, permissions, drafts, and approval before publishing.
- Faster development: ready-made plugins and modules for SEO, forms, and e-commerce.
- Consistency: one template keeps the whole site uniform.
- Easy maintenance: version history, backups, and centralized updates.
- Scalability: pages and features can be added easily as the site grows.
Q1(g). Suppose an application requires communication between distributed objects and uses Enterprise JavaBeans as part of its architecture. Which category does this belong to? (i) Client-side styling (ii) Distributed object model/server-side Java technology (iii) File transfer protocol (iv) Browser rendering20262m
Module III: Basics of Web Programming
View this question on its own page →Suppose an application requires communication between distributed objects and uses Enterprise JavaBeans as part of its architecture. Which category does this belong to?
(i) Client-side styling
(ii) Distributed object model/server-side Java technology
(iii) File transfer protocol
(iv) Browser renderingWorked SolutionCorrect answer: (ii) Distributed object model/server-side Java technology. EJB is a server-side Java component model for enterprise services such as transactions, security and business logic.
Q1(g). Which variable is used to collect form data sent with both the GET and POST methods in PHP? (i) _BOTH (ii) _REQUEST (iii) _REQUEST (iv) _BOTH20242m
Module III: Basics of Web Programming
View this question on its own page →Which variable is used to collect form data sent with both the GET and POST methods in PHP? (i) _REQUEST (iii) _BOTH
Worked SolutionAnswer: (ii)
$_REQUEST(options (ii) and (iii) are identical in the paper)._GET,_COOKIE.$_BOTHdoes not exist in PHP.- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q1(g). Differentiate cookies from session variables.20232m
Module III: Basics of Web Programming
View this question on its own page →Differentiate cookies from session variables.
Worked SolutionBasis Cookies Session variables Storage location Client (browser) Server (only a session ID is kept on the client, usually in a cookie) Security Less secure; user can view or modify them More secure; data stays on the server Capacity About 4 KB per cookie Limited only by server memory or storage Lifetime Persistent until the expiry date, or session-only Ends when the browser closes, on timeout, or on session_destroy()Data types Strings only Any data type, including arrays and objects Performance Sent with every request Uses server resources PHP access setcookie(),_SESSIONQ1(h). Explain Inheritance.20232m
Module III: Basics of Web Programming
View this question on its own page →Explain Inheritance.
Worked SolutionInheritance is an OOP mechanism in which a new class (subclass or child) acquires the fields and methods of an existing class (superclass or parent). It promotes code reuse and models an is-a relationship.
class Animal { void eat() { System.out.println("eating"); } } class Dog extends Animal { void bark() { System.out.println("barking"); } } // Dog d = new Dog(); d.eat(); d.bark();Types: single, multilevel, and hierarchical (Java supports multiple inheritance only through interfaces).
Benefits: reusability, easier maintenance, and method overriding for runtime polymorphism.
Q1(h). Which method is invoked immediately after the start() method and whenever an applet needs to be repainted itself in the browser? (i) init() (ii) stop() (iii) run() (iv) paint()20242m
Module III: Basics of Web Programming
View this question on its own page →Which method is invoked immediately after the start() method and whenever an applet needs to be repainted itself in the browser? (i) init() (ii) stop() (iii) run() (iv) paint()
Worked SolutionAnswer: (iv) paint()
Applet life cycle:
init()→start()→paint()→stop()→destroy().paint(Graphics g)is called right afterstart()and again whenever the applet must be redrawn (window resized, uncovered, orrepaint()called).Q1(i). What is polymorphism?20232m
Module III: Basics of Web Programming
View this question on its own page →What is polymorphism?
Worked SolutionPolymorphism means "many forms": one interface or method name behaving differently depending on the object or arguments.
1. Compile-time (static): method overloading, where the same name has different parameter lists.
int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; }2. Runtime (dynamic): method overriding, where the subclass redefines a parent method and the JVM picks the version from the actual object type.
Animal a = new Dog(); a.sound(); // calls Dog's sound()It makes code flexible and extensible.
Q1d. Which of the following is the correct syntax to print a page using JavaScript? (i) window.print(); (ii) browser.print(); (iii) navigator.print(); (iv) document.print();20202m
Module III: Basics of Web Programming
View this question on its own page →Which of the following is the correct syntax to print a page using JavaScript?
(i) window.print();
(ii) browser.print();
(iii) navigator.print();
(iv) document.print();Worked SolutionCorrect Answer: (i) window.print();
Explanation:
- In client-side JavaScript, the
window.print()method opens the browser's native Print dialog box, allowing the user to print the current webpage or save it as a PDF. - The
windowobject represents the global browser window containing the DOM document.
Example:
<button onclick="window.print()">Print This Page</button>Note on other objects:
browseris not a standard global DOM API.navigatorprovides browser metadata (user-agent, geolocation, platform).documentrepresents the HTML document tree, but theprint()method resides on the top-levelwindowobject.
- In client-side JavaScript, the
Q1e. JavaScript code is written inside file having extension (i) .jvs (ii) .JavaScript (iii) .js (iv) .jsc20192m
Module III: Basics of Web Programming
View this question on its own page →JavaScript code is written inside file having extension
(i) .jvs
(ii) .JavaScript
(iii) .js
(iv) .jscWorked SolutionCorrect Answer: (iii) .js
Explanation:
- External JavaScript source files are saved with the standard
.jsfile extension (e.g.,main.js,script.js). - They are linked into HTML documents using the
<script src="...">element:<script src="script.js"></script>
- External JavaScript source files are saved with the standard
Q1f. JavaScript is called as lightweight programming language because (i) JS is available free of cost (ii) JS is client-side scripting (iii) we can add programming functionality inside JS (iv) JS can provide programming functionality inside but up to certain extent20192m
Module III: Basics of Web Programming
View this question on its own page →JavaScript is called as lightweight programming language because
(i) JS is available free of cost
(ii) JS is client-side scripting
(iii) we can add programming functionality inside JS
(iv) JS can provide programming functionality inside but up to certain extentWorked SolutionCorrect Answer: (iv) JS can provide programming functionality inside but up to certain extent
Explanation:
- JavaScript is described as a "lightweight" language because:
- It has a small memory footprint and does not require complex local compilation or binaries before execution.
- It has restricted system-level access in the browser sandbox (cannot directly manage OS threads, pointers, or arbitrary disk files).
- It executes directly via the browser's lightweight JIT-interpreter engine.
- JavaScript is described as a "lightweight" language because:
Q1g. Which technology is used for server-side scripting? (i) HTML (ii) CSS (iii) JSP (iv) JavaScript20252m
Module III: Basics of Web Programming
View this question on its own page →Which technology is used for server-side scripting?
(i) HTML
(ii) CSS
(iii) JSP
(iv) JavaScriptWorked SolutionCorrect Answer: (iii) JSP
Explanation:
- JSP (JavaServer Pages) is a server-side technology that allows developers to insert Java code into HTML templates to generate dynamic web content on the server before sending it to the client.
- HTML and CSS are purely client-side markup and styling languages rendered directly by the browser.
- JavaScript historically runs as a client-side scripting language in the browser (unless explicitly executed on a runtime like Node.js).
How JSP Works on Server:
- Client requests a
.jspfile. - The web server translates JSP into a Java Servlet (
.java). - The servlet is compiled into bytecode (
.class) and executed. - The generated HTML response is sent back to the client.
Q1h. What is the fundamental unit of information of writer streams in Java? (i) Characters (ii) Bytes (iii) Files (iv) Records20192m
Module III: Basics of Web Programming
View this question on its own page →What is the fundamental unit of information of writer streams in Java?
(i) Characters
(ii) Bytes
(iii) Files
(iv) RecordsWorked SolutionCorrect Answer: (i) Characters
Explanation:
- In Java I/O (
java.io), Writer (and Reader) streams are Character Streams that operate on 16-bit Unicode Characters (e.g.,FileWriter,PrintWriter,BufferedWriter). - Byte Streams (e.g.,
FileOutputStream,InputStream) operate on 8-bit Bytes.
Stream Classification in Java:
Stream Hierarchy Base Class Unit of Data Character Output java.io.Writer16-bit Unicode Characters Character Input java.io.Reader16-bit Unicode Characters Byte Output java.io.OutputStream8-bit Bytes Byte Input java.io.InputStream8-bit Bytes - In Java I/O (
Q1h. Which of the following is a client-side scripting language? (i) PHP (ii) JavaScript (iii) JSP (iv) Servlet20252m
Module III: Basics of Web Programming
View this question on its own page →Which of the following is a client-side scripting language?
(i) PHP
(ii) JavaScript
(iii) JSP
(iv) ServletWorked SolutionCorrect Answer: (ii) JavaScript
Explanation:
- JavaScript is the standard client-side scripting language executed directly by the web browser's JavaScript engine (e.g., V8, SpiderMonkey).
- It enables interactive web pages, dynamic styling, DOM manipulation, form validation, and asynchronous requests (AJAX).
- PHP, JSP, and Servlets are all server-side technologies executed on the web/application server.
- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q1i. The command to execute a compiled Java program is (i) javac (ii) java (iii) run (iv) execute20192m
Module III: Basics of Web Programming
View this question on its own page →The command to execute a compiled Java program is
(i) javac
(ii) java
(iii) run
(iv) executeWorked SolutionCorrect Answer: (ii) java
Explanation:
- The
javacommand launches the Java Virtual Machine (JVM) to load, verify, and execute compiled.classbytecode files (e.g.,java ProgramName). javacis the compiler command used to compile.javasource code into bytecode (javac ProgramName.java).runandexecuteare not standard JDK command-line utilities.
- The
Q1j. The Java compiler (i) creates executable (ii) translates Java source code to byte code (iii) creates classes (iv) produces Java interpreters20192m
Module III: Basics of Web Programming
View this question on its own page →The Java compiler
(i) creates executable
(ii) translates Java source code to byte code
(iii) creates classes
(iv) produces Java interpretersWorked SolutionCorrect Answer: (ii) translates Java source code to byte code
Explanation:
- The Java Compiler (
javac) translates high-level Java source code (.java) into platform-independent intermediate Bytecode stored in.classfiles. - The bytecode is later interpreted and executed by the Java Virtual Machine (JVM).
- Unlike C/C++ compilers, the Java compiler does not generate direct machine-executable binaries (
.exeor.out).
- The Java Compiler (
Q1j. Which of the following keywords can be used in a subclass to call the constructor of superclass? (i) Super (ii) This (iii) Extent (iv) Extends20202m
Module III: Basics of Web Programming
View this question on its own page →Which of the following keywords can be used in a subclass to call the constructor of superclass?
(i) Super
(ii) This
(iii) Extent
(iv) ExtendsWorked SolutionCorrect Answer: (i) Super (specifically
super())Explanation:
- In Java, the
superkeyword is a reference variable used to refer to immediate parent (superclass) class objects. - When used with parentheses as
super()orsuper(arguments), it explicitly invokes the constructor of the superclass. - Rule: The call to
super()must be the very first statement inside the subclass constructor.
Example:
class Parent { Parent(String message) { System.out.println("Parent Constructor: " + message); } } class Child extends Parent { Child() { super("Invoking Superclass Constructor"); // Calls Parent constructor System.out.println("Child Constructor"); } }Contrast with other keywords:
this(): Invokes another constructor within the same class.extends: Declares class inheritance (class Child extends Parent).
- In Java, the
Q2(a). How does the use of cookies help in server-side scripting? Give examples for data stored using cookies.20237m
Module III: Basics of Web Programming
View this question on its own page →How does the use of cookies help in server-side scripting? Give examples for data stored using cookies.
Worked SolutionHow cookies help in server-side scripting
HTTP is stateless: the server treats every request as new. A server-side script (PHP, Node.js, JSP) can use cookies to recognise a returning client.
Flow:
- The script sends a
Set-Cookieheader in its response. - The browser stores the cookie.
- The browser sends it back in the
Cookieheader on every later request to that site. - The script reads it (
$_COOKIEin PHP,req.cookiesin Express) and customises the response.
Benefits for server-side scripts:
- Session tracking: a session ID cookie identifies the logged-in user.
- Personalisation: language, theme, layout.
- Remember me: keeps the user signed in across visits.
- Shopping carts and tracking: cart contents, visited pages, analytics.
Examples of data stored in cookies: username, session ID, preferred language, theme (dark/light), cart ID, last visited page, consent choice.
PHP example:
<?php setcookie("username", "raiyan", time() + 86400 * 7, "/"); // 7 days if (isset($_COOKIE["username"])) { echo "Welcome back, " . $_COOKIE["username"]; } ?>Express (JavaScript) example:
res.cookie('theme', 'dark', { maxAge: 86400000, httpOnly: true }); const theme = req.cookies.theme;Caution: cookies are visible to the client, so never store passwords or sensitive data in them. Use
HttpOnly,Secure, andSameSiteflags.- The script sends a
Q3(a). Design a simple HTML form to input a string and to display whether it is Armstrong or not within the form submitted. Use a PHP script.20237m
Module III: Basics of Web Programming
View this question on its own page →Design a simple HTML form to input a string and to display whether it is Armstrong or not within the form submitted. Use a PHP script.
Worked SolutionArmstrong number checker (HTML form + PHP)
An Armstrong number equals the sum of its digits each raised to the power of the number of digits (e.g. 153 = 1³ + 5³ + 3³; 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴).
armstrong.php (form and result on the same page)
<!DOCTYPE html> <html> <head><title>Armstrong Number Check</title></head> <body> <h2>Armstrong Number Checker</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"> <label>Enter a number: <input type="text" name="num" required> </label> <input type="submit" value="Check"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { _POST["num"]); if (!ctype_digit($input)) { echo "<p>Please enter digits only.</p>"; } else { input); // number of digits $sum = 0; for (i < i++) { input[n); } if (input) { echo "<p><b>$input</b> is an Armstrong number.</p>"; } else { echo "<p><b>$input</b> is NOT an Armstrong number.</p>"; } } } ?> </body> </html>How it works:
- The form posts the value to the same script (
PHP_SELF). - PHP reads it from
$_POST['num']and validates that it contains only digits. - It counts the digits, sums each digit raised to that power, and compares the sum with the original number.
- The result is printed below the form, so the answer appears within the submitted page.
Sample: input
153→ 1 + 125 + 27 = 153 → Armstrong. Input123→ 1 + 8 + 27 = 36 → not Armstrong.- The form posts the value to the same script (
Q3(b). What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?20237m
Module III: Basics of Web Programming
View this question on its own page →What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?
Worked SolutionSignificance of cookies
HTTP is stateless, so cookies give websites a memory. They enable:
- Session management: login state, shopping carts.
- Personalisation: language, theme, preferences.
- Tracking and analytics: counting visits, behaviour, advertising.
- Convenience: "remember me" and auto-filled details.
Creating a cookie in PHP
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);It must be called before any output (before
<html>), because cookies travel in HTTP headers.<?php // Create: valid for 1 hour setcookie("user", "Raiyan", time() + 3600, "/"); ?> <html><body> <?php if (isset($_COOKIE["user"])) { echo "Hello, " . $_COOKIE["user"]; // available from the next request } else { echo "Cookie not set yet."; } ?> </body></html>Destroying a cookie in PHP
There is no delete function. Set the same cookie with an expiry time in the past (same name, path, and domain):
<?php setcookie("user", "", time() - 3600, "/"); unset($_COOKIE["user"]); // also remove it from the current request ?>The browser sees the cookie has expired and removes it.
Q3a. Explain the steps involved in creating and executing a Java program.20207m
Module III: Basics of Web Programming
View this question on its own page →Explain the steps involved in creating and executing a Java program.
Worked SolutionAnswer: Steps Involved in Creating and Executing a Java Program
1. Introduction
Java follows the "Write Once, Run Anywhere" (WORA) philosophy. Unlike traditional compiled languages (like C/C++) that compile directly into platform-dependent machine binaries, Java source code is compiled into an intermediate, platform-neutral format called Bytecode, which is executed by the Java Virtual Machine (JVM).
+---------------------+ | Java Source Code | (HelloWorld.java) +----------+----------+ | | 1. javac Compiler v +---------------------+ | Java Bytecode | (HelloWorld.class) +----------+----------+ | | 2. Transferred to any OS (Windows, Linux, macOS) v +---------------------------------------------------------------+ | JAVA VIRTUAL MACHINE (JVM) | | | | +----------------------+ +---------------------------+ | | | ClassLoader Subsystem| ---> | Bytecode Verifier | | | +----------------------+ +-------------+-------------+ | | | | | v | | +---------------------------+ | | | Execution Engine | | | | (Interpreter + JIT Engine)| | | +-------------+-------------+ | +----------------------------------------------|----------------+ | v +--------------------+ | Machine Code / CPU | +--------------------+
2. Step-by-Step Process
Step 1: Writing the Source Code
- Create a Java source file using any text editor or IDE (VS Code, IntelliJ IDEA, Eclipse).
- Save the file with a
.javaextension. The file name must exactly match the public class name.
// File: HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World from Java!"); } }
Step 2: Compiling the Source Code (
javac)- The Java Compiler (
javac) reads the.javasource code, verifies syntax and semantic rules, and translates it into platform-independent Bytecode. - Command:
javac HelloWorld.java - Output: Produces a binary file named
HelloWorld.class.
Step 3: Loading Classes into Memory (ClassLoader)
When executing the program (
java HelloWorld), the JVM starts and its ClassLoader subsystem performs three phases:- Loading: Reads
.classbinary streams and creates theClassobject in the JVM Method Area. - Linking:
- Verification: Ensures bytecode adheres to JVM specifications and has no illegal memory accesses.
- Preparation: Allocates memory for static variables and initializes default values.
- Resolution: Replaces symbolic references with direct memory references.
- Initialization: Executes static initializers and assigns explicit static values.
Step 4: Bytecode Verification
- The Bytecode Verifier checks the code for security violations (e.g., stack overflow, illegal data type casting, unauthorized pointer manipulation) before execution.
Step 5: Execution by the JVM Execution Engine
The JVM execution engine executes bytecode instructions on the underlying CPU using two combined strategies:
- Interpreter: Reads and executes bytecode instructions line by line (starts quickly).
- JIT (Just-In-Time) Compiler: Identifies frequently executed code blocks ("hot spots") and compiles them directly into native machine code to drastically boost runtime performance.
- Garbage Collector: Automatically tracks and reclaims unreferenced heap memory in the background.
3. Summary of CLI Commands
Step Command Tool Used File Produced Compilation javac HelloWorld.javaJava Compiler ( javac)HelloWorld.class(Bytecode)Execution java HelloWorldJava Virtual Machine ( java)Console Output / Runtime Q3a. What are events? Explain the events used in JavaScript with the help of examples.20197m
Module III: Basics of Web Programming
View this question on its own page →What are events? Explain the events used in JavaScript with the help of examples.
Worked SolutionAnswer: Events and Event Handling in JavaScript
1. What are Events in JavaScript?
In JavaScript, an Event is an action or occurrence recognized by software, initiated either by the user (e.g., clicking a button, pressing a key, moving the mouse) or by the browser (e.g., page loading, network error).
JavaScript uses Event Listeners / Handlers to execute specific functions whenever a targeted event occurs on a DOM element.
[ User Action: Click Button ] ---> [ Event Object Created: 'click' ] ---> [ Event Listener Dispatches Callback ] ---> [ DOM / UI Updated ]
2. Three Ways to Register Event Handlers
- Inline HTML Attributes:
<button onclick="alert('Button Clicked!')">Click Me</button> - DOM Object Property:
const btn = document.getElementById("myBtn"); btn.onclick = function() { console.log("Clicked"); }; - W3C Standard
addEventListener()(Recommended):const btn = document.getElementById("myBtn"); btn.addEventListener("click", (event) => { console.log("Button clicked at coordinates: " + event.clientX + ", " + event.clientY); });
3. Major Categories of JavaScript Events
A. Mouse Events
Event Trigger Condition Code Example clickUser clicks on an element btn.addEventListener('click', handleClick)dblclickUser double-clicks an element box.addEventListener('dblclick', handleDoubleClick)mouseoverMouse pointer enters element boundaries card.addEventListener('mouseover', highlight)mouseoutMouse pointer leaves element boundaries card.addEventListener('mouseout', unhighlight)mousemoveMouse pointer moves over an element canvas.addEventListener('mousemove', draw)
B. Keyboard Events
Event Trigger Condition Code Example keydownKey is pressed down input.addEventListener('keydown', (e) => console.log(e.key))keyupKey is released input.addEventListener('keyup', validate)
C. Form Events
Event Trigger Condition Code Example submitForm is submitted (can intercept via e.preventDefault())form.addEventListener('submit', validateForm)changeValue of an input/select element has changed and lost focus select.addEventListener('change', updateSelection)focusElement receives focus input.addEventListener('focus', showHint)blurElement loses focus input.addEventListener('blur', hideHint)inputValue changes in real-time input.addEventListener('input', updateCharCount)
D. Window / Document Lifecycle Events
Event Trigger Condition Code Example DOMContentLoadedHTML document is fully parsed into DOM (without waiting for images/stylesheets) document.addEventListener('DOMContentLoaded', init)loadEntire page including all stylesheets, scripts, and images is fully loaded window.addEventListener('load', startApp)resizeBrowser window viewport is resized window.addEventListener('resize', handleResize)scrollUser scrolls the document window.addEventListener('scroll', checkScrollPosition)
4. Comprehensive Interactive Demonstration
<!DOCTYPE html> <html> <head> <title>JavaScript Events Demo</title> </head> <body> <h2>JavaScript Event Handling Demo</h2> <!-- Mouse Event --> <button id="alertBtn">Click Me (Mouse Event)</button> <!-- Keyboard Event --> <p>Type below to see live character count (Keyboard Event):</p> <input type="text" id="textInput" placeholder="Type something..."> <span id="charCount">0 characters</span> <!-- Form Event --> <form id="sampleForm" style="margin-top:20px;"> <input type="text" id="username" placeholder="Username" required> <button type="submit">Submit Form</button> </form> <p id="statusMsg"></p> <script> // 1. Mouse Event document.getElementById("alertBtn").addEventListener("click", () => { alert("Mouse Click Event Triggered!"); }); // 2. Keyboard & Input Event const textInput = document.getElementById("textInput"); const charCount = document.getElementById("charCount"); textInput.addEventListener("input", () => { charCount.innerText = textInput.value.length + " characters"; }); // 3. Form Submit Event with preventDefault() document.getElementById("sampleForm").addEventListener("submit", (e) => { e.preventDefault(); // Prevents page reload const user = document.getElementById("username").value; document.getElementById("statusMsg").innerText = "Form submitted for: " + user; }); </script> </body> </html>- Inline HTML Attributes:
Q3b. Explain Java garbage collection mechanism.20207m
Module III: Basics of Web Programming
View this question on its own page →Explain Java garbage collection mechanism.
Worked SolutionAnswer: Java Garbage Collection Mechanism
1. What is Java Garbage Collection (GC)?
Garbage Collection (GC) in Java is an automated memory management process managed by the Java Virtual Machine (JVM) that tracks objects allocated on the heap and reclaims memory occupied by objects that are no longer reachable or referenced by any active part of the running program.
Unlike languages like C/C++ where developers must manually allocate and free memory (
malloc()/free(),new/delete), Java automatically prevents memory leaks and dangling pointer errors.+---------------------------------------------------------------------------------+ | JVM HEAP | | | | +----------------------------- Young Gen ----------------------------+ | | | +----------------+ +--------------------+ +--------------------+ | Old | | | | Eden | | Survivor 0 (From) | | Survivor 1 (To) | | Gen | | | | (New Objects) | | (Minor GC S0) | | (Minor GC S1) | | (Tenured) | | +----------------+ +--------------------+ +--------------------+ | | | +--------------------------------------------------------------------+---------+
2. When Does an Object Become Eligible for GC?
An object on the heap is eligible for garbage collection when it has no live references pointing to it from the GC Roots (stack frames, static variables, JNI references).
Common Scenarios:
- Nullifying a Reference Variable:
Student s = new Student("Alice"); s = null; // Original Student object is now eligible for GC - Reassigning a Reference Variable:
Student s1 = new Student("Alice"); Student s2 = new Student("Bob"); s1 = s2; // Original "Alice" object is now orphaned and eligible for GC - Objects Created Inside a Method Scope:
- Once the method finishes execution, local reference variables popped from the call stack leave created objects unreferenced.
- Island of Isolation:
- Two objects reference each other, but neither is referenced by any active live reference from root threads.
3. Generational Garbage Collection Hypothesis
Most objects in software have short lifespans (created, used, and discarded quickly). JVM divides the Heap into Generations:
A. Young Generation
- Eden Space: All new objects are initially created here.
- Survivor Spaces (S0 & S1): Objects that survive a Minor GC in Eden are moved between S0 and S1, incrementing their age counter.
B. Old (Tenured) Generation
- Objects that survive multiple Minor GC cycles (threshold age, typically 15) are promoted to the Old Generation.
- Cleaned up during a Major GC (Full GC).
C. Metaspace (Non-Heap)
- Stores class metadata and static variables (replaces PermGen in Java 8+).
4. How Garbage Collection Works: The Mark-and-Sweep Process
- Mark Phase: The GC identifies and marks all live, reachable objects by traversing reference trees starting from GC Roots.
- Sweep Phase: The GC sweeps the heap and frees the memory occupied by all unmarked (unreachable) objects.
- Compact Phase (Optional): Moves all surviving objects together to eliminate memory fragmentation and create contiguous free space.
5. Explicit GC Request and Finalization
- Requesting GC: Developers can suggest garbage collection using:
(Note: This only requests GC; the JVM decides when to actually execute it).System.gc(); // or Runtime.getRuntime().gc(); finalize()Method: Historically invoked by the JVM before reclaiming an object's memory (deprecated in modern Java in favor ofAutoCloseable/Cleaner).
6. Popular JVM Garbage Collectors
Garbage Collector Use Case Key Characteristics Serial GC Small, single-threaded apps Single-threaded, basic Mark-Sweep-Compact Parallel GC High-throughput batch jobs Multi-threaded Minor and Major GC G1 GC (Garbage-First) Large heap sizes (>4GB), default in modern Java Divides heap into equal regions; prioritizes regions with most garbage ZGC / Shenandoah Ultra-low latency enterprise apps Sub-millisecond pause times concurrent GC - Nullifying a Reference Variable:
Q3b. Explain various data types used in JavaScript with the help of examples.20197m
Module III: Basics of Web Programming
View this question on its own page →Explain various data types used in JavaScript with the help of examples.
Worked SolutionAnswer: Data Types in JavaScript with Examples
1. Introduction
JavaScript is a dynamically typed (loosely typed) language, meaning variables do not require explicit type declarations; data types are automatically determined at runtime based on the assigned value.
Data types in JavaScript are divided into two primary categories:
- Primitive Data Types (Immutable, passed by value)
- Non-Primitive / Reference Data Types (Mutable, passed by reference)
+-----------------------------+ | JAVASCRIPT DATA TYPES | +--------------+--------------+ | +------------------------+------------------------+ | | v v +--------------------+ +--------------------+ | PRIMITIVE TYPES | | REFERENCE TYPES | | Number, String, | | Object, Array, | | Boolean, Undefined,| | Function, Date, | | Null, BigInt, | | Map, Set | | Symbol | | | +--------------------+ +--------------------+
2. Primitive Data Types
1.
Number- Represents both integer and floating-point numeric values (IEEE 754 64-bit float). Also includes special values:
Infinity,-Infinity, andNaN(Not-a-Number).
let age = 21; let price = 99.95; let invalid = "text" / 2; // Returns NaN2.
String- Represents textual data enclosed within single quotes (
'...'), double quotes ("..."), or backticks for template literals (`...`).
let name = "Rohan"; let message = `Hello, ${name}!`; // Template literal interpolation3.
Boolean- Represents a logical entity with only two possible values:
trueorfalse.
let isLoggedIn = true; let hasPaid = false;4.
Undefined- A variable that has been declared but not yet assigned a value automatically holds the value
undefined.
let x; console.log(x); // Output: undefined5.
Null- Represents the intentional absence of any object value (represents "empty" or "nothing").
let currentUser = null; // Explicitly no user logged in6.
BigInt- Used for arbitrarily large integers that exceed the safe integer limit of Number (
2^53 - 1). Created by appendingnto the integer.
let largeNumber = 9007199254740991123456789n;7.
Symbol- Represents a unique, immutable identifier, commonly used to create private or collision-resistant object keys.
let id1 = Symbol("id"); let id2 = Symbol("id"); console.log(id1 === id2); // false (each Symbol is globally unique)
3. Non-Primitive (Reference) Data Types
1.
Object- A collection of key-value pairs used to model complex entities.
let student = { name: "Aman", rollNo: 105, branch: "CSE", greet: function() { console.log("Hello from " + this.name); } };2.
Array- An ordered list/collection of elements (can hold mixed data types).
let subjects = ["Web Tech", "Networks", "Compiler Design", 2026, true]; console.log(subjects[0]); // Output: "Web Tech"3.
Function- Functions in JavaScript are First-Class Objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
function add(a, b) { return a + b; }
4. Checking Data Types using the
typeofOperatorconsole.log(typeof 42); // "number" console.log(typeof "Hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof 100n); // "bigint" console.log(typeof Symbol("key")); // "symbol" console.log(typeof { a: 1 }); // "object" console.log(typeof [1, 2, 3]); // "object" console.log(typeof function() {}); // "function" // Historical JavaScript quirk: console.log(typeof null); // "object" (known legacy bug in JS)
5. Dynamic Typing Example
let dynamicVar = 100; // Currently a Number dynamicVar = "Now a String"; // Now a String dynamicVar = [1, 2, 3]; // Now an Array (Object)- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q4a. What is multithreading in Java? Explain the inter-thread communication with the help of suitable example.20207m
Module III: Basics of Web Programming
View this question on its own page →What is multithreading in Java? Explain the inter-thread communication with the help of suitable example.
Worked SolutionAnswer: Multithreading and Inter-Thread Communication in Java
1. What is Multithreading in Java?
Multithreading is a core Java feature that allows concurrent execution of two or more parts of a program (called threads) to maximize CPU utilization. Each thread represents an independent path of execution sharing common memory space.
Ways to Create Threads in Java:
- By extending the
Threadclass and overridingrun(). - By implementing the
Runnableinterface and passing it to aThreadinstance.
2. What is Inter-Thread Communication?
Inter-thread communication (cooperation) allows synchronized threads to communicate with each other regarding resource availability and state changes, avoiding CPU-wasting polling loops (busy waiting).
Core Methods (Defined in
java.lang.Object):wait(): Causes the current thread to release the monitor lock and wait until another thread invokesnotify()ornotifyAll()on the same object.notify(): Wakes up a single thread waiting on this object's monitor.notifyAll(): Wakes up all threads waiting on this object's monitor.
Rule:
wait(),notify(), andnotifyAll()must always be executed inside asynchronizedblock or method.+-------------------+ +-------------------+ | Producer Thread | | Consumer Thread | +---------+---------+ +---------+---------+ | | | 1. Produces Item | | 2. Puts item in Shared Buffer | | 3. Calls notify() ------------------------------> | (Wakes Up) | 4. Buffer Full -> Calls wait() (Releases Lock) | 5. Consumes Item | | 6. Calls notify() |<--------------------------------------------------| (Wakes Up)
3. Producer-Consumer Implementation Example
// Shared resource buffer class SharedQueue { private int data; private boolean hasData = false; // Producer calls put() public synchronized void put(int value) { while (hasData) { try { wait(); // Wait if buffer already has data } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } this.data = value; this.hasData = true; System.out.println("Produced: " + value); notify(); // Notify the waiting consumer } // Consumer calls get() public synchronized int get() { while (!hasData) { try { wait(); // Wait if buffer is empty } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } this.hasData = false; System.out.println("Consumed: " + data); notify(); // Notify the waiting producer return data; } } // Producer Thread class Producer extends Thread { private SharedQueue queue; Producer(SharedQueue q) { this.queue = q; } public void run() { for (int i = 1; i <= 5; i++) { queue.put(i); try { Thread.sleep(500); } catch (InterruptedException ignored) {} } } } // Consumer Thread class Consumer extends Thread { private SharedQueue queue; Consumer(SharedQueue q) { this.queue = q; } public void run() { for (int i = 1; i <= 5; i++) { queue.get(); try { Thread.sleep(800); } catch (InterruptedException ignored) {} } } } // Main Driver Class public class InterThreadDemo { public static void main(String[] args) { SharedQueue queue = new SharedQueue(); Producer p = new Producer(queue); Consumer c = new Consumer(queue); p.start(); c.start(); } }Sample Output:
Produced: 1 Consumed: 1 Produced: 2 Consumed: 2 Produced: 3 Consumed: 3 ...
4. Key Takeaways
- Thread Synchronization: Prevents race conditions and dirty reads on shared data.
- Lock Release: Calling
wait()immediately releases the object monitor lock, whereasThread.sleep()retains the lock. - Deadlock Prevention: Coordinated
wait()andnotify()calls ensure producer and consumer threads run without starvation or deadlock.
- By extending the
Q4b. Explain different string handling functions and their syntax in Java language.20207m
Module III: Basics of Web Programming
View this question on its own page →Explain different string handling functions and their syntax in Java language.
Worked SolutionAnswer: String Handling Functions in Java
1. Introduction
In Java, a String is an object of the
java.lang.Stringclass that represents a sequence of characters.- Immutability: Once created, a
Stringobject’s content cannot be modified. Any modification creates a newStringobject in memory (utilizing the String Constant Pool). - For mutable strings, Java provides
StringBuffer(thread-safe, synchronized) andStringBuilder(faster, non-synchronized).
2. Core String Handling Methods
Method & Syntax Description Example int length()Returns the number of characters in the string. "Hello".length()5char charAt(int index)Returns the character at the specified 0-based index. "Java".charAt(1)'a'String substring(int begin, int end)Returns substring from begin(inclusive) toend(exclusive)."Technology".substring(0, 4)"Tech"boolean equals(Object obj)Compares character contents for exact equality (case-sensitive). "Cat".equals("cat")falseboolean equalsIgnoreCase(String s)Compares strings ignoring uppercase/lowercase differences. "Cat".equalsIgnoreCase("cat")trueint compareTo(String s)Compares strings lexicographically ( if equal, negative if smaller, positive if greater). "A".compareTo("B")-1String concat(String str)Appends the specified string to the end. "Web".concat("Tech")"WebTech"int indexOf(String str)Returns index of first occurrence of the substring (or -1). "banana".indexOf("na")2int lastIndexOf(String str)Returns index of last occurrence of the substring. "banana".lastIndexOf("na")4String toUpperCase()Converts all characters to uppercase. "java".toUpperCase()"JAVA"String toLowerCase()Converts all characters to lowercase. "HTML".toLowerCase()"html"String trim()Eliminates leading and trailing whitespace. " test ".trim()"test"String replace(char old, char new)Replaces all occurrences of oldwithnew."Java".replace('a', 'o')"Jovo"boolean contains(CharSequence s)Checks if string contains the specified sequence. "PYQDeck".contains("Deck")trueboolean startsWith(String prefix)Checks if string begins with specified prefix. "http://".startsWith("http")trueString[] split(String regex)Splits the string into an array around matches of regex. "a,b,c".split(",")["a", "b", "c"]char[] toCharArray()Converts string into a new character array. "Hi".toCharArray()['H', 'i']
3. Java Code Demonstration
public class StringHandlingDemo { public static void main(String[] args) { String s1 = " Bihar Engineering University "; System.out.println("Original String: '" + s1 + "'"); System.out.println("Length: " + s1.length()); System.out.println("Trimmed: '" + s1.trim() + "'"); System.out.println("Uppercase: " + s1.toUpperCase()); System.out.println("Character at index 7: " + s1.charAt(7)); System.out.println("Substring (1-6): " + s1.substring(1, 6)); System.out.println("Replaced: " + s1.replace("Bihar", "State")); System.out.println("Contains 'Engineering': " + s1.contains("Engineering")); // Splitting string String languages = "HTML,CSS,JavaScript,Java,PHP"; String[] langArray = languages.split(","); System.out.println(" Split Elements:"); for (String lang : langArray) { System.out.println(" - " + lang); } } }
4.
StringvsStringBuffervsStringBuilderParameter StringStringBufferStringBuilderStorage String Constant Pool / Heap Heap Heap Mutability Immutable Mutable Mutable Thread Safety Thread-safe (due to immutability) Thread-safe (Synchronized) Not Thread-safe Performance Slow on frequent concatenation Medium Fastest Introduced Java 1.0 Java 1.0 Java 1.5 - Immutability: Once created, a
Q5. Define session. How it works and what are its advantages?202314m
Module III: Basics of Web Programming
View this question on its own page →Define session. How it works and what are its advantages?
Worked SolutionDefinition
A session is a way to store information about a user on the server across multiple page requests. Since HTTP is stateless, a session gives each visitor a unique session ID so the server can associate later requests with the same user (login state, cart, preferences).
How it works
- Start: the user first visits; the script calls
session_start()(PHP) or creates a session (Express, JSP). - ID generation: the server creates a unique random session ID.
- Cookie sent: the ID is sent to the browser, usually as a cookie (
PHPSESSID), or in the URL if cookies are disabled. - Data stored on the server: values go into
$_SESSIONand are kept in a file, memory, or database, keyed by the ID. - Later requests: the browser returns the ID; the server loads the matching data.
- End: the session ends on logout (
session_destroy()), timeout, or when the browser closes.
<?php session_start(); $_SESSION["user"] = "raiyan"; // page 1 // page 2 session_start(); echo "Logged in as " . $_SESSION["user"]; // logout session_unset(); session_destroy(); ?>Express equivalent:
req.session.user = 'raiyan'usingexpress-session.Advantages
- More secure than cookies: data stays on the server; the client holds only an ID.
- Large storage: no 4 KB limit, and any data type (arrays, objects) can be stored.
- Works across pages: data is available anywhere within the site during the visit.
- Authentication and authorization: keeps users logged in and controls access.
- Automatic expiry: sessions time out, limiting misuse.
- Client-independent data: the user cannot directly edit stored values.
Drawbacks
Uses server memory or storage, needs the ID transmitted safely (use HTTPS, regenerate the ID on login to stop session fixation), and is harder to scale across multiple servers without a shared store such as Redis.
- Start: the user first visits; the script calls
Q5. Write a program in Java to do the following: (a) To swap the two numbers without using the third variable (b) Factorial of a number using recursion202014m
Module III: Basics of Web Programming
View this question on its own page →Write a program in Java to do the following:
(a) To swap the two numbers without using the third variable
(b) Factorial of a number using recursionWorked SolutionAnswer: Java Programs — Number Swapping & Recursive Factorial
Part (a): Swap Two Numbers Without Using a Third Variable
1. Algorithm & Logic
We can swap two numbers without a temporary variable using arithmetic addition/subtraction or bitwise XOR operations:
- Step 1: (Holds sum of both)
- Step 2: (Original value of )
- Step 3: (Original value of )
2. Java Code:
import java.util.Scanner; public class SwapWithoutThirdVariable { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first number (a): "); int a = sc.nextInt(); System.out.print("Enter second number (b): "); int b = sc.nextInt(); System.out.println(" --- Before Swapping ---"); System.out.println("a = " + a + ", b = " + b); // Swapping logic using arithmetic operators a = a + b; b = a - b; a = a - b; System.out.println(" --- After Swapping ---"); System.out.println("a = " + a + ", b = " + b); sc.close(); } }3. Dry Run:
- Initial:
- Line 1 ():
- Line 2 (): ( now holds original )
- Line 3 (): ( now holds original )
- Result: (Swapped successfully!)
Part (b): Factorial of a Number Using Recursion
1. Mathematical Principle & Base Case
2. Java Code:
import java.util.Scanner; public class RecursiveFactorial { // Recursive function to calculate factorial public static long calculateFactorial(int n) { // Base Condition if (n <= 1) { return 1; } // Recursive Call return n * calculateFactorial(n - 1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a non-negative integer: "); int number = sc.nextInt(); if (number < 0) { System.out.println("Factorial is not defined for negative numbers."); } else { long result = calculateFactorial(number); System.out.println("Factorial of " + number + " (" + number + "!) = " + result); } sc.close(); } }3. Recursive Call Stack Trace (For ):
calculateFactorial(4) = 4 * calculateFactorial(3) = 3 * calculateFactorial(2) = 2 * calculateFactorial(1) = 1 (Base case reached) = 2 * 1 = 2 = 3 * 2 = 6 = 4 * 6 = 24 Output: 24
Complete Unified Program
import java.util.Scanner; public class CombinedExamDemo { public static void swap(int a, int b) { System.out.println("Before Swap: a = " + a + ", b = " + b); a = a ^ b; // Bitwise XOR swapping b = a ^ b; a = a ^ b; System.out.println("After Swap: a = " + a + ", b = " + b); } public static long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } public static void main(String[] args) { // Test (a) swap(10, 20); // Test (b) int num = 5; System.out.println("Factorial of " + num + " = " + factorial(num)); } }Q5(a). Discuss the following with respect to JavaScript: Data types, function expression, and this keyword.20249m
Module III: Basics of Web Programming
View this question on its own page →Discuss the following with respect to JavaScript: Data types, function expression, and this keyword.
Worked Solution1. Data types in JavaScript
JavaScript is dynamically typed: a variable's type is decided at runtime and can change.
Primitive types (immutable, stored by value)
Type Example number42,3.14,NaN,Infinitystring"hello",'hi',`template ${x}`booleantrue,falseundefineda declared variable with no value nullintentional "no value" symbolSymbol('id'), a unique identifierbigint123n, for very large integersNon-primitive (reference) type:
object, which includes plain objects{}, arrays[], functions,Date,Map,Set(stored by reference).let a = 10; typeof a; // "number" let b = "text"; typeof b; // "string" let c = null; typeof c; // "object" (historic quirk) let d; typeof d; // "undefined" let e = [1, 2]; typeof e; // "object" (use Array.isArray)2. Function expression
A function expression creates a function inside an expression and assigns it to a variable; the function may be anonymous.
const square = function (n) { // function expression return n * n; }; console.log(square(5)); // 25 const add = (a, b) => a + b; // arrow function expressionDifferences from a function declaration (
function square(n) {...}):Declaration Expression Fully hoisted; can be called before it is defined Not usable before the assignment line runs (variable hoisted, value is not) Always has a name Can be anonymous or named Uses: callbacks (
arr.map(function (x) {...})), IIFEs(function(){ ... })();, closures, and passing functions as values.3. The
thiskeywordthisrefers to the object that is executing the current code; its value depends on how the function is called.Context Value of thisGlobal scope / plain function (non-strict) window(browser) orglobalThis;undefinedin strict modeMethod call obj.method()objConstructor new Person()the newly created object Event handler the element that received the event call,apply,bindthe object explicitly supplied Arrow function inherits thisfrom the enclosing scope (no ownthis)const user = { name: "Raiyan", greet() { console.log("Hi, " + this.name); } // this = user }; user.greet(); // Hi, Raiyan const fn = user.greet; fn(); // this lost: undefined / window.name fn.call({ name: "Ali" }); // Hi, Ali (explicit binding) const timer = { n: 0, start() { setInterval(() => this.n++, 1000); } // arrow keeps this = timer };Q5(b). Compare Servlets and JSP regarding their functionality, advantages, and limitations. In what scenarios would you choose one over the other?20245m
Module III: Basics of Web Programming
View this question on its own page →Compare Servlets and JSP regarding their functionality, advantages, and limitations. In what scenarios would you choose one over the other?
Worked SolutionServlets vs JSP
Servlet: a Java class that runs on a server (servlet container such as Tomcat), receives HTTP requests, and generates responses. It is Java code with HTML embedded in
out.println().JSP (JavaServer Pages): a text page that is HTML with Java embedded (scriptlets, expressions, JSTL, EL). The container translates a JSP into a servlet and compiles it on first request, so JSP is built on servlets.
// Servlet public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); res.getWriter().println("<h1>Hello " + req.getParameter("name") + "</h1>"); } }<%-- JSP --%> <h1>Hello <%= request.getParameter("name") %></h1>Comparison
Basis Servlet JSP Nature Java class with HTML in strings HTML page with Java tags Best for Logic, controllers, processing Presentation, views Ease of writing Harder for UI; markup is hard to edit Easier for designers; natural HTML Compilation Compiled manually Auto-translated and compiled on first request Maintenance Changing HTML needs recompiling Java Edit the page directly Built-in objects Must be obtained explicitly Implicit objects ( request,session,out)Performance Slightly faster on first request First request slower (translation), then equal Advantages and limitations
Servlets
- Advantages: full control over request handling, efficient (one thread per request), platform independent, good for controllers, filters, and APIs.
- Limitations: presentation code is cumbersome and mixes HTML into Java; designers cannot edit pages easily.
JSP
- Advantages: simple and quick UI development, easy for web designers, tag libraries (JSTL) reduce Java code, automatic recompilation.
- Limitations: heavy scriptlet logic makes pages messy and hard to debug and test; not suitable for complex business logic.
When to choose which
- Use Servlets for controllers, request processing, form handling, authentication, file upload, REST endpoints, and business logic.
- Use JSP for pages that mostly display dynamic data (views, reports, templates).
- Best practice (MVC): servlet as controller, JSP as view, JavaBeans/services as the model. The servlet processes the request, then forwards to a JSP:
request.getRequestDispatcher("result.jsp").forward(req, res);
Q5a. Describe how the following features of Java relate to the behavior of accessor and mutator methods: (i) Fields (ii) Local variables (iii) Parameters (iv) Return values (v) Visibility modifiers Illustrate each with brief code samples.20197m
Module III: Basics of Web Programming
View this question on its own page →Describe how the following features of Java relate to the behavior of accessor and mutator methods:
(i) Fields
(ii) Local variables
(iii) Parameters
(iv) Return values
(v) Visibility modifiersIllustrate each with brief code samples.
Worked SolutionAnswer: Relationship of Java Language Features with Accessor and Mutator Methods
1. Introduction to Accessor and Mutator Methods
In Java Object-Oriented Programming, Encapsulation is achieved by keeping class data hidden and providing controlled access through:
- Accessor Methods (Getters): Public methods that retrieve/read the internal state of an object without modifying it.
- Mutator Methods (Setters): Public methods that modify/update the internal state of an object, often performing data validation.
[ External Caller ] ---> getAge() [Accessor] ---> Reads (Returns field value) ---> setAge(21) [Mutator] ---> Validates & Updates Private Field
2. Detailed Relationship with Java Features
(i) Fields (Instance Variables)
- Role: Fields hold the persistent state and data of the object.
- Relationship: To protect fields from direct unauthorized access or corruption, they are declared
private. Accessors read from these fields, while mutators write to them.
public class Account { private double balance; // Private instance field }
(ii) Local Variables
- Role: Variables declared inside the body of a method that exist only on the call stack for the duration of method execution.
- Relationship: Mutators and accessors use local variables to perform temporary calculations, formatting, or validation checks before updating or returning field values.
public String getFormattedBalance() { String currencySymbol = "Rs. "; // Local variable return currencySymbol + this.balance; }
(iii) Parameters (Formal Arguments)
- Role: Input variables defined in the method signature that receive values passed by the caller.
- Relationship: Mutator methods accept parameters representing the new desired state. The
thiskeyword is used to distinguish the instance field from the method parameter when they share the same name (shadowing).
public void setBalance(double balance) { // 'balance' is a parameter if (balance >= 0) { this.balance = balance; // 'this.balance' is the field; 'balance' is the parameter } }
(iv) Return Values
- Role: The value and data type sent back to the caller when a method completes.
- Relationship:
- Accessors: Must have a non-void return type matching or widening the field's data type (e.g.,
public double getBalance()). - Mutators: Typically have a
voidreturn type, or return abooleanto indicate if the mutation/validation succeeded.
- Accessors: Must have a non-void return type matching or widening the field's data type (e.g.,
public double getBalance() { return this.balance; // Non-void return value }
(v) Visibility Modifiers (
private,public,protected)- Role: Specify access control boundaries and information hiding.
- Relationship:
- Fields: Declared
privateto restrict direct access from outside classes. - Accessors & Mutators: Declared
publicto expose a safe, controlled interface to external callers.
- Fields: Declared
private int age; // Hidden from outside world public int getAge() { ... } // Publicly accessible read public void setAge(int a) { // Publicly accessible validated write if (a > 0 && a < 120) this.age = a; }
3. Comprehensive Integrated Code Example
public class StudentProfile { // (i) & (v) Private Instance Fields private String studentName; private int studentAge; // (iv) & (v) Public Accessor (Getter) with Return Value public String getStudentName() { return this.studentName; } // (iii), (iv) & (v) Public Mutator (Setter) with Parameter public void setStudentName(String studentName) { // (ii) Local variable used for validation boolean isValid = (studentName != null && !studentName.trim().isEmpty()); if (isValid) { this.studentName = studentName.trim(); } } // Accessor for Age public int getStudentAge() { return this.studentAge; } // Mutator for Age with validation logic public boolean setStudentAge(int studentAge) { if (studentAge >= 17 && studentAge <= 60) { this.studentAge = studentAge; return true; // (iv) Boolean return value indicating success } return false; } }Q5b. What is Inheritance? Explain its different types. Write Java program to implement multiple inheritance.20197m
Module III: Basics of Web Programming
View this question on its own page →What is Inheritance? Explain its different types. Write Java program to implement multiple inheritance.
Worked SolutionAnswer: Inheritance Types and Multiple Inheritance Implementation in Java
1. What is Inheritance?
Inheritance is an object-oriented programming feature where a new class (subclass / derived class) acquires the properties, fields, and methods of an existing class (superclass / base class) using the
extendskeyword.- It models an "IS-A" relationship (e.g., Car IS-A Vehicle).
- Enables code reusability and runtime polymorphism (method overriding).
2. Types of Inheritance in Java
1. Single 2. Multilevel 3. Hierarchical +-------+ +-------+ +-------+ | Base | | Grand | | Base | +---+---+ +---+---+ +---+---+ | | | v v +--+--+ +-------+ +-------+ | | |Derived| |Parent | v v +-------+ +---+---+ +----+ +----+ | |Sub1| |Sub2| v +----+ +----+ +-------+ | Child | +-------+- Single Inheritance: A single subclass extends a single superclass.
- Multilevel Inheritance: A class extends a derived class, creating an inheritance chain ().
- Hierarchical Inheritance: Multiple subclasses inherit from a single common superclass.
- Multiple Inheritance: A class inherits from more than one superclass. (Supported in Java through Interfaces, but not through classes).
- Hybrid Inheritance: A combination of two or more types of inheritance.
3. Why Multiple Inheritance is Disallowed in Java with Classes
Java does not support multiple inheritance with classes (
class C extends A, B) to prevent ambiguity known as the "Diamond Problem":+-------+ | ClassA| (defines display()) +---+---+ | +-----+-----+ | | +--v----+ +--v----+ |ClassB | |ClassC | (Both override display()) +--+----+ +--+----+ | | +-----+-----+ | +---v---+ |ClassD | (Which display() should ClassD inherit? Ambiguity!) +-------+Java resolves this cleanly by allowing multiple inheritance only through Interfaces, since interface methods traditionally have no conflicting state.
4. Java Program Implementing Multiple Inheritance via Interfaces
// Interface 1: Backend Server Interface interface BackendEngine { void processData(); void connectDatabase(); } // Interface 2: Frontend UI Interface interface UserInterface { void renderUI(); } // Subclass implementing multiple interfaces class WebApplication implements BackendEngine, UserInterface { private String appName; WebApplication(String name) { this.appName = name; } // Implementing BackendEngine methods @Override public void processData() { System.out.println("[" + appName + "] Processing business logic on server."); } @Override public void connectDatabase() { System.out.println("[" + appName + "] Database connected successfully."); } // Implementing UserInterface methods @Override public void renderUI() { System.out.println("[" + appName + "] Rendering responsive HTML5 interface."); } } // Driver Class public class MultipleInheritanceDemo { public static void main(String[] args) { WebApplication portal = new WebApplication("PYQDeck Portal"); System.out.println("--- Executing WebApplication Capabilities ---"); portal.connectDatabase(); portal.processData(); portal.renderUI(); } }Program Output:
--- Executing WebApplication Capabilities --- [PYQDeck Portal] Database connected successfully. [PYQDeck Portal] Processing business logic on server. [PYQDeck Portal] Rendering responsive HTML5 interface.Q6. Define a class called Fuel_Monitor that will be used to check the amount of fuel that is left over in a vehicle after travelling a certain distance. The class should have instance variables tank capacity to store initial size of the tank and efficiency to store initial efficiency of the vehicle. Also, set the variable fuel_in_tank to zero that is used to store initial fuel in tank. Include a method that returns ini_tank_size, ini_effi and fuel_in_tank. Include a method add_fuel that calculates how much fuel can be filled depending upon the fuel already in the tank and the capacity of the tank. Also, include a method drive_distance that returns how much distance can be travelled with the fuel available in the tank with the efficiency provided. Embed your class in a test program. You should decide which variables should be public, if any.201914m
Module III: Basics of Web Programming
View this question on its own page →Define a class called
Fuel_Monitorthat will be used to check the amount of fuel that is left over in a vehicle after travelling a certain distance. The class should have instance variables tank capacity to store initial size of the tank and efficiency to store initial efficiency of the vehicle. Also, set the variablefuel_in_tankto zero that is used to store initial fuel in tank. Include a method that returnsini_tank_size,ini_effiandfuel_in_tank. Include a methodadd_fuelthat calculates how much fuel can be filled depending upon the fuel already in the tank and the capacity of the tank. Also, include a methoddrive_distancethat returns how much distance can be travelled with the fuel available in the tank with the efficiency provided. Embed your class in a test program. You should decide which variables should be public, if any.Worked SolutionAnswer: Java Implementation — Fuel_Monitor Class and Test Program
1. Class Design & Requirements Breakdown
Encapsulation Strategy:
- Private Instance Variables: All state variables are declared
privateto enforce encapsulation and prevent direct unauthorized alteration.tank_capacity: Total capacity of the fuel tank (in Litres).efficiency: Fuel efficiency / mileage (in Kilometers per Litre).fuel_in_tank: Current amount of fuel available in the tank (initialized to0.0).
Public Methods:
Fuel_Monitor(double capacity, double efficiency): Parameterized constructor to initialize the vehicle specifications.getStatus(): Returns a formatted summary of initial tank size, efficiency, and current fuel.add_fuel(double amount): Safely adds fuel up to maximum capacity and calculates how much fuel was actually filled.drive_distance(double distance): Simulates driving a specified distance, calculates fuel consumed (), updates the remaining fuel in tank, and returns the actual distance travelled.max_drive_distance(): Returns the total distance the vehicle can travel with the current remaining fuel in tank ().
2. Complete Java Code
import java.util.Scanner; class Fuel_Monitor { // Private instance variables for encapsulation private double tank_capacity; // Maximum fuel tank size (Litres) private double efficiency; // Mileage (km per Litre) private double fuel_in_tank; // Current fuel in tank (Litres) // Constructor to initialize tank capacity and vehicle efficiency public Fuel_Monitor(double tank_capacity, double efficiency) { this.tank_capacity = tank_capacity; this.efficiency = efficiency; this.fuel_in_tank = 0.0; // Initialized to zero as specified } // Method to return initial specifications and current fuel status public String getStatus() { return "Initial Tank Size: " + tank_capacity + " L | " + "Initial Efficiency: " + efficiency + " km/L | " + "Current Fuel: " + fuel_in_tank + " L"; } // Accessor methods public double get_ini_tank_size() { return tank_capacity; } public double get_ini_effi() { return efficiency; } public double get_fuel_in_tank() { return fuel_in_tank; } // Method to add fuel to the tank public double add_fuel(double amount) { if (amount <= 0) { System.out.println("Invalid fuel amount. Please enter a positive value."); return 0.0; } double available_space = tank_capacity - fuel_in_tank; if (amount <= available_space) { fuel_in_tank += amount; System.out.println("Added " + amount + " L. Current fuel in tank: " + fuel_in_tank + " L"); return amount; } else { // Fill tank to maximum capacity fuel_in_tank = tank_capacity; System.out.println("Tank Full! Only " + available_space + " L could be filled. (Overflow: " + (amount - available_space) + " L discarded)"); return available_space; } } // Method to drive a given distance and compute leftover fuel public double drive_distance(double distance) { if (distance <= 0) { System.out.println("Distance must be greater than zero."); return 0.0; } // Maximum distance possible with current fuel double max_possible_distance = fuel_in_tank * efficiency; if (distance <= max_possible_distance) { double fuel_consumed = distance / efficiency; fuel_in_tank -= fuel_consumed; System.out.println("Travelled " + distance + " km. Fuel consumed: " + String.format("%.2f", fuel_consumed) + " L."); System.out.println("Fuel left in tank: " + String.format("%.2f", fuel_in_tank) + " L."); return distance; } else { System.out.println("Not enough fuel to travel " + distance + " km!"); System.out.println("Vehicle travelled maximum possible: " + String.format("%.2f", max_possible_distance) + " km before running out of fuel."); fuel_in_tank = 0.0; return max_possible_distance; } } // Method returning max distance possible with current fuel public double get_max_possible_distance() { return fuel_in_tank * efficiency; } } // Test Program public class TestFuelMonitor { public static void main(String[] args) { System.out.println("=== VEHICLE FUEL MONITOR SIMULATION === "); // Create a vehicle with 50 Litre tank capacity and 15 km/L efficiency Fuel_Monitor car = new Fuel_Monitor(50.0, 15.0); // 1. Check initial status System.out.println("1. Initial Status:"); System.out.println(car.getStatus()); System.out.println(); // 2. Add Fuel System.out.println("2. Adding 30 Litres of Fuel:"); car.add_fuel(30.0); System.out.println("Max drivable range now: " + car.get_max_possible_distance() + " km "); // 3. Drive 150 km System.out.println("3. Driving 150 km:"); car.drive_distance(150.0); System.out.println(); // 4. Drive another 200 km System.out.println("4. Driving 200 km:"); car.drive_distance(200.0); System.out.println(); // 5. Try to drive more distance than fuel permits System.out.println("5. Attempting to drive 200 km with remaining fuel:"); car.drive_distance(200.0); System.out.println(); // 6. Overfill test System.out.println("6. Refueling with 60 Litres (Exceeds capacity):"); car.add_fuel(60.0); System.out.println(car.getStatus()); } }
3. Sample Program Output
=== VEHICLE FUEL MONITOR SIMULATION === 1. Initial Status: Initial Tank Size: 50.0 L | Initial Efficiency: 15.0 km/L | Current Fuel: 0.0 L 2. Adding 30 Litres of Fuel: Added 30.0 L. Current fuel in tank: 30.0 L Max drivable range now: 450.0 km 3. Driving 150 km: Travelled 150.0 km. Fuel consumed: 10.00 L. Fuel left in tank: 20.00 L. 4. Driving 200 km: Travelled 200.0 km. Fuel consumed: 13.33 L. Fuel left in tank: 6.67 L. 5. Attempting to drive 200 km with remaining fuel: Not enough fuel to travel 200.0 km! Vehicle travelled maximum possible: 100.00 km before running out of fuel. 6. Refueling with 60 Litres (Exceeds capacity): Tank Full! Only 50.0 L could be filled. (Overflow: 10.0 L discarded) Initial Tank Size: 50.0 L | Initial Efficiency: 15.0 km/L | Current Fuel: 50.0 L- Private Instance Variables: All state variables are declared
Q6(a). How to do pattern Matching in PHP?20237m
Module III: Basics of Web Programming
View this question on its own page →How to do pattern Matching in PHP?
Worked SolutionPattern matching in PHP
PHP does pattern matching mainly with regular expressions, using the PCRE (
preg_*) functions. A pattern is written between delimiters, e.g./pattern/flags.Main functions
Function Purpose preg_match(s, mpreg_match_all(s, $m)Finds all matches preg_replace(r, $s)Replaces matches preg_split(s)Splits a string on a pattern preg_grep(arr)Filters array elements that match Common syntax
.any character,\ddigit,\wword character,\swhitespace^start,$end*0+,+1+,?0 or 1,{n,m}range[abc]character class,(a|b)alternation,( )capture group- Flags:
icase-insensitive,mmultiline
Examples
<?php // 1. Simple match if (preg_match("/web/i", "Web Technology")) { echo "Found"; } // 2. Validate an email $email = "user@example.com"; if (preg_match("/^[\w.+-]+@[\w-]+\.[a-z]{2,}email)) { echo "Valid email"; } // 3. Extract digits with a capture group preg_match("/(\d{3})-(\d{4})/", "Call 555-1234", $m); echo m[2]; // 5551234 // 4. Replace echo preg_replace("/\s+/", " ", "too many spaces"); // too many spaces // 5. Find all numbers preg_match_all("/\d+/", "a1 b22 c333", $all); print_r($all[0]); // 1, 22, 333 ?>Simple (non-regex) matching
For plain text, use
strpos(),str_contains(),str_starts_with(), andstrcmp(). Usefnmatch()for shell-style wildcards.Use
preg_*for flexible patterns and the simple functions when a fixed substring is enough (they are faster).- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q6(a). Describe how to handle form data in PHP. Explain the creation of an HTML form, focusing on the method and action attributes. Discuss retrieving data using the GET and POST methods, and provide a code example demonstrating the form submission process.20247m
Module III: Basics of Web Programming
View this question on its own page →Describe how to handle form data in PHP. Explain the creation of an HTML form, focusing on the method and action attributes. Discuss retrieving data using the GET and POST methods, and provide a code example demonstrating the form submission process.
Worked SolutionHandling form data in PHP
A form collects user input in the browser and sends it to a PHP script on the server, which reads the values through the superglobals
_POST.1. Creating the HTML form
<form action="process.php" method="post"> Name: <input type="text" name="username" required><br> Email: <input type="email" name="email" required><br> <input type="submit" value="Submit"> </form>2. The
actionandmethodattributesaction: the URL of the script that receives and processes the data (process.php). If empty, it submits to the same page.method: how data is sent, eithergetorpost.- Each input's
nameattribute becomes the key in the PHP array.
3. GET vs POST
Basis GET POST Data location Appended to the URL as a query string ( ?username=Ali&email=a@b.com)Sent in the HTTP request body Visibility Visible, bookmarkable Hidden from the URL Size limit Limited by URL length Practically large Security Not for passwords or sensitive data Better, but still needs HTTPS Use Search, filters, idempotent reads Login, registration, uploads, data changes PHP array _POST['name']$_REQUESTholds both GET and POST (and cookie) data.4. Complete example
form.html
<form action="process.php" method="post"> Name: <input type="text" name="username"><br> Email: <input type="email" name="email"><br> <input type="submit" value="Register"> </form>process.php
<?php if ($_SERVER["REQUEST_METHOD"] === "POST") { // 1. Check that fields exist _POST["username"]) ? trim($_POST["username"]) : ""; _POST["email"]) ? trim($_POST["email"]) : ""; // 2. Validate if (email, FILTER_VALIDATE_EMAIL)) { echo "Please enter a valid name and email."; } else { // 3. Sanitize output to prevent XSS echo "Welcome, " . htmlspecialchars($name) . "<br>"; echo "Your email: " . htmlspecialchars($email); } } ?>GET example:
search.php?q=phpis read with_GET['q'] ?? '';Form submission process
- The user fills and submits the form.
- The browser sends a request to the
actionURL using the chosenmethod. - PHP receives the data in
_GET. - The script validates and sanitizes it (
trim,filter_var,htmlspecialchars), then processes it (store in a database, send email). - It returns a response page (or redirects with
header('Location: ...')).
Good practices: always validate on the server (client-side checks can be bypassed), use prepared statements for database queries, and use HTTPS for sensitive data.
Q6(a). Describe the important features of JavaScript and explain its role in developing interactive web pages with a suitable example.20267m
Module III: Basics of Web Programming
View this question on its own page →Describe the important features of JavaScript and explain its role in developing interactive web pages with a suitable example.
Worked SolutionJavaScript: Features and Role in Interactive Web Pages
JavaScript is a high-level programming language commonly used in browsers to make pages dynamic and interactive.
Important features
- Dynamic behaviour: responds to clicks, typing, scrolling and other events.
- DOM manipulation: can create, change or remove HTML elements and CSS classes.
- Form validation: checks input before sending it to a server.
- Asynchronous operations: Promises, async/await and Fetch allow network requests without freezing the page.
- Event-driven programming: event handlers respond to user actions.
- Objects and functions: supports object-oriented and functional programming styles.
- Cross-platform use: runs in modern browsers; server-side JavaScript also runs in environments such as Node.js.
Example:
<label for="name">Name:</label> <input id="name"> <button id="greet">Greet</button> <p id="result"></p> <script> document.querySelector("#greet").addEventListener("click", () => { const name = document.querySelector("#name").value.trim(); document.querySelector("#result").textContent = name ? "Hello, " + name + "!" : "Please enter your name."; }); </script>When the button is clicked, JavaScript reads the input, checks whether it is empty and updates the page without reloading.
Advantages: improves responsiveness, user experience and client-side validation. Limitations: users can disable scripts, browser environments vary, and client-side checks are not a security boundary. Sensitive validation and authorization must also occur on the server.
Conclusion: JavaScript connects user actions to page behaviour and is a core technology for interactive web applications.
Q6(b). Write a PHP script to count the instances of words in string?20237m
Module III: Basics of Web Programming
View this question on its own page →Write a PHP script to count the instances of words in string?
Worked SolutionPHP script to count word instances in a string
Method 1: built-in functions
<?php $text = "the quick brown fox jumps over the lazy dog the end"; // lower-case, then extract words (letters, digits, apostrophes) text), 1); // count occurrences of each word words); // sort by frequency (highest first) arsort($counts); echo "<table border='1'><tr><th>Word</th><th>Count</th></tr>"; foreach (word => $count) { echo "<tr><td>count</td></tr>"; } echo "</table>"; ?>Output (top rows): the → 3, quick → 1, brown → 1, fox → 1, ...
Method 2: manual loop
<?php $text = "to be or not to be"; text)); $count = []; foreach (w) { w, ".,!?;:"); if ($w === "") continue; if (isset(w])) { w]++; } else { w] = 1; } } foreach (w => $c) { echo "c<br>"; } ?>Output: to : 2, be : 2, or : 1, not : 1
Explanation
strtolower()makes counting case-insensitive.str_word_count($s, 1)(orexplode) splits the text into an array of words.array_count_values()builds an associative array of word → frequency; the manual loop does the same with anissetcheck.arsort()orders the result by frequency.
Q6(b). Describe the life cycle of a Java Servlet with a suitable diagram and explain the purpose of its major methods.20267m
Module III: Basics of Web Programming
View this question on its own page →Describe the life cycle of a Java Servlet with a suitable diagram and explain the purpose of its major methods.
Worked SolutionLife Cycle of a Java Servlet
A Servlet is a Java server-side component that handles requests and generates responses, commonly in a web container such as Apache Tomcat.
MermaidDiagramRendering diagram…Life-cycle methods
- Loading and instantiation: the container loads the servlet class and creates an instance.
- init(): called once after instantiation to initialize resources such as configuration or connections.
- service(): invoked for requests; in HttpServlet, it dispatches requests to methods such as doGet() and doPost().
- doGet(): commonly handles retrieval/read requests.
- doPost(): commonly handles submitted data or operations that change server state.
- destroy(): called before the servlet is taken out of service so it can release resources.
Request processing: the container maps a URL to the servlet, creates request and response objects, invokes the appropriate handler, and sends the generated response to the client.
Threading note: containers may process concurrent requests using multiple threads, so shared mutable fields must be handled carefully. Request-specific data should generally remain local to a request.
Conclusion: The servlet container manages the lifecycle, while the servlet's methods initialize resources, process requests and clean up resources.
Q6(b). What is AJAX (Asynchronous JavaScript and XML), and how does it enhance user experience in web applications? Provide a brief code example of an AJAX request and explain how to update a web page with the response.20247m
Module III: Basics of Web Programming
View this question on its own page →What is AJAX (Asynchronous JavaScript and XML), and how does it enhance user experience in web applications? Provide a brief code example of an AJAX request and explain how to update a web page with the response.
Worked SolutionWhat is AJAX?
AJAX (Asynchronous JavaScript and XML) is a technique for exchanging data with the server in the background and updating part of a web page without reloading the whole page. Despite the name, it commonly uses JSON today instead of XML.
Components: HTML/CSS (presentation), DOM (dynamic updates),
XMLHttpRequestorfetch()(asynchronous requests), JavaScript (logic), and JSON/XML (data format).How it improves user experience
- No full page reloads: only the changed part is refreshed, so the app feels fast and smooth.
- Responsiveness: the user keeps working while data loads.
- Less bandwidth: only the needed data travels, not the entire page.
- Live features: auto-suggest search, form validation, chat, notifications, infinite scroll, live scores.
- Desktop-like feel: enables single-page applications (Gmail, Google Maps).
Code example (fetch API)
<button id="load">Load user</button> <div id="result"></div> <script> document.getElementById('load').addEventListener('click', async () => { const box = document.getElementById('result'); box.textContent = 'Loading...'; try { const res = await fetch('https://jsonplaceholder.typicode.com/users/1'); // async request if (!res.ok) throw new Error('HTTP ' + res.status); const user = await res.json(); // parse JSON box.innerHTML = `<b>{user.email}`; // update the page } catch (err) { box.textContent = 'Error: ' + err.message; } }); </script>Classic version with XMLHttpRequest
const xhr = new XMLHttpRequest(); xhr.open('GET', 'data.php?id=1', true); // true = asynchronous xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById('result').innerHTML = xhr.responseText; } }; xhr.send();How the page is updated with the response
- An event (click, keypress, timer) triggers a JavaScript function.
- JavaScript sends an asynchronous request to the server (
fetch/XMLHttpRequest). - The server processes it and returns data (JSON, XML, or HTML fragment).
- A callback (or
await) receives the response once it arrives; the page stays usable meanwhile. - JavaScript parses the data (
res.json()) and modifies the DOM (textContent,innerHTML,appendChild) to show it.
Note:
innerHTMLwith untrusted data risks XSS, so prefertextContentor sanitize the data.Q6a. Describe the architecture and components of a Java Servlet.20257m
Module III: Basics of Web Programming
View this question on its own page →Describe the architecture and components of a Java Servlet.
Worked SolutionAnswer: Architecture, Life Cycle, and Components of a Java Servlet
1. What is a Java Servlet?
A Java Servlet is a server-side Java program running inside a Servlet Container (e.g., Apache Tomcat, Jetty, WildFly). It intercepts client requests, executes business logic, interacts with databases, and dynamically generates web responses (HTML, JSON, XML).
+-------------------+ 1. HTTP Request (GET/POST) +---------------------+ | Web Browser | --------------------------------------> | Web Server | | (Client) | <-------------------------------------- | (Apache Tomcat) | +-------------------+ 4. HTTP Response (HTML/JSON) +----------+----------+ | +---------------------v---------------------+ | SERVLET CONTAINER | | | | +-----------------------------------+ | | | Servlet Instance | | | | | | | | - init(ServletConfig config) | | | | - service(req, res) | | | | -> doGet() / doPost() | | | | - destroy() | | | +-----------------------------------+ | +-------------------------------------------+
2. Servlet Life Cycle Methods
The servlet life cycle is entirely managed by the servlet container through three fundamental methods:
[Load & Instantiate] ---> [init()] ---> [service() (doGet / doPost)] ---> [destroy()]- Initialization (
init(ServletConfig config)):- Invoked once when the servlet is first loaded into memory.
- Used for one-time initialization tasks (opening database connections, reading configuration parameters).
- Execution (
service(ServletRequest req, ServletResponse res)):- Invoked for every client request in a separate worker thread.
- For
HttpServlet, theservice()method dispatches the request todoGet(),doPost(),doPut(), ordoDelete()based on the HTTP method.
- Destruction (
destroy()):- Invoked once before the container takes the servlet instance out of service.
- Used to release resources, close database connections, and save state.
3. Major Components of the Servlet Architecture
1.
ServletInterface (jakarta.servlet.Servlet)- The central root interface of all Java servlets. Declares life cycle methods (
init,service,destroy,getServletConfig,getServletInfo).
2.
HttpServletAbstract Class (jakarta.servlet.http.HttpServlet)- Provides an HTTP-specific implementation. Subclassed by developers to handle standard HTTP verbs:
doGet(HttpServletRequest request, HttpServletResponse response)doPost(HttpServletRequest request, HttpServletResponse response)
3.
ServletConfig- Holds initialization parameters and configuration information specific to a single servlet instance defined in
web.xmlor via@WebServlet(initParams={...}).
4.
ServletContext- Represents the broader web application context shared by all servlets in the application.
- Used to store global application-level attributes, communicate between servlets, and access server logs.
5.
HttpServletRequest&HttpServletResponseHttpServletRequest: Encapsulates incoming request data (parameters, headers, cookies, form data, session).HttpServletResponse: Provides methods to set response headers, status codes, cookies, and obtain an output stream (PrintWriterorServletOutputStream) to write content back to the client.
6.
HttpSession- Provides stateful session tracking across multiple HTTP requests for an individual user (e.g., maintaining user login or shopping cart data).
4. Example: Simple HttpServlet Implementation
import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet("/welcome") public class WelcomeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String username = request.getParameter("name"); out.println("<!DOCTYPE html><html><body>"); out.println("<h2>Hello, " + (username != null ? username : "Guest") + "!</h2>"); out.println("</body></html>"); } }- Initialization (
Q6a. What is a constructor in Java? How many types of constructors are there in Java? Explain with examples.20207m
Module III: Basics of Web Programming
View this question on its own page →What is a constructor in Java? How many types of constructors are there in Java? Explain with examples.
Worked SolutionAnswer: Constructors in Java — Types and Examples
1. What is a Constructor in Java?
A Constructor in Java is a special member method invoked automatically at runtime when an instance (object) of a class is created using the
newkeyword. Its primary purpose is to initialize the newly created object's state (instance variables) and allocate necessary resources.+-------------------+ new Student("Rohan", 101) +-----------------------------+ | Client Code | ----------------------------------> | Constructor Invoked | +-------------------+ | Sets name = "Rohan", id=101 | +-----------------------------+Essential Rules for Constructors:
- Name Rule: The constructor name must be identical to the class name.
- No Return Type: It must not have any explicit return type (not even
void). - Modifiers: Cannot be
abstract,static,final, orsynchronized. Access modifiers (public,protected,private, default) are permitted.
2. Types of Constructors in Java
+-----------------------------+ | TYPES OF CONSTRUCTORS | +--------------+--------------+ | +------------------------+------------------------+ | | | v v v +--------------------+ +--------------------+ +--------------------+ | Default / No-Arg | | Parameterized | | Copy Constructor | | Constructor | | Constructor | | (Object Copy) | +--------------------+ +--------------------+ +--------------------+
A. Default / No-Argument Constructor
- If no constructor is defined in a class, the Java compiler automatically inserts a default no-argument constructor that initializes instance variables to default values (
0,null,false). - Programmers can also explicitly define a no-arg constructor to provide default custom values.
class Student { String name; int rollNo; // Explicit No-Argument Constructor Student() { this.name = "Unknown"; this.rollNo = 0; System.out.println("Default/No-Arg Constructor called"); } }
B. Parameterized Constructor
- A constructor that accepts one or more arguments to initialize instance variables with custom values at the time of object instantiation.
class Student { String name; int rollNo; // Parameterized Constructor Student(String name, int rollNo) { this.name = name; this.rollNo = rollNo; System.out.println("Parameterized Constructor called"); } }
C. Copy Constructor
- Java does not have a built-in copy constructor like C++, but programmers create copy constructors by passing an existing object of the same class to initialize a new object with identical attributes.
class Student { String name; int rollNo; // Copy Constructor Student(Student other) { this.name = other.name; this.rollNo = other.rollNo; System.out.println("Copy Constructor called"); } }
3. Comprehensive Code Example (Constructor Overloading & Chaining)
class Book { String title; String author; double price; // 1. No-argument Constructor Book() { this("Untitled", "Anonymous", 0.0); // Constructor chaining using this() } // 2. Parameterized Constructor (2 parameters) Book(String title, String author) { this(title, author, 199.99); } // 3. Parameterized Constructor (3 parameters) Book(String title, String author, double price) { this.title = title; this.author = author; this.price = price; } // 4. Copy Constructor Book(Book other) { this.title = other.title; this.author = other.author; this.price = other.price; } void display() { System.out.println("Title: " + title + " | Author: " + author + " | Price: Rs." + price); } } public class ConstructorDemo { public static void main(String[] args) { Book b1 = new Book(); Book b2 = new Book("Java: Complete Reference", "Herbert Schildt"); Book b3 = new Book("Web Technologies", "Achyut Godbole", 550.0); Book b4 = new Book(b3); // Copy constructor System.out.println(" --- Book Details ---"); b1.display(); b2.display(); b3.display(); b4.display(); } }Output:
--- Book Details --- Title: Untitled | Author: Anonymous | Price: Rs.0.0 Title: Java: Complete Reference | Author: Herbert Schildt | Price: Rs.199.99 Title: Web Technologies | Author: Achyut Godbole | Price: Rs.550.0 Title: Web Technologies | Author: Achyut Godbole | Price: Rs.550.0Q6b. What are Distributed Object Models? Compare CORBA, DCOM, and EJB.20257m
Module III: Basics of Web Programming
View this question on its own page →What are Distributed Object Models? Compare CORBA, DCOM, and EJB.
Worked SolutionAnswer: Distributed Object Models — Comparison of CORBA, DCOM, and EJB
1. What is a Distributed Object Model?
A Distributed Object Model (DOM) is an architectural paradigm in distributed computing where software objects located on different physical machines across a network can communicate and invoke methods on one another as if they were residing in the same local memory space.
+-----------------------+ +-----------------------+ | Client System | | Server System | | | | | | [Client Program] | | [Remote Object] | | | | | ^ | | v | | | | | [Stub/Proxy] | | [Skeleton/Adapter] | | | | | ^ | | v | | | | | [ORB / Runtime] | === Network Communication => | [ORB / Runtime] | +-----------------------+ (IIOP / RPC / RMI) +-----------------------+Core Mechanisms:
- Stub (Client Proxy): Marshals method parameters and serializes calls across the network.
- Skeleton / Dispatcher: Unmarshals parameters on the remote server, invokes the actual method, and serializes the return value back.
2. Overview of CORBA, DCOM, and EJB
A. CORBA (Common Object Request Broker Architecture)
- Specification: Defined by the Object Management Group (OMG) as an open vendor-neutral standard.
- Key Feature: Truly platform-independent and language-independent. Interfaces are defined using OMG IDL (Interface Definition Language).
- Communication: Uses an ORB (Object Request Broker) and communication protocol IIOP (Internet Inter-ORB Protocol).
B. DCOM (Distributed Component Object Model)
- Specification: Developed by Microsoft as a network extension of COM (Component Object Model).
- Key Feature: Deeply integrated into Windows OS; uses Microsoft RPC (Object RPC).
- Limitation: Windows-centric and proprietary, with limited cross-platform interoperability.
C. EJB (Enterprise JavaBeans)
- Specification: Developed by Sun Microsystems / Oracle (now part of Jakarta EE).
- Key Feature: Pure Java-centric server-side component architecture for building transactional, secure, scalable enterprise business logic.
- Container Architecture: Runs inside an EJB Container that automatically handles transactions, security, concurrency, connection pooling, and lifecycle.
3. Detailed Comparison Matrix
Parameter CORBA DCOM EJB Governing Body Object Management Group (OMG) Microsoft Sun / Oracle / Jakarta EE Platform Support Platform Independent (Unix, Linux, Windows) Windows Centric (Limited Unix support) Cross-Platform (Any Java-supported OS) Language Support Multi-language (C++, Java, Python, Ada, COBOL) Multi-language on Windows (C++, VB, C#) Java Only Interface Definition OMG IDL (Interface Definition Language) Microsoft IDL (MIDL) Java Interfaces (Local / Remote) Underlying Protocol IIOP (Internet Inter-ORB Protocol) ORPC (Object Remote Procedure Call) RMI / IIOP Enterprise Services Basic CORBA services (Naming, Event, Security) Microsoft MTS / COM+ Full Container Services (JTA, JPA, Security, Pooling) Architecture Model Client-Server with ORB middleware Binary COM components over network Component-Container model Primary Strength Universal vendor & language interoperability High performance on Windows enterprise environments Rapid enterprise development with built-in declarative services Weakness Steep learning curve, complex configuration Windows lock-in, poor firewall traversal Restricted to Java ecosystem
Conclusion
- CORBA is ideal for heterogeneous legacy integration across multiple programming languages and OS platforms.
- DCOM provided high performance in pure Microsoft Windows environments before modern Web APIs.
- EJB remains the enterprise standard for pure Java distributed systems, offering automated transactional and container-managed persistence capabilities.
Q6b. List the applications of object-oriented programming. What is the significance of Java's byte code?20207m
Module III: Basics of Web Programming
View this question on its own page →List the applications of object-oriented programming. What is the significance of Java's byte code?
Worked SolutionAnswer: Applications of OOP and Significance of Java Bytecode
Part 1: Major Applications of Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) organizes software design around data, or objects, and well-defined interfaces rather than functions and sequential logic. Major real-world applications include:
+-----------------------------+ | APPLICATIONS OF OOP | +--------------+--------------+ | +-------------------+--------------------+--------------------+-------------------+ | | | | | v v v v v +---------+ +---------+ +---------+ +---------+ +---------+ | GUI | | Real-time| | Game | | Database| | Web & | | Systems | | Simulators | Engines | | (OODBMS)| | Cloud | +---------+ +---------+ +---------+ +---------+ +---------+- Graphical User Interfaces (GUI) & Windowing Systems:
- GUI frameworks (Java Swing/JavaFX, Android SDK, Qt) model visual components (Windows, Buttons, TextBoxes, Menus) as hierarchical object classes inheriting common event-handling behaviors.
- Real-Time Simulation & Modeling:
- Complex physical systems (aerospace flight simulators, weather modeling, autonomous vehicle simulators) use objects to represent physical entities with state and physics behaviors.
- Game Development & Computer Graphics:
- Game engines (Unreal, Unity) model game worlds, characters, physics bodies, and inventory items through polymorphic classes and component inheritance.
- Enterprise Web & Distributed Cloud Systems:
- Tiered e-commerce platforms and banking applications use OOP principles (encapsulation, abstraction) to model business domains (Users, Accounts, Orders, Transactions) with secure boundaries.
- Object-Oriented Databases (OODBMS):
- Databases like db4o and ObjectDB store complex data types and direct object graphs without requiring relational Object-Relational Mapping (ORM) translation.
- Artificial Intelligence & Expert Systems:
- Models neural networks, knowledge graphs, and decision agents through specialized object hierarchies.
Part 2: Significance of Java's Bytecode
1. What is Bytecode?
Java Bytecode is the highly optimized, platform-independent intermediate instruction set generated by the Java Compiler (
javac). It is stored in binary files with a.classextension and is designed to be executed by the Java Virtual Machine (JVM).Java Source (.java) ---> [ javac ] ---> Bytecode (.class) ---> [ JVM on Windows/Linux/Mac ] ---> CPU
2. Key Significance & Advantages of Bytecode
- Platform Independence ("Write Once, Run Anywhere - WORA"):
- The developer compiles source code once into
.classbytecode. The identical bytecode file can execute on Windows, Linux, macOS, Solaris, or Android without recompilation, provided a compatible JVM is installed.
- The developer compiles source code once into
- Robust Security & Sandboxing:
- Before executing bytecode, the JVM's Bytecode Verifier checks the code for unsafe operations:
- No illegal pointer access or direct hardware memory tampering.
- Type-safety enforcement and stack overflow prevention.
- Array bounds checking.
- Before executing bytecode, the JVM's Bytecode Verifier checks the code for unsafe operations:
- Execution Performance via JIT Compilers:
- Bytecode is not purely interpreted. The JVM's Just-In-Time (JIT) Compiler compiles frequently executed bytecode blocks ("hot spots") into native CPU machine code at runtime, providing execution speeds comparable to C++.
- Polyglot Ecosystem (Multi-Language Support on JVM):
- The JVM only requires valid bytecode. Consequently, multiple modern programming languages (such as Kotlin, Scala, Groovy, and Clojure) compile directly into standard Java bytecode, sharing the entire Java ecosystem and standard libraries.
- Network Efficiency & Compactness:
- Bytecode instructions are compact (often single-byte opcodes), enabling fast transmission over networks (applets, dynamic remote class loaders, microservices).
Summary
- OOP provides modularity, maintainability, and reusability for modeling complex real-world software.
- Java Bytecode is the architectural cornerstone that grants Java its signature cross-platform portability, high security, and performance.
- Graphical User Interfaces (GUI) & Windowing Systems:
Q7. Write a program to display current cursor position of the mouse pointer on an Applet using MouseMotionListener interface.201914m
Module III: Basics of Web Programming
View this question on its own page →Write a program to display current cursor position of the mouse pointer on an Applet using MouseMotionListener interface.
Worked SolutionAnswer: Java Applet Program to Track Mouse Cursor Position
1. Overview
In Java AWT/Applet programming, tracking mouse movement is handled by the
MouseMotionListenerinterface from thejava.awt.eventpackage.The
MouseMotionListenerinterface provides two callback methods:mouseMoved(MouseEvent e): Invoked every time the mouse cursor moves within the Applet component boundaries without buttons pressed.mouseDragged(MouseEvent e): Invoked when the mouse is moved while a mouse button is pressed.
[ User Moves Mouse ] ---> [ MouseEvent Fired ] ---> [ mouseMoved(e) extracts X, Y ] ---> [ repaint() ] ---> [ paint(g) draws text ]
2. Complete Java Applet Code
import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; /* <applet code="MouseTrackerApplet.class" width="500" height="400"> </applet> */ public class MouseTrackerApplet extends Applet implements MouseMotionListener { // Variables to store mouse cursor coordinates and status private int mouseX = 0; private int mouseY = 0; private String statusMsg = "Move the mouse inside this Applet window..."; // Initialization method of Applet life cycle @Override public void init() { // Set Applet background and foreground colors setBackground(new Color(245, 246, 242)); setForeground(new Color(27, 36, 48)); setFont(new Font("SansSerif", Font.BOLD, 14)); // Register the Applet to listen to mouse motion events addMouseMotionListener(this); } // Invoked when the mouse is moved without pressing any button @Override public void mouseMoved(MouseEvent e) { mouseX = e.getX(); // Get current X coordinate mouseY = e.getY(); // Get current Y coordinate statusMsg = "Mouse Moving at: X = " + mouseX + ", Y = " + mouseY; repaint(); // Request JVM to re-render the Applet screen } // Invoked when the mouse is dragged with a button pressed @Override public void mouseDragged(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); statusMsg = "Mouse Dragged at: X = " + mouseX + ", Y = " + mouseY; repaint(); // Request JVM to re-render } // Paint method to render graphics and text on the screen @Override public void paint(Graphics g) { // Display header banner g.setColor(new Color(31, 75, 67)); g.fillRect(20, 20, 460, 40); g.setColor(Color.WHITE); g.drawString("JAVA APPLET MOUSE POSITION TRACKER", 80, 45); // Display current cursor coordinates g.setColor(new Color(178, 58, 46)); g.drawString(statusMsg, 30, 100); // Draw crosshair indicator at current cursor position if (mouseX > 0 && mouseY > 0) { g.setColor(Color.BLUE); g.drawOval(mouseX - 10, mouseY - 10, 20, 20); // Circle around cursor g.drawLine(mouseX - 15, mouseY, mouseX + 15, mouseY); // Horizontal line g.drawLine(mouseX, mouseY - 15, mouseX, mouseY + 15); // Vertical line // Draw small coordinate tooltip near cursor g.setFont(new Font("Monospaced", Font.PLAIN, 11)); g.drawString("(" + mouseX + ", " + mouseY + ")", mouseX + 12, mouseY - 8); } } }
3. HTML Code to Embed the Applet (
index.html)<!DOCTYPE html> <html> <head> <title>Mouse Motion Applet</title> </head> <body> <h2>Java Applet: Real-Time Mouse Pointer Coordinates</h2> <applet code="MouseTrackerApplet.class" width="500" height="400"> Your browser does not support Java Applets. </applet> </body> </html>
4. Execution Steps
- Compile the Applet:
javac MouseTrackerApplet.java - Run using AppletViewer (JDK tool):
(Or openappletviewer MouseTrackerApplet.javaindex.htmlin an applet-compatible browser environment).
5. Method Responsibilities Summary
Method Role init()Configures background color and attaches addMouseMotionListener(this).mouseMoved(MouseEvent e)Extracts using e.getX()ande.getY()when cursor is moving freely, then callsrepaint().mouseDragged(MouseEvent e)Extracts during drag gestures. paint(Graphics g)Draws status text and crosshair graphics using coordinates onto the graphics context.