2020 question paper

Web Technology

20 questions

  1. Q1a. Who is making the Web standards? (i) Mozilla (ii) Microsoft (iii) The World Wide Web Consortium (iv) NVDIA20202m

    Module I: Introduction to Web Technologies & Architectures

    Who is making the Web standards?

    (i) Mozilla
    (ii) Microsoft
    (iii) The World Wide Web Consortium
    (iv) NVDIA

    View this question on its own page →
    Worked Solution

    Correct Answer: (iii) The World Wide Web Consortium (W3C)

    Explanation:

    • The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web, founded in 1994 by Tim Berners-Lee.
    • W3C develops open standards (recommendations) such as HTML, CSS, XML, SVG, and WAI-ARIA to ensure the long-term growth and interoperability of the Web.
    • Mozilla and Microsoft are commercial/non-profit software vendors that build web browsers and participate as members in standards bodies (like W3C and WHATWG).
    • NVIDIA is a semiconductor and GPU hardware company.
  2. Q1b. If you want to align text to the right side of a block element in a cascading style sheet (CSS), then which of...20202m

    Module I: Introduction to Web Technologies & Architectures

    If you want to align text to the right side of a block element in a cascading style sheet (CSS), then which of...

    View this question on its own page →
    Worked Solution

    Correct Answer: text-align: right;

    Explanation:

    • In Cascading Style Sheets (CSS), the text-align property specifies the horizontal alignment of inline content (like text, images, or inline blocks) within a block element or table-cell box.
    • Setting text-align: right; aligns the text flush with the right edge of the containing block element.

    Syntax & Example:

    p {
      text-align: right;
    }
    

    Common text-align Values:

    • left: Aligns text to the left margin (default in LTR languages).
    • right: Aligns text to the right margin.
    • center: Centers the text horizontally.
    • justify: Stretches lines so that every line has equal width.
  3. Q1c. Markup tags tell the Web browser (i) how to organize the page (ii) how to display the page (iii) how to display message box on page (iv) None of the above20202m

    Module I: Introduction to Web Technologies & Architectures

    Markup tags tell the Web browser

    (i) how to organize the page
    (ii) how to display the page
    (iii) how to display message box on page
    (iv) None of the above

    View this question on its own page →
    Worked Solution

    Correct Answer: (ii) how to display the page

    Explanation:

    • Markup tags (HTML tags such as <h1>, <p>, <table>, <img>) are keywords enclosed in angle brackets that instruct the web browser on how to format, structure, and display text, multimedia, and layout elements on the screen.
    • The browser reads markup tags to construct the Document Object Model (DOM) and render the visual page according to the specified semantics and styling.
  4. 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.
  5. Q1e. Which of the following is an advantage of putting presentation information in a separate CSS file rather than in HTML itself? (i) The content becomes easy to manage (ii) Becomes easy to make site for different devices like mobile by making separate CSS files (iii) CSS files are generally cached and therefore decrease server load and network traffic (iv) All of the above20202m

    Module I: Introduction to Web Technologies & Architectures

    Which of the following is an advantage of putting presentation information in a separate CSS file rather than in HTML itself?

    (i) The content becomes easy to manage
    (ii) Becomes easy to make site for different devices like mobile by making separate CSS files
    (iii) CSS files are generally cached and therefore decrease server load and network traffic
    (iv) All of the above

    View this question on its own page →
    Worked Solution

    Correct Answer: (iv) All of the above

    Explanation:

    Separating presentation rules into an external .css file provides several key advantages:

    1. Maintainability & Separation of Concerns (i): HTML structure is decoupled from visual styling, allowing sitewide design changes by editing a single CSS file.
    2. Device Independence & Responsiveness (ii): Enables targeting distinct devices (mobiles, tablets, print) through separate stylesheets or CSS media queries (@media).
    3. Browser Caching & Performance (iii): External CSS files are cached by the browser after the first download, drastically reducing bandwidth consumption, network traffic, and server load on subsequent page requests.

    Therefore, (iv) All of the above is the correct option.

  6. Q1i. What does error 404 or Not Found error while accessing a URL mean? (i) The server could not find the requested URL (ii) Requested HTML file is not available (iii) The path to the interpreter of the script is not valid (iv) The requested HTML file does not have sufficient permissions20202m

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

    What does error 404 or Not Found error while accessing a URL mean?

    (i) The server could not find the requested URL
    (ii) Requested HTML file is not available
    (iii) The path to the interpreter of the script is not valid
    (iv) The requested HTML file does not have sufficient permissions

    View this question on its own page →
    Worked Solution

    Correct Answer: (i) The server could not find the requested URL

    Explanation:

    • The HTTP 404 Not Found status code is a standard client-side error response indicating that the origin web server successfully received the client's request, but could not locate the requested resource (URL/endpoint) on the server.
    • Common causes: Broken/dead links, mistyped URL paths, deleted pages, or missing URL rewrite routing rules.

    Other Related HTTP Status Codes:

    • 401 Unauthorized / 403 Forbidden: The user lacks sufficient permissions to access the resource.
    • 500 Internal Server Error: The server encountered an unexpected error or script interpreter failure.
    • 502 Bad Gateway: An upstream server failed to respond properly.
  7. 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).
  8. Q2a. Explain about domain name, IP address and WWW.20207m

    Module I: Introduction to Web Technologies & Architectures

    Explain about domain name, IP address and WWW.

    View this question on its own page →
    Worked Solution

    Answer: Domain Name, IP Address, and the World Wide Web (WWW)

    1. Introduction

    The internet relies on standardized addressing systems and information retrieval architectures to enable global communication between millions of interconnected computers. IP Addresses, Domain Names, and the World Wide Web (WWW) form the core foundation of this ecosystem.

    +-------------------+      DNS Resolution       +-------------------+
    |    Domain Name    | ------------------------> |    IP Address     |
    | (www.example.com) | <------------------------ |  (93.184.216.34)  |
    +-------------------+                           +---------+---------+
              |                                               |
              |       HTTP/HTTPS Request                      | Connects over
              +-----------------------------------------------> TCP/IP Network
                                                              |
                                                    +---------v---------+
                                                    |    WWW Resource   |
                                                    | (Web Page / HTML) |
                                                    +-------------------+
    

    2. IP Address (Internet Protocol Address)

    An IP address is a unique numerical identifier assigned to every device connected to a computer network that uses the Internet Protocol for communication.

    Key Characteristics:

    1. Addressing & Routing: Acts as a network identifier and location address to deliver packets to their destination.
    2. Versions of IP:
      • IPv4 (32-bit): Formatted as 4 octets separated by dots (e.g., 192.168.1.1). Provides 4.3×109\approx 4.3 \times 10^9 addresses.
      • IPv6 (128-bit): Formatted as 8 groups of hexadecimal digits separated by colons (e.g., 2001:0db8:85a3::8a2e:0370:7334) to overcome IPv4 exhaustion.
    3. Static vs. Dynamic IP:
      • Static IP: Permanent address configured for servers.
      • Dynamic IP: Temporarily leased address assigned by DHCP.

    3. Domain Name

    A Domain Name is a human-readable alias used to access websites without needing to remember numeric IP addresses (e.g., google.com instead of 142.250.190.46).

    Structure of a Domain Name:

    https://  subdomain .  second-level-domain .  top-level-domain (TLD)
              (  www    .       example        .         com        )
    
    • Top-Level Domain (TLD): Generic (.com, .org, .edu) or country-code (.in, .uk, .us).
    • Second-Level Domain (SLD): The organization or brand name (google, wikipedia).
    • Subdomain: Specific section or server (mail.google.com, api.example.com).

    DNS (Domain Name System):

    The global hierarchical database that translates human-friendly domain names into machine-routable IP addresses.


    4. WWW (World Wide Web)

    Invented in 1989 by Tim Berners-Lee at CERN, the World Wide Web (WWW) is an interconnected system of public hypertext documents and multimedia resources accessible over the Internet via the HTTP/HTTPS protocol.

    Core Architectural Pillars of the WWW:

    1. URI/URL (Uniform Resource Locator): Standardized global address to locate any document (e.g., https://www.example.com/index.html).
    2. HTTP/HTTPS: The application-layer communication protocol for exchanging web documents.
    3. HTML (HyperText Markup Language): The standard formatting language used to structure web content and hyperlinks.
    4. Web Browsers & Web Servers: The client software that renders pages and the server software that delivers them.

    5. Summary Comparison

    Concept Nature Function Example
    IP Address Numerical identifier Identifies physical machine on network 142.250.190.46
    Domain Name Human-friendly text name Mapped to IP for user convenience www.google.com
    WWW Global information system Application running on the Internet Web pages, hypermedia, web apps
  9. Q2b. What are logical and physical tags in HTML? What is CSS?20207m

    Module I: Introduction to Web Technologies & Architectures

    What are logical and physical tags in HTML? What is CSS?

    View this question on its own page →
    Worked Solution

    Answer: Physical vs Logical Tags in HTML and Introduction to CSS

    1. Physical vs. Logical Tags in HTML

    HTML tags used for formatting text are historically categorized into Physical Tags and Logical Tags:

                                   +-----------------------------+
                                   |     HTML FORMATTING TAGS    |
                                   +--------------+--------------+
                                                  |
                         +------------------------+------------------------+
                         |                                                 |
                         v                                                 v
               +--------------------+                            +--------------------+
               |   PHYSICAL TAGS    |                            |    LOGICAL TAGS    |
               | (Visual Appearance)|                            | (Semantic Meaning) |
               |  <b>, <i>, <u>     |                            | <strong>, <em>     |
               +--------------------+                            +--------------------+
    

    A. Physical Tags

    • Definition: Physical tags tell the browser strictly how to visually render the enclosed text (its appearance/style) without conveying any semantic meaning, importance, or context.
    • Characteristics: Focused entirely on visual layout; ignored by assistive screen readers in terms of vocal inflection.
    • Examples:
      • <b>Text</b>: Renders text in bold style.
      • <i>Text</i>: Renders text in italicized style.
      • <u>Text</u>: Underlines the text.
      • <s>Text</s> or <strike>: Renders text with a strikethrough line.
      • <tt>Text</tt>: Displays text in fixed-width teletype font.
      • <sub> / <sup>: Subscript and superscript formatting.

    B. Logical Tags (Semantic Tags)

    • Definition: Logical tags describe the semantic meaning, purpose, or structural importance of the enclosed content to the browser, search engines, and screen readers.
    • Characteristics: The browser standardly provides default formatting (e.g., <strong> is bolded, <em> is italicized), but screen readers adjust voice tone and emphasis accordingly.
    • Examples:
      • <strong>Text</strong>: Indicates strong importance or urgency (default rendered as bold).
      • <em>Text</em>: Indicates emphasized stress (default rendered as italic).
      • <code>Text</code>: Defines a snippet of computer code (monospace).
      • <cite>Text</cite>: References the title of a creative work or author.
      • <mark>Text</mark>: Highlights relevant text for reference.
      • <abbr title="World Health Organization">WHO</abbr>: Defines an abbreviation or acronym.

    C. Comparison Table

    Parameter Physical Tags Logical (Semantic) Tags
    Focus Visual appearance and styling Meaning, context, and structural value
    Accessibility (Screen Readers) Treated as normal text without vocal change Read with appropriate vocal stress and emphasis
    SEO Impact Minimal search engine value High value for search engine indexers
    W3C Recommendation Deprecated in modern HTML5 (use CSS instead) Strongly recommended in modern semantic HTML
    Examples <b>, <i>, <u>, <tt>, <big> <strong>, <em>, <code>, <cite>, <abbr>

    2. What is CSS (Cascading Style Sheets)?

    CSS (Cascading Style Sheets) is a style sheet language used to describe the visual presentation, layout, colors, typography, and responsive design of a document written in HTML or XML.

    CSS Rule Syntax:

    /* Selector { Property: Value; } */
    h1 {
      color: #b23a2e;
      font-size: 24px;
      text-align: center;
    }
    

    Three Ways to Apply CSS in HTML:

    1. Inline CSS: Applied directly to an element via the style attribute:
      <p style="color: red; font-size: 14px;">Inline Styled Text</p>
      
    2. Internal (Embedded) CSS: Written inside <style> tags within the <head> section:
      <style>
        body { background-color: #f5f6f2; }
      </style>
      
    3. External CSS (Best Practice): Stored in a separate .css file and linked in <head>:
      <link rel="stylesheet" href="styles.css">
      

    Key Benefits of CSS:

    • Separation of Content and Design: Keeps HTML clean and easy to maintain.
    • Faster Page Load: External stylesheets are cached by browsers.
    • Responsive Layouts: Media queries (@media) allow dynamic adaptation across mobile, tablet, and desktop viewports.
  10. 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
  11. 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
  12. 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.
  13. 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
  14. 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=abb = a - b (Original value of aa)
    • Step 3: a=aba = 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=abb = a - b): b=4025=15b = 40 - 25 = 15 (bb now holds original aa)
    • Line 3 (a=aba = a - b): a=4015=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(n1)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));
        }
    }
    
  15. 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
    
  16. 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.
  17. Q7a. With suitable code segments, illustrate various uses of 'final' keyword. Discuss about anonymous inner classes.20207m

    Module III: Basics of Web Programming

    With suitable code segments, illustrate various uses of 'final' keyword. Discuss about anonymous inner classes.

    View this question on its own page →
    Worked Solution

    Answer: Uses of 'final' Keyword and Anonymous Inner Classes in Java


    Part 1: Various Uses of the 'final' Keyword in Java

    In Java, the final non-access modifier is used to impose restrictions and enforce immutability across three primary programming levels: variables, methods, and classes.

                                   +-----------------------------+
                                   |     USES OF 'final' KEYWORD |
                                   +--------------+--------------+
                                                  |
                         +------------------------+------------------------+
                         |                        |                        |
                         v                        v                        v
               +--------------------+   +--------------------+   +--------------------+
               |   Final Variable   |   |    Final Method    |   |    Final Class     |
               | (Constant / No Re- |   |  (Cannot Override) |   | (Cannot Inherit /  |
               |     assignment)    |   |                    |   |    Subclass)       |
               +--------------------+   +--------------------+   +--------------------+
    

    1. final Variable (Constants)

    • A final variable's value cannot be modified once assigned (acts as a constant).
    • Can be initialized at declaration or inside a constructor (blank final variable).
    class Circle {
        // Final constant
        final double PI = 3.14159265359;
        final double radius; // Blank final variable
    
        Circle(double r) {
            this.radius = r; // Initialized in constructor
        }
    
        void changeValue() {
            // PI = 3.14; // COMPILE ERROR: Cannot assign a value to final variable PI
        }
    }
    

    2. final Method (Prevents Method Overriding)

    • Declaring a method as final prevents subclasses from overriding or altering its core implementation (critical for security and invariant business logic).
    class ParentService {
        // Final method cannot be overridden
        final void authenticateUser(String username, String password) {
            System.out.println("Executing secure internal authentication logic.");
        }
    }
    
    class ChildService extends ParentService {
        // COMPILE ERROR: authenticateUser() in ChildService cannot override authenticateUser() in ParentService
        /*
        void authenticateUser(String username, String password) {
            System.out.println("Trying to bypass authentication");
        }
        */
    }
    

    3. final Class (Prevents Inheritance)

    • A final class cannot be extended by any other class (e.g., java.lang.String, java.lang.System, Wrapper classes).
    final class SecureToken {
        String tokenValue = "XYZ-123";
    }
    
    // COMPILE ERROR: Cannot inherit from final class SecureToken
    // class CustomToken extends SecureToken { }
    

    Part 2: Anonymous Inner Classes in Java

    1. Concept & Definition

    An Anonymous Inner Class in Java is an inner class that has no formal class name and is simultaneously declared and instantiated in a single expression.

    • It is used when you need to override methods of a class or implement an interface for one-time local use, avoiding the overhead of creating a separate .java class file.

    2. Syntax & Implementation Example

    // Interface with a single method
    interface GreetingService {
        void greet(String name);
    }
    
    public class AnonymousInnerClassDemo {
        public static void main(String[] args) {
            
            // Creating and instantiating an Anonymous Inner Class
            GreetingService hindiGreeting = new GreetingService() {
                @Override
                public void greet(String name) {
                    System.out.println("Namaste, " + name + "!");
                }
            };
    
            // Another anonymous instance with different behavior
            GreetingService englishGreeting = new GreetingService() {
                @Override
                public void greet(String name) {
                    System.out.println("Welcome, " + name + "!");
                }
            };
    
            hindiGreeting.greet("Rohan");
            englishGreeting.greet("Rohan");
    
            // Example with Thread / Runnable
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Background worker thread running inside anonymous class.");
                }
            });
            t.start();
        }
    }
    

    3. Key Characteristics of Anonymous Inner Classes:

    1. No Constructor: Since it has no name, it cannot define a constructor.
    2. Access Rules: Can access instance variables of the enclosing class and local variables in scope (provided the local variables are final or effectively final).
    3. Compiled Name: The compiler generates class files with numbering: OuterClassName1.class,OuterClassName1.class`, `OuterClassName2.class.
  18. Q7b. What are the benefits of inheritance? Explain the various forms of inheritance with suitable code segments.20207m

    Module III: Basics of Web Programming

    What are the benefits of inheritance? Explain the various forms of inheritance with suitable code segments.

    View this question on its own page →
    Worked Solution

    Answer: Benefits and Forms of Inheritance in Java

    1. What is Inheritance?

    Inheritance is a fundamental Object-Oriented Programming mechanism where a new class (Subclass / Child Class / Derived Class) derives properties, fields, and behaviors (methods) from an existing class (Superclass / Parent Class / Base Class) using the extends keyword. It models an "IS-A" relationship.


    2. Benefits of Inheritance

    1. Code Reusability: Subclasses automatically inherit existing, tested methods from parent classes without re-writing code.
    2. Runtime Polymorphism: Enables dynamic method dispatch through method overriding (@Override), allowing polymorphic code behavior.
    3. Data Encapsulation & Hierarchy: Organizes classes into clear, logical, and maintainable domain hierarchies (e.g., Vehicle -> Car -> ElectricCar).
    4. Extensibility: Facilitates adding new features to existing software architectures without modifying original parent classes (Open-Closed Principle).

    3. Various Forms of Inheritance in Java

      1. Single         2. Multilevel        3. Hierarchical      4. Multiple (Interfaces)
       +-----+             +-----+               +-----+               +-----+  +-----+
       |  A  |             |  A  |               |  A  |               | I1  |  | I2  |
       +--+--+             +--+--+               +--+--+               +--+--+  +--+--+
          |                   |                     |                     \       /
          v                   v                  +--+--+                   v     v
       +-----+             +-----+               |     |                   +-----+
       |  B  |             |  B  |               v     v                   |  C  |
       +-----+             +--+--+            +-----+ +-----+              +-----+
                              |               |  B  | |  C  |
                              v               +-----+ +-----+
                           +-----+
                           |  C  |
                           +-----+
    

    Form 1: Single Inheritance (ABA \to B)

    • A single subclass inherits from a single superclass.
    class Animal {
        void eat() { System.out.println("Animal eats food."); }
    }
    
    class Dog extends Animal {
        void bark() { System.out.println("Dog barks."); }
    }
    

    Form 2: Multilevel Inheritance (ABCA \to B \to C)

    • A subclass inherits from a derived class, forming an inheritance chain.
    class Vehicle {
        void startEngine() { System.out.println("Engine started."); }
    }
    
    class Car extends Vehicle {
        void drive() { System.out.println("Car is driving on 4 wheels."); }
    }
    
    class ElectricCar extends Car {
        void chargeBattery() { System.out.println("Charging lithium-ion battery."); }
    }
    

    Form 3: Hierarchical Inheritance (ABA \to B and ACA \to C)

    • Multiple subclasses inherit from a single common superclass.
    class Account {
        double balance;
        void showBalance() { System.out.println("Balance: " + balance); }
    }
    
    class SavingsAccount extends Account {
        double interestRate = 4.5;
    }
    
    class CurrentAccount extends Account {
        double overdraftLimit = 50000;
    }
    

    Form 4: Multiple Inheritance (Achieved via Interfaces)

    • Note on Classes: Java does not support multiple inheritance with classes (class C extends A, B) to prevent ambiguity and the "Diamond Problem".
    • Supported via Interfaces: A class can implement multiple interfaces using the implements keyword.
    interface Printable {
        void print();
    }
    
    interface Showable {
        void show();
    }
    
    // Implementing multiple interfaces
    class Document implements Printable, Showable {
        public void print() { System.out.println("Printing document page."); }
        public void show() { System.out.println("Showing document preview."); }
    }
    

    Form 5: Hybrid Inheritance

    • A combination of two or more types of inheritance (e.g., Multilevel + Multiple), implemented in Java using a mix of classes and interfaces.
    interface GPS {
        void navigate();
    }
    
    class Phone {
        void makeCall() { System.out.println("Calling number..."); }
    }
    
    // Hybrid: Extends class Phone and Implements interface GPS
    class SmartPhone extends Phone implements GPS {
        public void navigate() { System.out.println("Navigating via GPS maps."); }
    }
    
  19. Q8. WAP to create a superclass called figure that stores the dimensions of a two-dimensional object. It also defines a method called area () that computes the area of an object. The program derives two subclasses from figure. The first is rectangle and the second is triangle. Each of these subclasses overrides area () so that it returns the area of a rectangle and a triangle respectively.202014m

    Module III: Basics of Web Programming

    WAP to create a superclass called figure that stores the dimensions of a two-dimensional object. It also defines a method called area () that computes the area of an object. The program derives two subclasses from figure. The first is rectangle and the second is triangle. Each of these subclasses overrides area () so that it returns the area of a rectangle and a triangle respectively.

    View this question on its own page →
    Worked Solution

    Answer: Java Program — Figure Hierarchy with Dynamic Method Dispatch

    1. Problem Specification

    • Superclass: Figure
      • Instance variables: dim1, dim2 (dimensions of a 2D geometric object).
      • Method: area() returning double.
    • Subclasses:
      • Rectangle: Overrides area() to compute Length×Breadth=dim1×dim2\text{Length} \times \text{Breadth} = \text{dim1} \times \text{dim2}.
      • Triangle: Overrides area() to compute 12×Base×Height=0.5×dim1×dim2\frac{1}{2} \times \text{Base} \times \text{Height} = 0.5 \times \text{dim1} \times \text{dim2}.
    • Driver Class: Demonstrates Dynamic Method Dispatch (Runtime Polymorphism).
                               +------------------------+
                               |         Figure         |
                               |------------------------|
                               | double dim1, dim2      |
                               | double area()          |
                               +-----------+------------+
                                           |
                         +-----------------+-----------------+
                         |                                   |
                         v                                   v
                 +---------------+                   +---------------+
                 |   Rectangle   |                   |   Triangle    |
                 |---------------|                   |---------------|
                 | double area() |                   | double area() |
                 | (dim1 * dim2) |                   | (0.5*dim1*dim2|
                 +---------------+                   +---------------+
    

    2. Complete Java Program

    // Superclass Figure
    class Figure {
        double dim1;
        double dim2;
    
        // Parameterized constructor to initialize dimensions
        Figure(double dim1, double dim2) {
            this.dim1 = dim1;
            this.dim2 = dim2;
        }
    
        // Base area method (to be overridden by subclasses)
        double area() {
            System.out.println("Area for generic Figure is undefined.");
            return 0;
        }
    }
    
    // Subclass Rectangle overriding area()
    class Rectangle extends Figure {
        Rectangle(double length, double breadth) {
            super(length, breadth); // Pass dimensions to superclass
        }
    
        // Overriding area() for rectangle: length * breadth
        @Override
        double area() {
            System.out.println("Calculating Area of Rectangle:");
            return dim1 * dim2;
        }
    }
    
    // Subclass Triangle overriding area()
    class Triangle extends Figure {
        Triangle(double base, double height) {
            super(base, height); // Pass dimensions to superclass
        }
    
        // Overriding area() for triangle: 1/2 * base * height
        @Override
        double area() {
            System.out.println("Calculating Area of Triangle:");
            return 0.5 * dim1 * dim2;
        }
    }
    
    // Driver Class to test polymorphism
    public class FigureAreaDemo {
        public static void main(String[] args) {
            // Instantiate specific shape objects
            Figure genericFig = new Figure(10, 10);
            Rectangle rect = new Rectangle(12.0, 8.0);
            Triangle tri = new Triangle(10.0, 6.0);
    
            // Reference variable of superclass Figure
            Figure figRef;
    
            System.out.println("========================================");
            System.out.println("   DYNAMIC METHOD DISPATCH DEMO");
            System.out.println("========================================
    ");
    
            // 1. Superclass reference pointing to Rectangle object
            figRef = rect;
            System.out.println("Rectangle Dimensions: [Length = " + rect.dim1 + ", Breadth = " + rect.dim2 + "]");
            System.out.println("Computed Area = " + figRef.area() + " sq units
    ");
    
            // 2. Superclass reference pointing to Triangle object
            figRef = tri;
            System.out.println("Triangle Dimensions: [Base = " + tri.dim1 + ", Height = " + tri.dim2 + "]");
            System.out.println("Computed Area = " + figRef.area() + " sq units
    ");
    
            // 3. Superclass reference pointing to generic Figure object
            figRef = genericFig;
            System.out.println("Generic Figure Area = " + figRef.area());
        }
    }
    

    3. Sample Output

    ========================================
       DYNAMIC METHOD DISPATCH DEMO
    ========================================
    
    Rectangle Dimensions: [Length = 12.0, Breadth = 8.0]
    Calculating Area of Rectangle:
    Computed Area = 96.0 sq units
    
    Triangle Dimensions: [Base = 10.0, Height = 6.0]
    Calculating Area of Triangle:
    Computed Area = 30.0 sq units
    
    Generic Figure Area = Area for generic Figure is undefined.
    0.0
    

    4. Key OOP Concepts Demonstrated

    1. Inheritance (extends & super): The subclasses inherit fields dim1 and dim2 and pass values using super(dim1, dim2).
    2. Method Overriding (@Override): Subclasses provide specific implementations of the inherited area() method.
    3. Runtime Polymorphism / Dynamic Method Dispatch: The Java Virtual Machine resolves the call figRef.area() dynamically at runtime based on the actual object type referenced by figRef, rather than the reference type.
  20. Q9. Write short notes on the following : (a) HTML commands (b) DHTML dragging and drooping (c) AWT (d) JDBC202014m

    Module I: Introduction to Web Technologies & Architectures

    Write short notes on the following :

    (a) HTML commands
    (b) DHTML dragging and drooping
    (c) AWT
    (d) JDBC

    View this question on its own page →
    Worked Solution

    Answer: Short Notes on Web & Java Technologies


    (a) HTML Commands (Tags & Elements)

    HTML (HyperText Markup Language) commands (commonly referred to as HTML tags and elements) are syntax keywords enclosed within angle brackets (<tagname>) used to define the structure, content, and hypermedia links of a webpage.

    Core HTML Command Categories:

    1. Document Skeleton Commands:
      • <!DOCTYPE html>: Declares HTML5 document type.
      • <html>, <head>, <body>: Defines the root, metadata, and visible document body.
    2. Text Formatting Commands:
      • <h1> to <h6>: Headings; <p>: Paragraph; <br>: Line break; <hr>: Horizontal rule.
    3. Hyperlinks & Media Commands:
      • <a href="...">: Creates clickable hyperlinks.
      • <img src="..." alt="...">: Embeds images.
    4. Lists & Tables:
      • <ul>, <ol>, <li>: Unordered (bulleted) and ordered (numbered) lists.
      • <table>, <tr>, <th>, <td>: Renders structured tabular data.
    5. Interactive Forms:
      • <form>, <input>, <select>, <button>, <textarea>: Collects user data.

    (b) DHTML Dragging and Dropping

    DHTML (Dynamic HTML) is not a standalone language, but rather the synergistic combination of HTML, CSS, JavaScript, and the Document Object Model (DOM) to create interactive, animated web pages.

    Drag and Drop Mechanism:

    Drag and Drop allows users to click, grab an onscreen element, drag it over a target zone, and drop it.

    [Draggable Element] -- (dragstart) --> [Dragging Over Target] -- (drop) --> [Dropped Element]
     (draggable="true")                     (event.preventDefault())             (dataTransfer)
    

    Core HTML5 / DHTML Drag-and-Drop Events:

    • dragstart: Fires when the user starts dragging an element. Uses event.dataTransfer.setData("text", target.id) to store data.
    • dragover: Fires continuously when a dragged element is over a valid drop target. Must invoke event.preventDefault() to allow dropping.
    • drop: Fires when the dragged item is released over the drop target. Retrieves data via event.dataTransfer.getData("text").
    <div id="dragItem" draggable="true" ondragstart="event.dataTransfer.setData('text', this.id)">
      Drag Me
    </div>
    <div id="dropZone" ondragover="event.preventDefault()" ondrop="this.appendChild(document.getElementById(event.dataTransfer.getData('text')))">
      Drop Zone
    </div>
    

    (c) AWT (Abstract Window Toolkit)

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

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

    Key Features of AWT:

    1. Heavyweight Components: AWT components rely directly on the underlying operating system's native GUI peer widgets (e.g., a java.awt.Button creates a native Windows button on Windows and a Motif button on Unix).
    2. Container Hierarchy:
      • Frame: Top-level window with a title bar, border, and minimize/maximize buttons.
      • Panel: Space-allocating container used to group components.
    3. Layout Managers: Automatically arrange component geometry (FlowLayout, BorderLayout, GridLayout, GridBagLayout).
    4. Event Delegation Model: Decouples event sources (e.g., Button) from event listeners (ActionListener, MouseListener).

    (d) JDBC (Java Database Connectivity)

    JDBC (java.sql / javax.sql) is the standard Java API specification that enables Java applications to interact independently with relational database management systems (RDBMS like MySQL, Oracle, PostgreSQL).

    +-----------------------+
    |   Java Application    |
    +-----------+-----------+
                | (JDBC API Calls)
                v
    +-----------------------+
    |  JDBC DriverManager   |
    +-----------+-----------+
                |
                v
    +-----------------------+
    |   JDBC Driver (MySQL) |
    +-----------+-----------+
                | (Database Protocol)
                v
    +-----------------------+
    |   RDBMS Database      |
    +-----------------------+
    

    Standard 5 Steps to Execute JDBC Operations:

    1. Load Driver Class:
      Class.forName("com.mysql.cj.jdbc.Driver");
      
    2. Establish Database Connection:
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "password");
      
    3. Create Statement:
      Statement stmt = con.createStatement();
      // Or PreparedStatement for parameterized SQL
      
    4. Execute SQL Query:
      ResultSet rs = stmt.executeQuery("SELECT * FROM students");
      while (rs.next()) {
          System.out.println(rs.getInt("roll_no") + " : " + rs.getString("name"));
      }
      
    5. Close Resources:
      rs.close(); stmt.close(); con.close();