Web Technology

106609
Back to Web Technology

Module III: Basics of Web Programming

  1. Q1(a). What is scriptlet?20232m

    Module III: Basics of Web Programming

    What is scriptlet?

    View this question on its own page →
    Worked Solution

    A 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 <%@ ... %>.

  2. Q1(c). What are interfaces in JAVA.20232m

    Module III: Basics of Web Programming

    What are interfaces in JAVA.

    View this question on its own page →
    Worked Solution

    An interface in Java is a reference type that declares abstract methods (and constants) without providing a full implementation. A class that implements the 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 default and static methods.
    • Fields are implicitly public static final.
  3. Q1(d). Explain cookies.20232m

    Module III: Basics of Web Programming

    Explain cookies.

    View this question on its own page →
    Worked Solution

    A 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; Secure
    
  4. Q1(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

    Which method is used in JavaScript to send a request to the server asynchronously? (i) fetch() (ii) XMLHttpRequest() (iii) $.get() (iv) send()

    View this question on its own page →
    Worked Solution

    Answer: (i) fetch()

    fetch() is the modern, Promise-based API for asynchronous HTTP requests:

    const res = await fetch('/api/data');
    const data = await res.json();
    

    XMLHttpRequest is the older async mechanism, and $.get() is a jQuery library wrapper. The built-in native method to prefer is fetch().

  5. Q1(e). What is the role of query string in web communication?20232m

    Module III: Basics of Web Programming

    What is the role of query string in web communication?

    View this question on its own page →
    Worked Solution

    The query string is the part of a URL after ? that carries data to the server as name=value pairs joined by &.

    https://example.com/search?q=web+tech&page=2
    

    Role 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.q in 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.

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

    In JavaScript, what is the result of the following expression: typeof null? (i) null (ii) object (iii) undefined (iv) boolean

    View this question on its own page →
    Worked Solution

    Answer: (ii) object

    typeof null returns "object". This is a long-standing bug from the first version of JavaScript, where null was represented with the object type tag, and it was kept for backward compatibility. To test for null, use value === null.

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

    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) EJB

    View this question on its own page →
    Worked Solution

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

  8. Q1(f). What are advantages of a content management system?20232m

    Module III: Basics of Web Programming

    What are advantages of a content management system?

    View this question on its own page →
    Worked Solution

    A Content Management System (CMS) lets users create, edit, organize, and publish web content without writing code (e.g. WordPress, Drupal, Joomla).

    Advantages:

    1. No coding needed: non-technical users can update content through a WYSIWYG editor.
    2. Separation of content and design: themes and templates control layout, so content can be changed independently.
    3. Multi-user workflow: roles, permissions, drafts, and approval before publishing.
    4. Faster development: ready-made plugins and modules for SEO, forms, and e-commerce.
    5. Consistency: one template keeps the whole site uniform.
    6. Easy maintenance: version history, backups, and centralized updates.
    7. Scalability: pages and features can be added easily as the site grows.
  9. 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

    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 rendering

    View this question on its own page →
    Worked Solution

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

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

    Which variable is used to collect form data sent with both the GET and POST methods in PHP? (i) BOTH(ii)_BOTH (ii) _REQUEST (iii) REQUEST(iv)_REQUEST (iv) _BOTH

    View this question on its own page →
    Worked Solution

    Answer: (ii) $_REQUEST (options (ii) and (iii) are identical in the paper).

    REQUEST‘isaPHPsuperglobalthatcollectsdatafrom‘_REQUEST` is a PHP superglobal that collects data from `_GET, POST‘,and‘_POST`, and `_COOKIE. $_BOTH does not exist in PHP.

  11. Budget 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.

    Install Pocketly
  12. Q1(g). Differentiate cookies from session variables.20232m

    Module III: Basics of Web Programming

    Differentiate cookies from session variables.

    View this question on its own page →
    Worked Solution
    Basis 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(), COOKIE‘∣‘sessionstart()‘,‘_COOKIE` | `session_start()`, `_SESSION
  13. Q1(h). Explain Inheritance.20232m

    Module III: Basics of Web Programming

    Explain Inheritance.

    View this question on its own page →
    Worked Solution

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

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

    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()

    View this question on its own page →
    Worked Solution

    Answer: (iv) paint()

    Applet life cycle: init() → start() → paint() → stop() → destroy(). paint(Graphics g) is called right after start() and again whenever the applet must be redrawn (window resized, uncovered, or repaint() called).

  15. Q1(i). What is polymorphism?20232m

    Module III: Basics of Web Programming

    What is polymorphism?

    View this question on its own page →
    Worked Solution

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

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

    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();

    View this question on its own page →
    Worked Solution

    Correct 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 window object represents the global browser window containing the DOM document.

    Example:

    <button onclick="window.print()">Print This Page</button>
    

    Note on other objects:

    • browser is not a standard global DOM API.
    • navigator provides browser metadata (user-agent, geolocation, platform).
    • document represents the HTML document tree, but the print() method resides on the top-level window object.
  17. 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>
      
  18. 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.
  19. Q1g. Which technology is used for server-side scripting? (i) HTML (ii) CSS (iii) JSP (iv) JavaScript20252m

    Module III: Basics of Web Programming

    Which technology is used for server-side scripting?

    (i) HTML
    (ii) CSS
    (iii) JSP
    (iv) JavaScript

    View this question on its own page →
    Worked Solution

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

    1. Client requests a .jsp file.
    2. The web server translates JSP into a Java Servlet (.java).
    3. The servlet is compiled into bytecode (.class) and executed.
    4. The generated HTML response is sent back to the client.
  20. 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
  21. 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

    Which of the following is a client-side scripting language?

    (i) PHP
    (ii) JavaScript
    (iii) JSP
    (iv) Servlet

    View this question on its own page →
    Worked Solution

    Correct 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.
  22. Budget 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.

    Install Pocketly
  23. 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.
  24. 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).
  25. 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

    Which of the following keywords can be used in a subclass to call the constructor of superclass?

    (i) Super
    (ii) This
    (iii) Extent
    (iv) Extends

    View this question on its own page →
    Worked Solution

    Correct Answer: (i) Super (specifically super())

    Explanation:

    • In Java, the super keyword is a reference variable used to refer to immediate parent (superclass) class objects.
    • When used with parentheses as super() or super(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).
  26. 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

    How does the use of cookies help in server-side scripting? Give examples for data stored using cookies.

    View this question on its own page →
    Worked Solution

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

    1. The script sends a Set-Cookie header in its response.
    2. The browser stores the cookie.
    3. The browser sends it back in the Cookie header on every later request to that site.
    4. The script reads it ($_COOKIE in PHP, req.cookies in 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, and SameSite flags.

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

    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.

    View this question on its own page →
    Worked Solution

    Armstrong 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") {
        input=trim(input = trim(_POST["num"]);
    
        if (!ctype_digit($input)) {
            echo "<p>Please enter digits only.</p>";
        } else {
            n=strlen(n      = strlen(input);   // number of digits
            $sum    = 0;
            for (i=0;i = 0; i < n;n; i++) {
                sum+=pow((int)sum += pow((int)input[i],i], n);
            }
    
            if (sum==(int)sum == (int)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:

    1. The form posts the value to the same script (PHP_SELF).
    2. PHP reads it from $_POST['num'] and validates that it contains only digits.
    3. It counts the digits, sums each digit raised to that power, and compares the sum with the original number.
    4. The result is printed below the form, so the answer appears within the submitted page.

    Sample: input 153 → 1 + 125 + 27 = 153 → Armstrong. Input 123 → 1 + 8 + 27 = 36 → not Armstrong.

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

    What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?

    View this question on its own page →
    Worked Solution

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

  29. Q3a. Explain the steps involved in creating and executing a Java program.20207m

    Module III: Basics of Web Programming

    Explain the steps involved in creating and executing a Java program.

    View this question on its own page →
    Worked Solution

    Answer: 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 .java extension. 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 .java source 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:

    1. Loading: Reads .class binary streams and creates the Class object in the JVM Method Area.
    2. 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.
    3. 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:

    1. Interpreter: Reads and executes bytecode instructions line by line (starts quickly).
    2. 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.
    3. 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.java Java Compiler (javac) HelloWorld.class (Bytecode)
    Execution java HelloWorld Java Virtual Machine (java) Console Output / Runtime
  30. 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>
    
  31. Q3b. Explain Java garbage collection mechanism.20207m

    Module III: Basics of Web Programming

    Explain Java garbage collection mechanism.

    View this question on its own page →
    Worked Solution

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

    1. Nullifying a Reference Variable:
      Student s = new Student("Alice");
      s = null; // Original Student object is now eligible for GC
      
    2. 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
      
    3. Objects Created Inside a Method Scope:
      • Once the method finishes execution, local reference variables popped from the call stack leave created objects unreferenced.
    4. 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

    1. Mark Phase: The GC identifies and marks all live, reachable objects by traversing reference trees starting from GC Roots.
    2. Sweep Phase: The GC sweeps the heap and frees the memory occupied by all unmarked (unreachable) objects.
    3. 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:
      System.gc(); // or Runtime.getRuntime().gc();
      
      (Note: This only requests GC; the JVM decides when to actually execute it).
    • finalize() Method: Historically invoked by the JVM before reclaiming an object's memory (deprecated in modern Java in favor of AutoCloseable / 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
  32. 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)
    
  33. Budget 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.

    Install Pocketly
  34. Q4a. What is multithreading in Java? Explain the inter-thread communication with the help of suitable example.20207m

    Module III: Basics of Web Programming

    What is multithreading in Java? Explain the inter-thread communication with the help of suitable example.

    View this question on its own page →
    Worked Solution

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

    1. By extending the Thread class and overriding run().
    2. By implementing the Runnable interface and passing it to a Thread instance.

    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 invokes notify() or notifyAll() 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(), and notifyAll() must always be executed inside a synchronized block 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

    1. Thread Synchronization: Prevents race conditions and dirty reads on shared data.
    2. Lock Release: Calling wait() immediately releases the object monitor lock, whereas Thread.sleep() retains the lock.
    3. Deadlock Prevention: Coordinated wait() and notify() calls ensure producer and consumer threads run without starvation or deadlock.
  35. Q4b. Explain different string handling functions and their syntax in Java language.20207m

    Module III: Basics of Web Programming

    Explain different string handling functions and their syntax in Java language.

    View this question on its own page →
    Worked Solution

    Answer: String Handling Functions in Java

    1. Introduction

    In Java, a String is an object of the java.lang.String class that represents a sequence of characters.

    • Immutability: Once created, a String object’s content cannot be modified. Any modification creates a new String object in memory (utilizing the String Constant Pool).
    • For mutable strings, Java provides StringBuffer (thread-safe, synchronized) and StringBuilder (faster, non-synchronized).

    2. Core String Handling Methods

    Method & Syntax Description Example
    int length() Returns the number of characters in the string. "Hello".length() →\to 5
    char charAt(int index) Returns the character at the specified 0-based index. "Java".charAt(1) →\to 'a'
    String substring(int begin, int end) Returns substring from begin (inclusive) to end (exclusive). "Technology".substring(0, 4) →\to "Tech"
    boolean equals(Object obj) Compares character contents for exact equality (case-sensitive). "Cat".equals("cat") →\to false
    boolean equalsIgnoreCase(String s) Compares strings ignoring uppercase/lowercase differences. "Cat".equalsIgnoreCase("cat") →\to true
    int compareTo(String s) Compares strings lexicographically (00 if equal, negative if smaller, positive if greater). "A".compareTo("B") →\to -1
    String concat(String str) Appends the specified string to the end. "Web".concat("Tech") →\to "WebTech"
    int indexOf(String str) Returns index of first occurrence of the substring (or -1). "banana".indexOf("na") →\to 2
    int lastIndexOf(String str) Returns index of last occurrence of the substring. "banana".lastIndexOf("na") →\to 4
    String toUpperCase() Converts all characters to uppercase. "java".toUpperCase() →\to "JAVA"
    String toLowerCase() Converts all characters to lowercase. "HTML".toLowerCase() →\to "html"
    String trim() Eliminates leading and trailing whitespace. " test ".trim() →\to "test"
    String replace(char old, char new) Replaces all occurrences of old with new. "Java".replace('a', 'o') →\to "Jovo"
    boolean contains(CharSequence s) Checks if string contains the specified sequence. "PYQDeck".contains("Deck") →\to true
    boolean startsWith(String prefix) Checks if string begins with specified prefix. "http://".startsWith("http") →\to true
    String[] split(String regex) Splits the string into an array around matches of regex. "a,b,c".split(",") →\to ["a", "b", "c"]
    char[] toCharArray() Converts string into a new character array. "Hi".toCharArray() →\to ['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. String vs StringBuffer vs StringBuilder

    Parameter String StringBuffer StringBuilder
    Storage 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
  36. Q5. Define session. How it works and what are its advantages?202314m

    Module III: Basics of Web Programming

    Define session. How it works and what are its advantages?

    View this question on its own page →
    Worked Solution

    Definition

    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

    1. Start: the user first visits; the script calls session_start() (PHP) or creates a session (Express, JSP).
    2. ID generation: the server creates a unique random session ID.
    3. Cookie sent: the ID is sent to the browser, usually as a cookie (PHPSESSID), or in the URL if cookies are disabled.
    4. Data stored on the server: values go into $_SESSION and are kept in a file, memory, or database, keyed by the ID.
    5. Later requests: the browser returns the ID; the server loads the matching data.
    6. 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' using express-session.

    Advantages

    1. More secure than cookies: data stays on the server; the client holds only an ID.
    2. Large storage: no 4 KB limit, and any data type (arrays, objects) can be stored.
    3. Works across pages: data is available anywhere within the site during the visit.
    4. Authentication and authorization: keeps users logged in and controls access.
    5. Automatic expiry: sessions time out, limiting misuse.
    6. 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.

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

    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 recursion

    View this question on its own page →
    Worked Solution

    Answer: 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: a=a+ba = a + b (Holds sum of both)
    • Step 2: b=a−bb = a - b (Original value of aa)
    • Step 3: a=a−ba = a - b (Original value of bb)

    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: a=15,b=25a = 15, b = 25
    • Line 1 (a=a+ba = a + b): a=15+25=40a = 15 + 25 = 40
    • Line 2 (b=a−bb = a - b): b=40−25=15b = 40 - 25 = 15 (bb now holds original aa)
    • Line 3 (a=a−ba = a - b): a=40−15=25a = 40 - 15 = 25 (aa now holds original bb)
    • Result: a=25,b=15a = 25, b = 15 (Swapped successfully!)

    Part (b): Factorial of a Number Using Recursion

    1. Mathematical Principle & Base Case

    Factorial(n)={1if n=0 or n=1(Base Case)n×Factorial(n−1)if n>1(Recursive Step)\text{Factorial}(n) = \begin{cases} 1 & \text{if } n = 0 \text{ or } n = 1 \quad \text{(Base Case)} \\ n \times \text{Factorial}(n - 1) & \text{if } n > 1 \quad \text{(Recursive Step)} \end{cases}

    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 n=4n = 4):

    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));
        }
    }
    
  38. Q5(a). Discuss the following with respect to JavaScript: Data types, function expression, and this keyword.20249m

    Module III: Basics of Web Programming

    Discuss the following with respect to JavaScript: Data types, function expression, and this keyword.

    View this question on its own page →
    Worked Solution

    1. 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
    number 42, 3.14, NaN, Infinity
    string "hello", 'hi', `template ${x}`
    boolean true, false
    undefined a declared variable with no value
    null intentional "no value"
    symbol Symbol('id'), a unique identifier
    bigint 123n, for very large integers

    Non-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 expression
    

    Differences 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 this keyword

    this refers to the object that is executing the current code; its value depends on how the function is called.

    Context Value of this
    Global scope / plain function (non-strict) window (browser) or globalThis; undefined in strict mode
    Method call obj.method() obj
    Constructor new Person() the newly created object
    Event handler the element that received the event
    call, apply, bind the object explicitly supplied
    Arrow function inherits this from the enclosing scope (no own this)
    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
    };
    
  39. 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

    Compare Servlets and JSP regarding their functionality, advantages, and limitations. In what scenarios would you choose one over the other?

    View this question on its own page →
    Worked Solution

    Servlets 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);
  40. 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;
        }
    }
    
  41. 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 (A→B→CA \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.
    
  42. 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
    
  43. Q6(a). How to do pattern Matching in PHP?20237m

    Module III: Basics of Web Programming

    How to do pattern Matching in PHP?

    View this question on its own page →
    Worked Solution

    Pattern 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(p,p, s, m)‘∣Findsthefirstmatch;returns1/0andfills‘m)` | Finds the first match; returns 1/0 and fills `m
    preg_match_all(p,p, s, $m) Finds all matches
    preg_replace(p,p, r, $s) Replaces matches
    preg_split(p,p, s) Splits a string on a pattern
    preg_grep(p,p, arr) Filters array elements that match

    Common syntax

    • . any character, \d digit, \w word character, \s whitespace
    • ^ start, $ end
    • * 0+, + 1+, ? 0 or 1, {n,m} range
    • [abc] character class, (a|b) alternation, ( ) capture group
    • Flags: i case-insensitive, m multiline

    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,}/i",/i", email)) {
        echo "Valid email";
    }
    
    // 3. Extract digits with a capture group
    preg_match("/(\d{3})-(\d{4})/", "Call 555-1234", $m);
    echo m[1].m[1] . 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(), and strcmp(). Use fnmatch() for shell-style wildcards.

    Use preg_* for flexible patterns and the simple functions when a fixed substring is enough (they are faster).

  44. Budget 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.

    Install Pocketly
  45. 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

    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.

    View this question on its own page →
    Worked Solution

    Handling 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 GET‘and‘_GET` and `_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 action and method attributes

    • action: 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, either get or post.
    • Each input's name attribute 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 GET[′name′]‘∣‘_GET['name']` | `_POST['name']

    $_REQUEST holds 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
        name=isset(name  = isset(_POST["username"]) ? trim($_POST["username"]) : "";
        email=isset(email = isset(_POST["email"])    ? trim($_POST["email"])    : "";
    
        // 2. Validate
        if (name===""∣∣!filtervar(name === "" || !filter_var(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=php is read with q=q = _GET['q'] ?? '';

    Form submission process

    1. The user fills and submits the form.
    2. The browser sends a request to the action URL using the chosen method.
    3. PHP receives the data in POST‘/‘_POST`/`_GET.
    4. The script validates and sanitizes it (trim, filter_var, htmlspecialchars), then processes it (store in a database, send email).
    5. 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.

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

    Describe the important features of JavaScript and explain its role in developing interactive web pages with a suitable example.

    View this question on its own page →
    Worked Solution

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

    1. Dynamic behaviour: responds to clicks, typing, scrolling and other events.
    2. DOM manipulation: can create, change or remove HTML elements and CSS classes.
    3. Form validation: checks input before sending it to a server.
    4. Asynchronous operations: Promises, async/await and Fetch allow network requests without freezing the page.
    5. Event-driven programming: event handlers respond to user actions.
    6. Objects and functions: supports object-oriented and functional programming styles.
    7. 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.

  47. Q6(b). Write a PHP script to count the instances of words in string?20237m

    Module III: Basics of Web Programming

    Write a PHP script to count the instances of words in string?

    View this question on its own page →
    Worked Solution

    PHP 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)
    words=strwordcount(strtolower(words = str_word_count(strtolower(text), 1);
    
    // count occurrences of each word
    counts=arraycountvalues(counts = array_count_values(words);
    
    // sort by frequency (highest first)
    arsort($counts);
    
    echo "<table border='1'><tr><th>Word</th><th>Count</th></tr>";
    foreach (countsascounts as word => $count) {
        echo "<tr><td>word</td><td>word</td><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";
    words=explode("",strtolower(words = explode(" ", strtolower(text));
    $count = [];
    
    foreach (wordsaswords as w) {
        w=trim(w = trim(w, ".,!?;:");
        if ($w === "") continue;
        if (isset(count[count[w])) {
            count[count[w]++;
        } else {
            count[count[w] = 1;
        }
    }
    
    foreach (countascount as w => $c) {
        echo "w:w : c<br>";
    }
    ?>
    

    Output: to : 2, be : 2, or : 1, not : 1

    Explanation

    1. strtolower() makes counting case-insensitive.
    2. str_word_count($s, 1) (or explode) splits the text into an array of words.
    3. array_count_values() builds an associative array of word → frequency; the manual loop does the same with an isset check.
    4. arsort() orders the result by frequency.
  48. 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

    Describe the life cycle of a Java Servlet with a suitable diagram and explain the purpose of its major methods.

    View this question on its own page →
    Worked Solution

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

    MermaidDiagram
    Rendering diagram…

    Life-cycle methods

    1. Loading and instantiation: the container loads the servlet class and creates an instance.
    2. init(): called once after instantiation to initialize resources such as configuration or connections.
    3. service(): invoked for requests; in HttpServlet, it dispatches requests to methods such as doGet() and doPost().
    4. doGet(): commonly handles retrieval/read requests.
    5. doPost(): commonly handles submitted data or operations that change server state.
    6. 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.

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

    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.

    View this question on its own page →
    Worked Solution

    What 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), XMLHttpRequest or fetch() (asynchronous requests), JavaScript (logic), and JSON/XML (data format).

    How it improves user experience

    1. No full page reloads: only the changed part is refreshed, so the app feels fast and smooth.
    2. Responsiveness: the user keeps working while data loads.
    3. Less bandwidth: only the needed data travels, not the entire page.
    4. Live features: auto-suggest search, form validation, chat, notifications, infinite scroll, live scores.
    5. 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.name</b><br>{user.name}</b><br>{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

    1. An event (click, keypress, timer) triggers a JavaScript function.
    2. JavaScript sends an asynchronous request to the server (fetch/XMLHttpRequest).
    3. The server processes it and returns data (JSON, XML, or HTML fragment).
    4. A callback (or await) receives the response once it arrives; the page stays usable meanwhile.
    5. JavaScript parses the data (res.json()) and modifies the DOM (textContent, innerHTML, appendChild) to show it.

    Note: innerHTML with untrusted data risks XSS, so prefer textContent or sanitize the data.

  50. Q6a. Describe the architecture and components of a Java Servlet.20257m

    Module III: Basics of Web Programming

    Describe the architecture and components of a Java Servlet.

    View this question on its own page →
    Worked Solution

    Answer: 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()]
    
    1. 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).
    2. Execution (service(ServletRequest req, ServletResponse res)):
      • Invoked for every client request in a separate worker thread.
      • For HttpServlet, the service() method dispatches the request to doGet(), doPost(), doPut(), or doDelete() based on the HTTP method.
    3. 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. Servlet Interface (jakarta.servlet.Servlet)

    • The central root interface of all Java servlets. Declares life cycle methods (init, service, destroy, getServletConfig, getServletInfo).

    2. HttpServlet Abstract 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.xml or 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 & HttpServletResponse

    • HttpServletRequest: 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 (PrintWriter or ServletOutputStream) 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>");
        }
    }
    
  51. 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

    What is a constructor in Java? How many types of constructors are there in Java? Explain with examples.

    View this question on its own page →
    Worked Solution

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

    1. Name Rule: The constructor name must be identical to the class name.
    2. No Return Type: It must not have any explicit return type (not even void).
    3. Modifiers: Cannot be abstract, static, final, or synchronized. 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.0
    
  52. Q6b. What are Distributed Object Models? Compare CORBA, DCOM, and EJB.20257m

    Module III: Basics of Web Programming

    What are Distributed Object Models? Compare CORBA, DCOM, and EJB.

    View this question on its own page →
    Worked Solution

    Answer: 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.
  53. Q6b. List the applications of object-oriented programming. What is the significance of Java's byte code?20207m

    Module III: Basics of Web Programming

    List the applications of object-oriented programming. What is the significance of Java's byte code?

    View this question on its own page →
    Worked Solution

    Answer: 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   |
    +---------+         +---------+          +---------+          +---------+         +---------+
    
    1. 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.
    2. 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.
    3. Game Development & Computer Graphics:
      • Game engines (Unreal, Unity) model game worlds, characters, physics bodies, and inventory items through polymorphic classes and component inheritance.
    4. 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.
    5. 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.
    6. 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 .class extension 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

    1. Platform Independence ("Write Once, Run Anywhere - WORA"):
      • The developer compiles source code once into .class bytecode. The identical bytecode file can execute on Windows, Linux, macOS, Solaris, or Android without recompilation, provided a compatible JVM is installed.
    2. 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.
    3. 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++.
    4. 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.
    5. 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.
  54. 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.