2019 question paper

Web Technology

22 questions

  1. Q1a. A DNS client is called (i) DNS updater (ii) DNS resolver (iii) DNS handler (iv) None of the above20192m

    Module II: Browser & Apache Web Server Architecture; Common Protocols

    A DNS client is called

    (i) DNS updater
    (ii) DNS resolver
    (iii) DNS handler
    (iv) None of the above

    View this question on its own page →
    Worked Solution

    Correct Answer: (ii) DNS resolver

    Explanation:

    • A DNS client is known as a DNS Resolver (or stub resolver).
    • It runs on client operating systems and applications (e.g., web browsers) to initiate DNS queries, contacting local recursive DNS servers to resolve human-readable domain names (e.g., www.example.com) into IP addresses (e.g., 93.184.216.34).
  2. Q1b. If a server has no clue about where to find the address for a hostname, then (i) server asks to the root server (ii) server asks to its adjacent server (iii) request is not processed (iv) None of the above20192m

    Module II: Browser & Apache Web Server Architecture; Common Protocols

    If a server has no clue about where to find the address for a hostname, then

    (i) server asks to the root server
    (ii) server asks to its adjacent server
    (iii) request is not processed
    (iv) None of the above

    View this question on its own page →
    Worked Solution

    Correct Answer: (i) server asks to the root server

    Explanation:

    • When a recursive DNS server receives a query for a hostname and has no cached record or zone information for it, it initiates the standard hierarchical lookup process by querying one of the 13 logical Root Name Servers (e.g., a.root-servers.net).
    • The root server points the recursive resolver to the authoritative Top-Level Domain (TLD) server (e.g., .com or .org), which in turn directs it to the domain's authoritative name server.
  3. Q1c. Which of the following is not used with text-decoration property? (i) Overline (ii) Underline (iii) Line-through (iv) Inline20192m

    Module I: Introduction to Web Technologies & Architectures

    Which of the following is not used with text-decoration property?

    (i) Overline
    (ii) Underline
    (iii) Line-through
    (iv) Inline

    View this question on its own page →
    Worked Solution

    Correct Answer: (iv) Inline

    Explanation:

    • In CSS, the text-decoration (or text-decoration-line) property accepts values that specify decorative lines added to text:
      • underline: Line under the text.
      • overline: Line above the text.
      • line-through: Strikethrough line across the text.
      • none: Removes any decoration.
    • inline is a value of the CSS display property (display: inline;), not the text-decoration property.
  4. Q1d. Which of the following HTML tags is used to define an internal style sheet? (i) \<script\> (ii) \<css\> (iii) \<style\> (iv) None of the above20192m

    Module I: Introduction to Web Technologies & Architectures

    Which of the following HTML tags is used to define an internal style sheet?

    (i) <script>
    (ii) <css>
    (iii) <style>
    (iv) None of the above

    View this question on its own page →
    Worked Solution

    Correct Answer: (iii) <style>

    Explanation:

    • In HTML, internal (embedded) Cascading Style Sheets are defined inside the <style> tag, placed within the <head> section of the HTML document.
    • <script> is used to embed or reference executable JavaScript code.
    • <css> is not a valid HTML element.

    Example:

    <head>
      <style>
        body {
          background-color: #f5f6f2;
          color: #1b2430;
        }
      </style>
    </head>
    
  5. Q1e. JavaScript code is written inside file having extension (i) .jvs (ii) .JavaScript (iii) .js (iv) .jsc20192m

    Module III: Basics of Web Programming

    JavaScript code is written inside file having extension

    (i) .jvs
    (ii) .JavaScript
    (iii) .js
    (iv) .jsc

    View this question on its own page →
    Worked Solution

    Correct Answer: (iii) .js

    Explanation:

    • External JavaScript source files are saved with the standard .js file extension (e.g., main.js, script.js).
    • They are linked into HTML documents using the <script src="..."> element:
      <script src="script.js"></script>
      
  6. 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

    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 extent

    View this question on its own page →
    Worked Solution

    Correct Answer: (iv) JS can provide programming functionality inside but up to certain extent

    Explanation:

    • JavaScript is described as a "lightweight" language because:
      1. It has a small memory footprint and does not require complex local compilation or binaries before execution.
      2. It has restricted system-level access in the browser sandbox (cannot directly manage OS threads, pointers, or arbitrary disk files).
      3. It executes directly via the browser's lightweight JIT-interpreter engine.
  7. Q1g. Choose the correct HTML tag to make a text bold. (i) \<b\> (ii) \<bold\> (iii) \<bb\> (iv) \<bld\>20192m

    Module I: Introduction to Web Technologies & Architectures

    Choose the correct HTML tag to make a text bold.

    (i) <b>
    (ii) <bold>
    (iii) <bb>
    (iv) <bld>

    View this question on its own page →
    Worked Solution

    Correct Answer: (i) <b>

    Explanation:

    • In HTML, the <b> tag (physical formatting tag) and the <strong> tag (semantic logical tag) are used to format text in bold.
    • Tags like <bold>, <bb>, and <bld> are not valid HTML elements.

    Example:

    <p>This is <b>bold text</b> using the b tag.</p>
    
  8. 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

    What is the fundamental unit of information of writer streams in Java?

    (i) Characters
    (ii) Bytes
    (iii) Files
    (iv) Records

    View this question on its own page →
    Worked Solution

    Correct 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.Writer 16-bit Unicode Characters
    Character Input java.io.Reader 16-bit Unicode Characters
    Byte Output java.io.OutputStream 8-bit Bytes
    Byte Input java.io.InputStream 8-bit Bytes
  9. Q1i. The command to execute a compiled Java program is (i) javac (ii) java (iii) run (iv) execute20192m

    Module III: Basics of Web Programming

    The command to execute a compiled Java program is

    (i) javac
    (ii) java
    (iii) run
    (iv) execute

    View this question on its own page →
    Worked Solution

    Correct Answer: (ii) java

    Explanation:

    • The java command launches the Java Virtual Machine (JVM) to load, verify, and execute compiled .class bytecode files (e.g., java ProgramName).
    • javac is the compiler command used to compile .java source code into bytecode (javac ProgramName.java).
    • run and execute are not standard JDK command-line utilities.
  10. 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

    The Java compiler

    (i) creates executable
    (ii) translates Java source code to byte code
    (iii) creates classes
    (iv) produces Java interpreters

    View this question on its own page →
    Worked Solution

    Correct 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 .class files.
    • 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 (.exe or .out).
  11. Q2a. What, if there is no text between the tags or if a text was omitted by mistake, will it affect the display of the HTML file? Explain with the help of example.20197m

    Module I: Introduction to Web Technologies & Architectures

    What, if there is no text between the tags or if a text was omitted by mistake, will it affect the display of the HTML file? Explain with the help of example.

    View this question on its own page →
    Worked Solution

    Answer: Effect of Empty Tags and Omitted Text in HTML Display

    1. Core Principle of HTML Parsing

    HTML parsers in modern web browsers are designed to be fault-tolerant and permissive. When a browser encounters an HTML tag with no text enclosed between its opening and closing tags (<tag></tag>), or if content is omitted by mistake, it handles it in specific predictable ways depending on the type of element:

                                   +-----------------------------+
                                   |    EMPTY / OMITTED TAGS     |
                                   +--------------+--------------+
                                                  |
                         +------------------------+------------------------+
                         |                                                 |
                         v                                                 v
               +--------------------+                            +--------------------+
               |  Container Elements|                            | Void/Empty Elements|
               |  <p></p>, <b></b>  |                            | <br>, <hr>, <img>  |
               | (Rendered as blank)|                            | (Self-contained)   |
               +--------------------+                            +--------------------+
    

    2. Impact on Webpage Display

    A. Non-Visual / Zero-Dimension Rendering

    • For standard inline and block-level text formatting tags (such as <p></p>, <b></b>, <i></i>, <span></span>, <h1></h1>), having no text inside results in an element with zero inner text content.
    • Inline tags (like <b></b> or <span></span>) take up 0×00 \times 0 pixels on the screen, causing no visible impact or distortion to surrounding text.

    B. Impact on Vertical Spacing and Margins (Block Elements)

    • While empty text tags are invisible, empty block-level elements (like <p></p> or <div></div> or <h1></h1>) still retain their default browser margin and padding rules (unless overridden by CSS).
    • An empty <p></p> may introduce unexpected vertical empty white space (line gaps) between adjacent paragraphs.

    C. Structural and Table Elements

    • An empty table cell <td></td> or table row <tr></tr> may collapse or render as a blank border square, potentially altering column alignment if table styling is not fixed.

    3. Illustrative HTML Example

    <!DOCTYPE html>
    <html>
    <head>
      <title>Empty Tags Test</title>
      <style>
        .highlight { border: 1px dashed red; }
      </style>
    </head>
    <body>
    
      <!-- Example 1: Empty inline bold and italic tags (No effect on text) -->
      <p>This is <b></b> a sample sentence with <i></i> omitted text.</p>
      <!-- Output: "This is a sample sentence with omitted text." (Normal spacing) -->
    
      <!-- Example 2: Empty block tags (Introduces vertical whitespace gap) -->
      <p>Paragraph 1: Introduction to Web Design.</p>
      <p class="highlight"></p> <!-- Empty tag with margins -->
      <p>Paragraph 2: Continuing after empty block.</p>
    
      <!-- Example 3: Empty heading tag -->
      <h2 class="highlight"></h2> <!-- Collapses vertically, zero width -->
    
      <!-- Example 4: Empty table cell -->
      <table border="1">
        <tr>
          <td>Student Name</td>
          <td>Marks</td>
        </tr>
        <tr>
          <td>Rohan Kumar</td>
          <td></td> <!-- Empty data cell: renders as empty box -->
        </tr>
      </table>
    
    </body>
    </html>
    

    4. Key Takeaways

    1. No Fatal Parser Crash: Omitting text inside HTML tags will not throw an error or crash the page rendering.
    2. Invisible Inline Tags: Inline tags without content produce zero visual footprint.
    3. Ghost Spacing: Empty block elements (<p>, <div>, <h1>-<h6>) can produce unwanted vertical spacing due to default user-agent stylesheets.
    4. Best Practice: Remove empty and redundant tags during code cleanup and minification to keep DOM trees light and maintain valid semantic structure.
  12. Q2b. Describe the HTML code required for adding a form to a Web page.20197m

    Module I: Introduction to Web Technologies & Architectures

    Describe the HTML code required for adding a form to a Web page.

    View this question on its own page →
    Worked Solution

    Answer: HTML Code and Elements for Adding a Form to a Web Page

    1. Introduction to HTML Forms

    An HTML Form is a section of a document containing interactive controls used to collect user data (such as login credentials, registration details, feedback, or payment inputs) and send that data to a server for processing.


    2. The <form> Element and Core Attributes

    <form action="/submit-handler.php" method="POST" enctype="multipart/form-data">
      <!-- Form Controls Go Here -->
    </form>
    

    Essential Form Attributes:

    • action: Specifies the destination URL (server script, e.g., PHP, Servlet, API endpoint) where the form data is sent upon submission.
    • method: The HTTP transfer method used to send data:
      • GET: Appends form data to the URL query string (e.g., /search?q=java). Used for idempotent searches (not for passwords/sensitive data).
      • POST: Sends form data in the HTTP request body. Used for secure, large, or state-modifying operations (login, registration, payments).
    • enctype: Defines the MIME encoding type of the data:
      • application/x-www-form-urlencoded (default for text).
      • multipart/form-data (mandatory for file uploads).

    3. Major Form Controls and Input Elements

    Form Element Description Code Example
    Text Input Single-line alphanumeric text box <input type="text" name="fullname" required>
    Password Masks characters with dots/asterisks <input type="password" name="pwd">
    Email Validates email syntax <input type="email" name="useremail">
    Radio Button Selects a single option from a group <input type="radio" name="gender" value="male"> Male
    Checkbox Selects multiple independent options <input type="checkbox" name="skills" value="Java"> Java
    Dropdown List Selectable dropdown menu <select name="country"><option value="IN">India</option></select>
    Textarea Multi-line text entry box <textarea name="comments" rows="4"></textarea>
    File Upload Selects local files for upload <input type="file" name="resume">
    Submit Button Submits the form data <input type="submit" value="Submit Form">
    Reset Button Resets form inputs to defaults <input type="reset" value="Clear">

    4. Comprehensive Working HTML Form Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Student Registration Form</title>
      <style>
        .form-container { width: 420px; padding: 20px; border: 1px solid #ccc; font-family: Arial, sans-serif; }
        .form-group { margin-bottom: 15px; }
        label { display: block; font-weight: bold; margin-bottom: 5px; }
        input[type="text"], input[type="email"], input[type="password"], select, textarea {
          width: 100%; padding: 8px; box-sizing: border-box;
        }
      </style>
    </head>
    <body>
    
    <div class="form-container">
      <h2>Student Registration</h2>
      
      <form action="/register" method="POST" enctype="multipart/form-data">
        
        <!-- Text Input with Label -->
        <div class="form-group">
          <label for="name">Full Name:</label>
          <input type="text" id="name" name="student_name" placeholder="Enter full name" required>
        </div>
    
        <!-- Email Input -->
        <div class="form-group">
          <label for="email">Email Address:</label>
          <input type="email" id="email" name="student_email" placeholder="name@example.com" required>
        </div>
    
        <!-- Password Input -->
        <div class="form-group">
          <label for="password">Password:</label>
          <input type="password" id="password" name="student_password" required>
        </div>
    
        <!-- Radio Buttons -->
        <div class="form-group">
          <label>Gender:</label>
          <input type="radio" id="male" name="gender" value="male">
          <label for="male" style="display:inline;">Male</label>
          <input type="radio" id="female" name="gender" value="female">
          <label for="female" style="display:inline;">Female</label>
        </div>
    
        <!-- Select Dropdown -->
        <div class="form-group">
          <label for="course">Branch / Course:</label>
          <select id="course" name="branch">
            <option value="CSE">Computer Science & Engineering</option>
            <option value="ECE">Electronics & Communication</option>
            <option value="EE">Electrical Engineering</option>
            <option value="ME">Mechanical Engineering</option>
          </select>
        </div>
    
        <!-- Textarea -->
        <div class="form-group">
          <label for="address">Address:</label>
          <textarea id="address" name="student_address" rows="3"></textarea>
        </div>
    
        <!-- Submit & Reset Buttons -->
        <div class="form-group">
          <input type="submit" value="Register Now">
          <input type="reset" value="Reset Form">
        </div>
    
      </form>
    </div>
    
    </body>
    </html>
    
  13. Q3a. What are events? Explain the events used in JavaScript with the help of examples.20197m

    Module III: Basics of Web Programming

    What are events? Explain the events used in JavaScript with the help of examples.

    View this question on its own page →
    Worked Solution

    Answer: 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

    1. Inline HTML Attributes:
      <button onclick="alert('Button Clicked!')">Click Me</button>
      
    2. DOM Object Property:
      const btn = document.getElementById("myBtn");
      btn.onclick = function() { console.log("Clicked"); };
      
    3. 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
    click User clicks on an element btn.addEventListener('click', handleClick)
    dblclick User double-clicks an element box.addEventListener('dblclick', handleDoubleClick)
    mouseover Mouse pointer enters element boundaries card.addEventListener('mouseover', highlight)
    mouseout Mouse pointer leaves element boundaries card.addEventListener('mouseout', unhighlight)
    mousemove Mouse pointer moves over an element canvas.addEventListener('mousemove', draw)

    B. Keyboard Events

    Event Trigger Condition Code Example
    keydown Key is pressed down input.addEventListener('keydown', (e) => console.log(e.key))
    keyup Key is released input.addEventListener('keyup', validate)

    C. Form Events

    Event Trigger Condition Code Example
    submit Form is submitted (can intercept via e.preventDefault()) form.addEventListener('submit', validateForm)
    change Value of an input/select element has changed and lost focus select.addEventListener('change', updateSelection)
    focus Element receives focus input.addEventListener('focus', showHint)
    blur Element loses focus input.addEventListener('blur', hideHint)
    input Value changes in real-time input.addEventListener('input', updateCharCount)

    D. Window / Document Lifecycle Events

    Event Trigger Condition Code Example
    DOMContentLoaded HTML document is fully parsed into DOM (without waiting for images/stylesheets) document.addEventListener('DOMContentLoaded', init)
    load Entire page including all stylesheets, scripts, and images is fully loaded window.addEventListener('load', startApp)
    resize Browser window viewport is resized window.addEventListener('resize', handleResize)
    scroll User 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>
    
  14. Q3b. Explain various data types used in JavaScript with the help of examples.20197m

    Module III: Basics of Web Programming

    Explain various data types used in JavaScript with the help of examples.

    View this question on its own page →
    Worked Solution

    Answer: 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:

    1. Primitive Data Types (Immutable, passed by value)
    2. 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, and NaN (Not-a-Number).
    let age = 21;
    let price = 99.95;
    let invalid = "text" / 2; // Returns NaN
    

    2. String

    • Represents textual data enclosed within single quotes ('...'), double quotes ("..."), or backticks for template literals (`...`).
    let name = "Rohan";
    let message = `Hello, ${name}!`; // Template literal interpolation
    

    3. Boolean

    • Represents a logical entity with only two possible values: true or false.
    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: undefined
    

    5. Null

    • Represents the intentional absence of any object value (represents "empty" or "nothing").
    let currentUser = null; // Explicitly no user logged in
    

    6. BigInt

    • Used for arbitrarily large integers that exceed the safe integer limit of Number (2^53 - 1). Created by appending n to 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 typeof Operator

    console.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)
    
  15. Q4a. What do you understand by working layer in DHTML? Explain with the help of example.20197m

    Module I: Introduction to Web Technologies & Architectures

    What do you understand by working layer in DHTML? Explain with the help of example.

    View this question on its own page →
    Worked Solution

    Answer: Working with Layers in DHTML

    1. What is a "Layer" in DHTML?

    In Dynamic HTML (DHTML), a Layer refers to an independent, positioning-enabled rectangular content container (typically a <div> element styled with CSS positioning) that exists on its own distinct plane above or below other page content.

    Layers enable overlapping content, 3D depth stacking (zz-indexing), dynamic visibility toggling, and animation across the X,YX, Y coordinate plane without requiring full-page reloads.

                      +-----------------------------------+
                      |        Top Layer (Z-Index: 3)     |
                      |     (Dropdown / Modal / Tooltip)  |
                      +-----------------+-----------------+
                                        |
             +--------------------------v------------------------+
             |              Middle Layer (Z-Index: 2)            |
             |                   (Sidebar / Menu)                |
             +--------------------------+------------------------+
                                        |
    +-----------------------------------v-----------------------------------+
    |                        Base Layer (Z-Index: 1)                        |
    |                         (Main Web Page Text)                          |
    +-----------------------------------------------------------------------+
    

    2. Core CSS & DOM Properties Governing DHTML Layers

    1. position: Enables coordinate positioning (absolute, relative, or fixed).
    2. top, left, right, bottom: Specifies exact 2D pixel coordinates of the layer relative to its container or viewport.
    3. z-index: Specifies the 3D stacking order along the Z-axis. Elements with higher integer values render on top of elements with lower values.
    4. visibility & display: Toggles visual appearance (visibility: visible/hidden or display: block/none).
    5. overflow & clip: Controls whether content overflowing the layer's boundaries is clipped or scrollable.

    3. Working Mechanism of DHTML Layers

    A working DHTML layer is realized through three cooperating layers of technology:

    1. HTML: Defines the layer structure (<div id="myLayer">).
    2. CSS: Establishes initial positioning, dimensions, background color, and z-index.
    3. JavaScript: Dynamically alters style coordinates and visibility properties in response to user events (element.style.left, element.style.display).

    4. Complete Working DHTML Layer Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>DHTML Layers Demo</title>
      <style>
        body { font-family: Arial, sans-serif; }
    
        /* Base Layer (Normal Document Flow) */
        .base-content {
          background-color: #ebede7;
          padding: 20px;
          width: 500px;
          border: 1px solid #ccc;
        }
    
        /* Floating Interactive Layer */
        #popupLayer {
          position: absolute;
          top: 80px;
          left: 120px;
          width: 280px;
          padding: 15px;
          background-color: #ffffff;
          border: 2px solid #b23a2e;
          box-shadow: 0 4px 12px rgba(0,0,0,0.25);
          z-index: 100; /* Stacks above base content */
          display: none; /* Initially hidden */
        }
      </style>
    </head>
    <body>
    
      <div class="base-content">
        <h2>Main Webpage Content (Base Layer)</h2>
        <p>This text resides on the base layer of the webpage. DHTML layers can overlay this text dynamically.</p>
        
        <button onclick="toggleLayer()">Toggle Floating Layer</button>
        <button onclick="moveLayer()">Move Layer Right</button>
      </div>
    
      <!-- DHTML Layer -->
      <div id="popupLayer">
        <h3 style="margin-top:0; color:#b23a2e;">Floating DHTML Layer</h3>
        <p>I am an independent layer positioned above the base content using CSS z-index and absolute positioning.</p>
        <button onclick="toggleLayer()">Close Layer</button>
      </div>
    
      <script>
        const layer = document.getElementById("popupLayer");
        let currentLeft = 120;
    
        // Toggle Visibility
        function toggleLayer() {
            if (layer.style.display === "block") {
                layer.style.display = "none";
            } else {
                layer.style.display = "block";
            }
        }
    
        // Dynamic Coordinate Animation
        function moveLayer() {
            if (layer.style.display !== "block") layer.style.display = "block";
            currentLeft += 40;
            layer.style.left = currentLeft + "px"; // Dynamically update X-coordinate
        }
      </script>
    
    </body>
    </html>
    

    5. Applications of DHTML Layers

    • Modal Dialogs and Lightbox Popups
    • Dropdown & Flyout Navigation Menus
    • Floating Tooltips and Context Menus
    • Interactive Draggable Widgets & Games
  16. Q4b. How can you do dragging and dropping data using DHTML? Explain with example.20197m

    Module I: Introduction to Web Technologies & Architectures

    How can you do dragging and dropping data using DHTML? Explain with example.

    View this question on its own page →
    Worked Solution

    Answer: Dragging and Dropping Data Using DHTML / HTML5

    1. Introduction

    Drag and Drop (DnD) is an interactive user interface feature in DHTML/HTML5 that allows a user to click and hold the mouse button over an element, drag it across the screen, and release (drop) it onto a designated target container.

    +-------------------+                                       +-------------------+
    |  Draggable Source |                                       |    Drop Target    |
    |   (Item Box)      |                                       |     (Bucket)      |
    +---------+---------+                                       +---------+---------+
              |                                                           |
              | 1. ondragstart                                            |
              |    (dataTransfer.setData('text', id))                     |
              |==================== [User Drags Item] ===================>|
              |                                                           |
              |                                                           | 2. ondragover
              |                                                           |    (event.preventDefault())
              |                                                           |
              |                                                           | 3. ondrop
              |                                                           |    (dataTransfer.getData('text'))
              v                                                           v
    

    2. The Drag and Drop Event Cycle

    A. Events on the Draggable Source:

    • dragstart: Fires when the user begins dragging the element. Used to populate the dataTransfer payload.
    • drag: Fires continuously while the element is being dragged.
    • dragend: Fires when the drag operation completes (released or cancelled).

    B. Events on the Drop Target:

    • dragenter: Fires when the dragged item enters the drop zone boundary.
    • dragover: Fires continuously while the dragged item hovers over the drop zone. Must call event.preventDefault() to allow dropping.
    • dragleave: Fires when the dragged item leaves the drop zone boundary.
    • drop: Fires when the dragged element is released onto the drop target.

    3. The DataTransfer Object

    The event.dataTransfer object holds the payload transferred during the drag operation:

    • setData(format, data): Sets the drag data and MIME type (e.g., event.dataTransfer.setData("text/plain", e.target.id)).
    • getData(format): Retrieves the stored data during the drop event.

    4. Complete Working DHTML Code Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>DHTML Drag and Drop Demo</title>
      <style>
        body { font-family: Arial, sans-serif; }
        
        .container { display: flex; gap: 30px; margin-top: 20px; }
    
        /* Drop Zone Containers */
        .drop-box {
          width: 220px;
          min-height: 220px;
          padding: 15px;
          border: 2px dashed #5b6472;
          background-color: #f5f6f2;
          border-radius: 8px;
        }
    
        .drop-box.hovered {
          border-color: #b23a2e;
          background-color: #efe9de;
        }
    
        /* Draggable Item */
        .drag-item {
          padding: 12px;
          margin: 8px 0;
          background-color: #1f4b43;
          color: #ffffff;
          font-weight: bold;
          border-radius: 4px;
          cursor: grab;
          text-align: center;
        }
    
        .drag-item:active {
          cursor: grabbing;
          opacity: 0.6;
        }
      </style>
    </head>
    <body>
    
      <h2>DHTML Drag and Drop Data Demo</h2>
      <p>Drag items between Box A and Box B:</p>
    
      <div class="container">
        <!-- Box A -->
        <div id="boxA" class="drop-box" ondragover="allowDrop(event)" ondrop="handleDrop(event)" ondragleave="removeHover(event)">
          <div id="item1" class="drag-item" draggable="true" ondragstart="handleDragStart(event)">
            Item 1: JavaScript
          </div>
          <div id="item2" class="drag-item" draggable="true" ondragstart="handleDragStart(event)">
            Item 2: HTML5 & CSS3
          </div>
        </div>
    
        <!-- Box B -->
        <div id="boxB" class="drop-box" ondragover="allowDrop(event)" ondrop="handleDrop(event)" ondragleave="removeHover(event)">
          <div id="item3" class="drag-item" draggable="true" ondragstart="handleDragStart(event)">
            Item 3: Java Servlets
          </div>
        </div>
      </div>
    
      <script>
        // 1. Drag Start: Store element ID in dataTransfer
        function handleDragStart(event) {
            event.dataTransfer.setData("text/plain", event.target.id);
            event.dataTransfer.effectAllowed = "move";
        }
    
        // 2. Drag Over: Must preventDefault to permit dropping
        function allowDrop(event) {
            event.preventDefault();
            event.currentTarget.classList.add("hovered");
        }
    
        function removeHover(event) {
            event.currentTarget.classList.remove("hovered");
        }
    
        // 3. Drop: Retrieve element and append to new parent
        function handleDrop(event) {
            event.preventDefault();
            event.currentTarget.classList.remove("hovered");
            
            const draggedElementId = event.dataTransfer.getData("text/plain");
            const draggedNode = document.getElementById(draggedElementId);
            
            if (draggedNode && event.currentTarget.classList.contains("drop-box")) {
                event.currentTarget.appendChild(draggedNode);
            }
        }
      </script>
    
    </body>
    </html>
    
  17. 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

    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.

    View this question on its own page →
    Worked Solution

    Answer: 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 this keyword 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 void return type, or return a boolean to indicate if the mutation/validation succeeded.
    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 private to restrict direct access from outside classes.
      • Accessors & Mutators: Declared public to expose a safe, controlled interface to external callers.
    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;
        }
    }
    
  18. Q5b. What is Inheritance? Explain its different types. Write Java program to implement multiple inheritance.20197m

    Module III: Basics of Web Programming

    What is Inheritance? Explain its different types. Write Java program to implement multiple inheritance.

    View this question on its own page →
    Worked Solution

    Answer: 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 extends keyword.

    • 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 |
                             +-------+
    
    1. Single Inheritance: A single subclass extends a single superclass.
    2. Multilevel Inheritance: A class extends a derived class, creating an inheritance chain (ABCA \to B \to C).
    3. Hierarchical Inheritance: Multiple subclasses inherit from a single common superclass.
    4. Multiple Inheritance: A class inherits from more than one superclass. (Supported in Java through Interfaces, but not through classes).
    5. 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.
    
  19. 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

    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.

    View this question on its own page →
    Worked Solution

    Answer: Java Implementation — Fuel_Monitor Class and Test Program

    1. Class Design & Requirements Breakdown

    Encapsulation Strategy:

    • Private Instance Variables: All state variables are declared private to 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 to 0.0).

    Public Methods:

    1. Fuel_Monitor(double capacity, double efficiency): Parameterized constructor to initialize the vehicle specifications.
    2. getStatus(): Returns a formatted summary of initial tank size, efficiency, and current fuel.
    3. add_fuel(double amount): Safely adds fuel up to maximum capacity and calculates how much fuel was actually filled.
    4. drive_distance(double distance): Simulates driving a specified distance, calculates fuel consumed (fuel_used=distanceefficiency\text{fuel\_used} = \frac{\text{distance}}{\text{efficiency}}), updates the remaining fuel in tank, and returns the actual distance travelled.
    5. max_drive_distance(): Returns the total distance the vehicle can travel with the current remaining fuel in tank (fuel_in_tank×efficiency\text{fuel\_in\_tank} \times \text{efficiency}).

    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
    
  20. 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

    Write a program to display current cursor position of the mouse pointer on an Applet using MouseMotionListener interface.

    View this question on its own page →
    Worked Solution

    Answer: Java Applet Program to Track Mouse Cursor Position

    1. Overview

    In Java AWT/Applet programming, tracking mouse movement is handled by the MouseMotionListener interface from the java.awt.event package.

    The MouseMotionListener interface provides two callback methods:

    1. mouseMoved(MouseEvent e): Invoked every time the mouse cursor moves within the Applet component boundaries without buttons pressed.
    2. 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

    1. Compile the Applet:
      javac MouseTrackerApplet.java
      
    2. Run using AppletViewer (JDK tool):
      appletviewer MouseTrackerApplet.java
      
      (Or open index.html in an applet-compatible browser environment).

    5. Method Responsibilities Summary

    Method Role
    init() Configures background color and attaches addMouseMotionListener(this).
    mouseMoved(MouseEvent e) Extracts (X,Y)(X, Y) using e.getX() and e.getY() when cursor is moving freely, then calls repaint().
    mouseDragged(MouseEvent e) Extracts (X,Y)(X, Y) during drag gestures.
    paint(Graphics g) Draws status text and crosshair graphics using coordinates onto the graphics context.
  21. Q8. Write an Applet application which will display colours in list box and a scrolling banner which scrolls from left to right within a browser. When user selects any color from the list, it changes the color of scrolling banner.201914m

    Module III: Basics of Web Programming

    Write an Applet application which will display colours in list box and a scrolling banner which scrolls from left to right within a browser. When user selects any color from the list, it changes the color of scrolling banner.

    View this question on its own page →
    Worked Solution

    Answer: Java Applet Application — Color List Box & Scrolling Banner

    1. Problem Requirements Breakdown

    1. Color List Box (java.awt.List): Displays multiple color names (e.g., Red, Green, Blue, Magenta, Orange) allowing user selection.
    2. Scrolling Banner: A text banner that continuously scrolls horizontally from left to right across the Applet screen using a background Thread (Runnable interface).
    3. Dynamic Color Change (ItemListener): When the user selects a color from the list, the banner's text/fill color dynamically updates to the selected color.
    +-------------------------------------------------------------+
    |  [ Color List Box ]         SCROLLING BANNER TEXT ----->    |
    |  | Red        |             (Updates X position in Thread)  |
    |  | Green      |                                             |
    |  | Blue       |             (Selected color updates text)   |
    |  | Magenta    |                                             |
    +-------------------------------------------------------------+
    

    2. Complete Java Applet Source Code

    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.List;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    
    /*
      <applet code="ColorBannerApplet.class" width="650" height="350">
      </applet>
    */
    public class ColorBannerApplet extends Applet implements Runnable, ItemListener {
        // GUI List Box for selecting colors
        private List colorList;
    
        // Scrolling Banner properties
        private String bannerText = "Welcome to Bihar Engineering University - Web Technology Exam Archive";
        private int bannerX = -300; // Starting X coordinate (left)
        private int bannerY = 220;  // Y coordinate
        private Color bannerColor = Color.RED; // Default banner color
    
        // Animation thread
        private Thread animationThread = null;
        private volatile boolean running = false;
    
        // Applet Initialization
        @Override
        public void init() {
            setLayout(null); // Absolute positioning layout
            setBackground(new Color(245, 246, 242));
    
            // 1. Create and populate the Color List Box
            colorList = new List(5, false); // 5 visible rows, single selection
            colorList.add("Red");
            colorList.add("Green");
            colorList.add("Blue");
            colorList.add("Magenta");
            colorList.add("Orange");
            colorList.add("Dark Teal");
            colorList.add("Black");
    
            // Set position and dimensions of the list box
            colorList.setBounds(30, 60, 140, 110);
            colorList.select(0); // Select 'Red' by default
    
            // Register ItemListener to capture user selection
            colorList.addItemListener(this);
    
            // Add component to Applet
            add(colorList);
        }
    
        // Applet Start: Launch Animation Thread
        @Override
        public void start() {
            if (animationThread == null) {
                running = true;
                animationThread = new Thread(this);
                animationThread.start();
            }
        }
    
        // Animation Loop: Scrolls Banner from Left to Right
        @Override
        public void run() {
            while (running) {
                // Move banner coordinate to the right
                bannerX += 5;
    
                // When the banner scrolls off the right edge, wrap back to the left
                if (bannerX > getWidth()) {
                    bannerX = -gEstimateTextWidth();
                }
    
                repaint(); // Request screen redraw
    
                try {
                    Thread.sleep(60); // Control scrolling speed (approx 16 FPS)
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }
    
        // Rough text width estimation for wrapping
        private int gEstimateTextWidth() {
            return bannerText.length() * 10;
        }
    
        // Applet Stop: Stop Thread cleanly
        @Override
        public void stop() {
            running = false;
            animationThread = null;
        }
    
        // Event Handler for List Box Selection
        @Override
        public void itemStateChanged(ItemEvent e) {
            String selected = colorList.getSelectedItem();
            
            if ("Red".equalsIgnoreCase(selected)) {
                bannerColor = new Color(178, 58, 46);
            } else if ("Green".equalsIgnoreCase(selected)) {
                bannerColor = new Color(34, 139, 34);
            } else if ("Blue".equalsIgnoreCase(selected)) {
                bannerColor = new Color(0, 102, 204);
            } else if ("Magenta".equalsIgnoreCase(selected)) {
                bannerColor = new Color(180, 0, 180);
            } else if ("Orange".equalsIgnoreCase(selected)) {
                bannerColor = new Color(230, 120, 0);
            } else if ("Dark Teal".equalsIgnoreCase(selected)) {
                bannerColor = new Color(31, 75, 67);
            } else if ("Black".equalsIgnoreCase(selected)) {
                bannerColor = Color.BLACK;
            }
    
            repaint(); // Immediately redraw with new color
        }
    
        // Screen Paint Rendering
        @Override
        public void paint(Graphics g) {
            // UI Labels
            g.setColor(new Color(27, 36, 48));
            g.setFont(new Font("SansSerif", Font.BOLD, 15));
            g.drawString("Select Banner Color:", 30, 45);
    
            // Banner Track Area Box
            g.setColor(new Color(235, 237, 231));
            g.fillRect(10, 185, getWidth() - 20, 70);
            g.setColor(new Color(219, 223, 215));
            g.drawRect(10, 185, getWidth() - 20, 70);
    
            // Draw Scrolling Banner
            g.setColor(bannerColor);
            g.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 20));
            g.drawString(bannerText, bannerX, bannerY);
        }
    }
    

    3. HTML Deployment File (banner.html)

    <!DOCTYPE html>
    <html>
    <head>
      <title>Color Banner Applet Demo</title>
    </head>
    <body>
      <h2>Java Applet: Scrolling Banner with Color Selector</h2>
      <applet code="ColorBannerApplet.class" width="650" height="350">
        Java Applets are not supported in your environment.
      </applet>
    </body>
    </html>
    

    4. Lifecycle & Flow Explanation

    1. init(): Creates the List component, populates color names, sets absolute bounds (setBounds), and registers addItemListener(this).
    2. start() / run(): Starts the background thread that continuously increments bannerX by 5 pixels and invokes Thread.sleep(60) to produce smooth left-to-right scrolling.
    3. itemStateChanged(): Triggers immediately when a user clicks any color in the list, maps the selection to a java.awt.Color object, and updates bannerColor.
    4. paint(): Renders the background container and draws the text at dynamic position (bannerX, bannerY) with bannerColor.
  22. Q9. Write short notes on any two of the following: (a) AWT (b) Exception Handling (c) DHTML and HTML (d) API201914m

    Module III: Basics of Web Programming

    Write short notes on any two of the following:

    (a) AWT
    (b) Exception Handling
    (c) DHTML and HTML
    (d) API

    View this question on its own page →
    Worked Solution

    Answer: Short Notes on Core Web & Java Concepts


    (a) AWT (Abstract Window Toolkit)

    AWT (java.awt) is Java's original, platform-dependent Graphical User Interface (GUI) toolkit introduced in JDK 1.0.

                                   +-----------------------------+
                                   |     Component (Base Class)  |
                                   +--------------+--------------+
                                                  |
                         +------------------------+------------------------+
                         |                                                 |
                         v                                                 v
               +--------------------+                            +--------------------+
               |  Basic Controls    |                            |     Container      |
               | Button, Checkbox,  |                            | (Panel, Window,    |
               | TextField, List    |                            |  Frame, Dialog)    |
               +--------------------+                            +--------------------+
    

    Key Architectural Characteristics:

    1. Heavyweight Peer Components: AWT components map directly to native operating system peer widgets (e.g., a Button in AWT creates a Windows button on Windows and a Motif button on Solaris).
    2. Container Hierarchy:
      • Frame: Top-level application window with title bar, border, and control icons.
      • Panel: Nested container used to group and layout UI elements.
    3. Layout Managers: Automatically calculates layout coordinates across different screen resolutions (BorderLayout, FlowLayout, GridLayout, GridBagLayout).
    4. Event Delegation Model: Decouples event sources from event listeners using interfaces like ActionListener, MouseListener, and KeyListener.

    (b) Exception Handling in Java

    Exception Handling in Java is a robust mechanism to intercept, handle, and recover from runtime errors (e.g., NullPointerException, ArithmeticException, IOException, SQLException), ensuring the normal flow of the application does not abruptly crash.

                                   +-----------------------------+
                                   |          Throwable          |
                                   +--------------+--------------+
                                                  |
                         +------------------------+------------------------+
                         |                                                 |
                         v                                                 v
               +--------------------+                            +--------------------+
               |     Exception      |                            |       Error        |
               | (Can be Handled)   |                            | (Unrecoverable OS/ |
               | Checked & Unchecked|                            |  JVM System Fail)  |
               +--------------------+                            +--------------------+
    

    The 5 Core Keywords:

    • try: Encloses code that might throw an exception.
    • catch: Handles the specific thrown exception.
    • finally: Executes cleanup code (closing files/connections) regardless of whether an exception occurred.
    • throw: Explicitly throws a custom or standard exception instance.
    • throws: Declares exceptions a method might throw to caller methods.
    try {
        int result = 50 / 0; // Throws ArithmeticException
    } catch (ArithmeticException e) {
        System.out.println("Error: Cannot divide by zero: " + e.getMessage());
    } finally {
        System.out.println("Cleanup executed regardless of exception.");
    }
    

    (c) Comparison: HTML vs. DHTML

    Parameter HTML (HyperText Markup Language) DHTML (Dynamic HTML)
    Definition Standard static markup language for structuring web pages. Combination of HTML, CSS, JavaScript, and DOM.
    Interactivity Static display of text, images, and links. Rich interactivity, client-side animation, drag-and-drop.
    Server Dependence Requires page refresh/server request to change content. Updates content dynamically in-place without page reload.
    Technologies Pure HTML markup tags (<h1>, <p>, <table>). HTML + CSS Positioning + JavaScript + DOM API.
    Complexity Simple, easy to learn and parse. Moderate to complex scripting logic.

    (d) API (Application Programming Interface)

    An API (Application Programming Interface) is a formal set of defined rules, protocols, data structures, and functions that allows one software application to communicate, exchange data, and interact with another software system.

    [ Client App / Frontend ] <==== (JSON / REST API over HTTP) ====> [ Server API / Database ]
    

    Major Categories of APIs:

    1. Language / Library APIs: Built-in SDK classes (e.g., Java Collections API, Java Stream API, Python math module).
    2. Web APIs (RESTful / GraphQL / SOAP): Network endpoints that exchange structured JSON/XML data over HTTP (e.g., Stripe Payment API, Google Maps API, Weather API).
    3. Operating System APIs: Low-level system routines providing hardware and file access (e.g., Windows Win32 API, POSIX system calls).

    Key Benefits of APIs:

    • Modularity & Reusability: Developers can integrate complex functionality (payments, maps, AI models) without building from scratch.
    • Security & Controlled Access: Exposes only necessary data/endpoints while hiding internal implementation details and database logic.