Web Technology
Module III: Basics of Web Programming
Q1d. Which of the following is the correct syntax to print a page using JavaScript? (i) window.print(); (ii) browser.print(); (iii) navigator.print(); (iv) document.print();20202m
Module III: Basics of Web Programming
View this question on its own page →Which of the following is the correct syntax to print a page using JavaScript?
(i) window.print();
(ii) browser.print();
(iii) navigator.print();
(iv) document.print();Worked SolutionCorrect Answer: (i) window.print();
Explanation:
- In client-side JavaScript, the
window.print()method opens the browser's native Print dialog box, allowing the user to print the current webpage or save it as a PDF. - The
windowobject represents the global browser window containing the DOM document.
Example:
<button onclick="window.print()">Print This Page</button>Note on other objects:
browseris not a standard global DOM API.navigatorprovides browser metadata (user-agent, geolocation, platform).documentrepresents the HTML document tree, but theprint()method resides on the top-levelwindowobject.
- In client-side JavaScript, the
Q1e. JavaScript code is written inside file having extension (i) .jvs (ii) .JavaScript (iii) .js (iv) .jsc20192m
Module III: Basics of Web Programming
View this question on its own page →JavaScript code is written inside file having extension
(i) .jvs
(ii) .JavaScript
(iii) .js
(iv) .jscWorked SolutionCorrect Answer: (iii) .js
Explanation:
- External JavaScript source files are saved with the standard
.jsfile extension (e.g.,main.js,script.js). - They are linked into HTML documents using the
<script src="...">element:<script src="script.js"></script>
- External JavaScript source files are saved with the standard
Q1f. JavaScript is called as lightweight programming language because (i) JS is available free of cost (ii) JS is client-side scripting (iii) we can add programming functionality inside JS (iv) JS can provide programming functionality inside but up to certain extent20192m
Module III: Basics of Web Programming
View this question on its own page →JavaScript is called as lightweight programming language because
(i) JS is available free of cost
(ii) JS is client-side scripting
(iii) we can add programming functionality inside JS
(iv) JS can provide programming functionality inside but up to certain extentWorked SolutionCorrect Answer: (iv) JS can provide programming functionality inside but up to certain extent
Explanation:
- JavaScript is described as a "lightweight" language because:
- It has a small memory footprint and does not require complex local compilation or binaries before execution.
- It has restricted system-level access in the browser sandbox (cannot directly manage OS threads, pointers, or arbitrary disk files).
- It executes directly via the browser's lightweight JIT-interpreter engine.
- JavaScript is described as a "lightweight" language because:
Q1g. Which technology is used for server-side scripting? (i) HTML (ii) CSS (iii) JSP (iv) JavaScript20252m
Module III: Basics of Web Programming
View this question on its own page →Which technology is used for server-side scripting?
(i) HTML
(ii) CSS
(iii) JSP
(iv) JavaScriptWorked SolutionCorrect Answer: (iii) JSP
Explanation:
- JSP (JavaServer Pages) is a server-side technology that allows developers to insert Java code into HTML templates to generate dynamic web content on the server before sending it to the client.
- HTML and CSS are purely client-side markup and styling languages rendered directly by the browser.
- JavaScript historically runs as a client-side scripting language in the browser (unless explicitly executed on a runtime like Node.js).
How JSP Works on Server:
- Client requests a
.jspfile. - The web server translates JSP into a Java Servlet (
.java). - The servlet is compiled into bytecode (
.class) and executed. - The generated HTML response is sent back to the client.
Q1h. Which of the following is a client-side scripting language? (i) PHP (ii) JavaScript (iii) JSP (iv) Servlet20252m
Module III: Basics of Web Programming
View this question on its own page →Which of the following is a client-side scripting language?
(i) PHP
(ii) JavaScript
(iii) JSP
(iv) ServletWorked SolutionCorrect Answer: (ii) JavaScript
Explanation:
- JavaScript is the standard client-side scripting language executed directly by the web browser's JavaScript engine (e.g., V8, SpiderMonkey).
- It enables interactive web pages, dynamic styling, DOM manipulation, form validation, and asynchronous requests (AJAX).
- PHP, JSP, and Servlets are all server-side technologies executed on the web/application server.
Q1h. What is the fundamental unit of information of writer streams in Java? (i) Characters (ii) Bytes (iii) Files (iv) Records20192m
Module III: Basics of Web Programming
View this question on its own page →What is the fundamental unit of information of writer streams in Java?
(i) Characters
(ii) Bytes
(iii) Files
(iv) RecordsWorked SolutionCorrect Answer: (i) Characters
Explanation:
- In Java I/O (
java.io), Writer (and Reader) streams are Character Streams that operate on 16-bit Unicode Characters (e.g.,FileWriter,PrintWriter,BufferedWriter). - Byte Streams (e.g.,
FileOutputStream,InputStream) operate on 8-bit Bytes.
Stream Classification in Java:
Stream Hierarchy Base Class Unit of Data Character Output java.io.Writer16-bit Unicode Characters Character Input java.io.Reader16-bit Unicode Characters Byte Output java.io.OutputStream8-bit Bytes Byte Input java.io.InputStream8-bit Bytes - In Java I/O (
Q1i. The command to execute a compiled Java program is (i) javac (ii) java (iii) run (iv) execute20192m
Module III: Basics of Web Programming
View this question on its own page →The command to execute a compiled Java program is
(i) javac
(ii) java
(iii) run
(iv) executeWorked SolutionCorrect Answer: (ii) java
Explanation:
- The
javacommand launches the Java Virtual Machine (JVM) to load, verify, and execute compiled.classbytecode files (e.g.,java ProgramName). javacis the compiler command used to compile.javasource code into bytecode (javac ProgramName.java).runandexecuteare not standard JDK command-line utilities.
- The
Q1j. The Java compiler (i) creates executable (ii) translates Java source code to byte code (iii) creates classes (iv) produces Java interpreters20192m
Module III: Basics of Web Programming
View this question on its own page →The Java compiler
(i) creates executable
(ii) translates Java source code to byte code
(iii) creates classes
(iv) produces Java interpretersWorked SolutionCorrect Answer: (ii) translates Java source code to byte code
Explanation:
- The Java Compiler (
javac) translates high-level Java source code (.java) into platform-independent intermediate Bytecode stored in.classfiles. - The bytecode is later interpreted and executed by the Java Virtual Machine (JVM).
- Unlike C/C++ compilers, the Java compiler does not generate direct machine-executable binaries (
.exeor.out).
- The Java Compiler (
Q1j. Which of the following keywords can be used in a subclass to call the constructor of superclass? (i) Super (ii) This (iii) Extent (iv) Extends20202m
Module III: Basics of Web Programming
View this question on its own page →Which of the following keywords can be used in a subclass to call the constructor of superclass?
(i) Super
(ii) This
(iii) Extent
(iv) ExtendsWorked SolutionCorrect Answer: (i) Super (specifically
super())Explanation:
- In Java, the
superkeyword is a reference variable used to refer to immediate parent (superclass) class objects. - When used with parentheses as
super()orsuper(arguments), it explicitly invokes the constructor of the superclass. - Rule: The call to
super()must be the very first statement inside the subclass constructor.
Example:
class Parent { Parent(String message) { System.out.println("Parent Constructor: " + message); } } class Child extends Parent { Child() { super("Invoking Superclass Constructor"); // Calls Parent constructor System.out.println("Child Constructor"); } }Contrast with other keywords:
this(): Invokes another constructor within the same class.extends: Declares class inheritance (class Child extends Parent).
- In Java, the
Q3a. What are events? Explain the events used in JavaScript with the help of examples.20197m
Module III: Basics of Web Programming
View this question on its own page →What are events? Explain the events used in JavaScript with the help of examples.
Worked SolutionAnswer: Events and Event Handling in JavaScript
1. What are Events in JavaScript?
In JavaScript, an Event is an action or occurrence recognized by software, initiated either by the user (e.g., clicking a button, pressing a key, moving the mouse) or by the browser (e.g., page loading, network error).
JavaScript uses Event Listeners / Handlers to execute specific functions whenever a targeted event occurs on a DOM element.
[ User Action: Click Button ] ---> [ Event Object Created: 'click' ] ---> [ Event Listener Dispatches Callback ] ---> [ DOM / UI Updated ]
2. Three Ways to Register Event Handlers
- Inline HTML Attributes:
<button onclick="alert('Button Clicked!')">Click Me</button> - DOM Object Property:
const btn = document.getElementById("myBtn"); btn.onclick = function() { console.log("Clicked"); }; - W3C Standard
addEventListener()(Recommended):const btn = document.getElementById("myBtn"); btn.addEventListener("click", (event) => { console.log("Button clicked at coordinates: " + event.clientX + ", " + event.clientY); });
3. Major Categories of JavaScript Events
A. Mouse Events
Event Trigger Condition Code Example clickUser clicks on an element btn.addEventListener('click', handleClick)dblclickUser double-clicks an element box.addEventListener('dblclick', handleDoubleClick)mouseoverMouse pointer enters element boundaries card.addEventListener('mouseover', highlight)mouseoutMouse pointer leaves element boundaries card.addEventListener('mouseout', unhighlight)mousemoveMouse pointer moves over an element canvas.addEventListener('mousemove', draw)
B. Keyboard Events
Event Trigger Condition Code Example keydownKey is pressed down input.addEventListener('keydown', (e) => console.log(e.key))keyupKey is released input.addEventListener('keyup', validate)
C. Form Events
Event Trigger Condition Code Example submitForm is submitted (can intercept via e.preventDefault())form.addEventListener('submit', validateForm)changeValue of an input/select element has changed and lost focus select.addEventListener('change', updateSelection)focusElement receives focus input.addEventListener('focus', showHint)blurElement loses focus input.addEventListener('blur', hideHint)inputValue changes in real-time input.addEventListener('input', updateCharCount)
D. Window / Document Lifecycle Events
Event Trigger Condition Code Example DOMContentLoadedHTML document is fully parsed into DOM (without waiting for images/stylesheets) document.addEventListener('DOMContentLoaded', init)loadEntire page including all stylesheets, scripts, and images is fully loaded window.addEventListener('load', startApp)resizeBrowser window viewport is resized window.addEventListener('resize', handleResize)scrollUser scrolls the document window.addEventListener('scroll', checkScrollPosition)
4. Comprehensive Interactive Demonstration
<!DOCTYPE html> <html> <head> <title>JavaScript Events Demo</title> </head> <body> <h2>JavaScript Event Handling Demo</h2> <!-- Mouse Event --> <button id="alertBtn">Click Me (Mouse Event)</button> <!-- Keyboard Event --> <p>Type below to see live character count (Keyboard Event):</p> <input type="text" id="textInput" placeholder="Type something..."> <span id="charCount">0 characters</span> <!-- Form Event --> <form id="sampleForm" style="margin-top:20px;"> <input type="text" id="username" placeholder="Username" required> <button type="submit">Submit Form</button> </form> <p id="statusMsg"></p> <script> // 1. Mouse Event document.getElementById("alertBtn").addEventListener("click", () => { alert("Mouse Click Event Triggered!"); }); // 2. Keyboard & Input Event const textInput = document.getElementById("textInput"); const charCount = document.getElementById("charCount"); textInput.addEventListener("input", () => { charCount.innerText = textInput.value.length + " characters"; }); // 3. Form Submit Event with preventDefault() document.getElementById("sampleForm").addEventListener("submit", (e) => { e.preventDefault(); // Prevents page reload const user = document.getElementById("username").value; document.getElementById("statusMsg").innerText = "Form submitted for: " + user; }); </script> </body> </html>- Inline HTML Attributes:
Q3a. Explain the steps involved in creating and executing a Java program.20207m
Module III: Basics of Web Programming
View this question on its own page →Explain the steps involved in creating and executing a Java program.
Worked SolutionAnswer: Steps Involved in Creating and Executing a Java Program
1. Introduction
Java follows the "Write Once, Run Anywhere" (WORA) philosophy. Unlike traditional compiled languages (like C/C++) that compile directly into platform-dependent machine binaries, Java source code is compiled into an intermediate, platform-neutral format called Bytecode, which is executed by the Java Virtual Machine (JVM).
+---------------------+ | Java Source Code | (HelloWorld.java) +----------+----------+ | | 1. javac Compiler v +---------------------+ | Java Bytecode | (HelloWorld.class) +----------+----------+ | | 2. Transferred to any OS (Windows, Linux, macOS) v +---------------------------------------------------------------+ | JAVA VIRTUAL MACHINE (JVM) | | | | +----------------------+ +---------------------------+ | | | ClassLoader Subsystem| ---> | Bytecode Verifier | | | +----------------------+ +-------------+-------------+ | | | | | v | | +---------------------------+ | | | Execution Engine | | | | (Interpreter + JIT Engine)| | | +-------------+-------------+ | +----------------------------------------------|----------------+ | v +--------------------+ | Machine Code / CPU | +--------------------+
2. Step-by-Step Process
Step 1: Writing the Source Code
- Create a Java source file using any text editor or IDE (VS Code, IntelliJ IDEA, Eclipse).
- Save the file with a
.javaextension. The file name must exactly match the public class name.
// File: HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World from Java!"); } }
Step 2: Compiling the Source Code (
javac)- The Java Compiler (
javac) reads the.javasource code, verifies syntax and semantic rules, and translates it into platform-independent Bytecode. - Command:
javac HelloWorld.java - Output: Produces a binary file named
HelloWorld.class.
Step 3: Loading Classes into Memory (ClassLoader)
When executing the program (
java HelloWorld), the JVM starts and its ClassLoader subsystem performs three phases:- Loading: Reads
.classbinary streams and creates theClassobject in the JVM Method Area. - Linking:
- Verification: Ensures bytecode adheres to JVM specifications and has no illegal memory accesses.
- Preparation: Allocates memory for static variables and initializes default values.
- Resolution: Replaces symbolic references with direct memory references.
- Initialization: Executes static initializers and assigns explicit static values.
Step 4: Bytecode Verification
- The Bytecode Verifier checks the code for security violations (e.g., stack overflow, illegal data type casting, unauthorized pointer manipulation) before execution.
Step 5: Execution by the JVM Execution Engine
The JVM execution engine executes bytecode instructions on the underlying CPU using two combined strategies:
- Interpreter: Reads and executes bytecode instructions line by line (starts quickly).
- JIT (Just-In-Time) Compiler: Identifies frequently executed code blocks ("hot spots") and compiles them directly into native machine code to drastically boost runtime performance.
- Garbage Collector: Automatically tracks and reclaims unreferenced heap memory in the background.
3. Summary of CLI Commands
Step Command Tool Used File Produced Compilation javac HelloWorld.javaJava Compiler ( javac)HelloWorld.class(Bytecode)Execution java HelloWorldJava Virtual Machine ( java)Console Output / Runtime Q3b. Explain various data types used in JavaScript with the help of examples.20197m
Module III: Basics of Web Programming
View this question on its own page →Explain various data types used in JavaScript with the help of examples.
Worked SolutionAnswer: Data Types in JavaScript with Examples
1. Introduction
JavaScript is a dynamically typed (loosely typed) language, meaning variables do not require explicit type declarations; data types are automatically determined at runtime based on the assigned value.
Data types in JavaScript are divided into two primary categories:
- Primitive Data Types (Immutable, passed by value)
- Non-Primitive / Reference Data Types (Mutable, passed by reference)
+-----------------------------+ | JAVASCRIPT DATA TYPES | +--------------+--------------+ | +------------------------+------------------------+ | | v v +--------------------+ +--------------------+ | PRIMITIVE TYPES | | REFERENCE TYPES | | Number, String, | | Object, Array, | | Boolean, Undefined,| | Function, Date, | | Null, BigInt, | | Map, Set | | Symbol | | | +--------------------+ +--------------------+
2. Primitive Data Types
1.
Number- Represents both integer and floating-point numeric values (IEEE 754 64-bit float). Also includes special values:
Infinity,-Infinity, andNaN(Not-a-Number).
let age = 21; let price = 99.95; let invalid = "text" / 2; // Returns NaN2.
String- Represents textual data enclosed within single quotes (
'...'), double quotes ("..."), or backticks for template literals (`...`).
let name = "Rohan"; let message = `Hello, ${name}!`; // Template literal interpolation3.
Boolean- Represents a logical entity with only two possible values:
trueorfalse.
let isLoggedIn = true; let hasPaid = false;4.
Undefined- A variable that has been declared but not yet assigned a value automatically holds the value
undefined.
let x; console.log(x); // Output: undefined5.
Null- Represents the intentional absence of any object value (represents "empty" or "nothing").
let currentUser = null; // Explicitly no user logged in6.
BigInt- Used for arbitrarily large integers that exceed the safe integer limit of Number (
2^53 - 1). Created by appendingnto the integer.
let largeNumber = 9007199254740991123456789n;7.
Symbol- Represents a unique, immutable identifier, commonly used to create private or collision-resistant object keys.
let id1 = Symbol("id"); let id2 = Symbol("id"); console.log(id1 === id2); // false (each Symbol is globally unique)
3. Non-Primitive (Reference) Data Types
1.
Object- A collection of key-value pairs used to model complex entities.
let student = { name: "Aman", rollNo: 105, branch: "CSE", greet: function() { console.log("Hello from " + this.name); } };2.
Array- An ordered list/collection of elements (can hold mixed data types).
let subjects = ["Web Tech", "Networks", "Compiler Design", 2026, true]; console.log(subjects[0]); // Output: "Web Tech"3.
Function- Functions in JavaScript are First-Class Objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
function add(a, b) { return a + b; }
4. Checking Data Types using the
typeofOperatorconsole.log(typeof 42); // "number" console.log(typeof "Hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof 100n); // "bigint" console.log(typeof Symbol("key")); // "symbol" console.log(typeof { a: 1 }); // "object" console.log(typeof [1, 2, 3]); // "object" console.log(typeof function() {}); // "function" // Historical JavaScript quirk: console.log(typeof null); // "object" (known legacy bug in JS)
5. Dynamic Typing Example
let dynamicVar = 100; // Currently a Number dynamicVar = "Now a String"; // Now a String dynamicVar = [1, 2, 3]; // Now an Array (Object)Q3b. Explain Java garbage collection mechanism.20207m
Module III: Basics of Web Programming
View this question on its own page →Explain Java garbage collection mechanism.
Worked SolutionAnswer: Java Garbage Collection Mechanism
1. What is Java Garbage Collection (GC)?
Garbage Collection (GC) in Java is an automated memory management process managed by the Java Virtual Machine (JVM) that tracks objects allocated on the heap and reclaims memory occupied by objects that are no longer reachable or referenced by any active part of the running program.
Unlike languages like C/C++ where developers must manually allocate and free memory (
malloc()/free(),new/delete), Java automatically prevents memory leaks and dangling pointer errors.+---------------------------------------------------------------------------------+ | JVM HEAP | | | | +----------------------------- Young Gen ----------------------------+ | | | +----------------+ +--------------------+ +--------------------+ | Old | | | | Eden | | Survivor 0 (From) | | Survivor 1 (To) | | Gen | | | | (New Objects) | | (Minor GC S0) | | (Minor GC S1) | | (Tenured) | | +----------------+ +--------------------+ +--------------------+ | | | +--------------------------------------------------------------------+---------+
2. When Does an Object Become Eligible for GC?
An object on the heap is eligible for garbage collection when it has no live references pointing to it from the GC Roots (stack frames, static variables, JNI references).
Common Scenarios:
- Nullifying a Reference Variable:
Student s = new Student("Alice"); s = null; // Original Student object is now eligible for GC - Reassigning a Reference Variable:
Student s1 = new Student("Alice"); Student s2 = new Student("Bob"); s1 = s2; // Original "Alice" object is now orphaned and eligible for GC - Objects Created Inside a Method Scope:
- Once the method finishes execution, local reference variables popped from the call stack leave created objects unreferenced.
- Island of Isolation:
- Two objects reference each other, but neither is referenced by any active live reference from root threads.
3. Generational Garbage Collection Hypothesis
Most objects in software have short lifespans (created, used, and discarded quickly). JVM divides the Heap into Generations:
A. Young Generation
- Eden Space: All new objects are initially created here.
- Survivor Spaces (S0 & S1): Objects that survive a Minor GC in Eden are moved between S0 and S1, incrementing their age counter.
B. Old (Tenured) Generation
- Objects that survive multiple Minor GC cycles (threshold age, typically 15) are promoted to the Old Generation.
- Cleaned up during a Major GC (Full GC).
C. Metaspace (Non-Heap)
- Stores class metadata and static variables (replaces PermGen in Java 8+).
4. How Garbage Collection Works: The Mark-and-Sweep Process
- Mark Phase: The GC identifies and marks all live, reachable objects by traversing reference trees starting from GC Roots.
- Sweep Phase: The GC sweeps the heap and frees the memory occupied by all unmarked (unreachable) objects.
- Compact Phase (Optional): Moves all surviving objects together to eliminate memory fragmentation and create contiguous free space.
5. Explicit GC Request and Finalization
- Requesting GC: Developers can suggest garbage collection using:
(Note: This only requests GC; the JVM decides when to actually execute it).System.gc(); // or Runtime.getRuntime().gc(); finalize()Method: Historically invoked by the JVM before reclaiming an object's memory (deprecated in modern Java in favor ofAutoCloseable/Cleaner).
6. Popular JVM Garbage Collectors
Garbage Collector Use Case Key Characteristics Serial GC Small, single-threaded apps Single-threaded, basic Mark-Sweep-Compact Parallel GC High-throughput batch jobs Multi-threaded Minor and Major GC G1 GC (Garbage-First) Large heap sizes (>4GB), default in modern Java Divides heap into equal regions; prioritizes regions with most garbage ZGC / Shenandoah Ultra-low latency enterprise apps Sub-millisecond pause times concurrent GC - Nullifying a Reference Variable:
Q4a. What is multithreading in Java? Explain the inter-thread communication with the help of suitable example.20207m
Module III: Basics of Web Programming
View this question on its own page →What is multithreading in Java? Explain the inter-thread communication with the help of suitable example.
Worked SolutionAnswer: Multithreading and Inter-Thread Communication in Java
1. What is Multithreading in Java?
Multithreading is a core Java feature that allows concurrent execution of two or more parts of a program (called threads) to maximize CPU utilization. Each thread represents an independent path of execution sharing common memory space.
Ways to Create Threads in Java:
- By extending the
Threadclass and overridingrun(). - By implementing the
Runnableinterface and passing it to aThreadinstance.
2. What is Inter-Thread Communication?
Inter-thread communication (cooperation) allows synchronized threads to communicate with each other regarding resource availability and state changes, avoiding CPU-wasting polling loops (busy waiting).
Core Methods (Defined in
java.lang.Object):wait(): Causes the current thread to release the monitor lock and wait until another thread invokesnotify()ornotifyAll()on the same object.notify(): Wakes up a single thread waiting on this object's monitor.notifyAll(): Wakes up all threads waiting on this object's monitor.
Rule:
wait(),notify(), andnotifyAll()must always be executed inside asynchronizedblock or method.+-------------------+ +-------------------+ | Producer Thread | | Consumer Thread | +---------+---------+ +---------+---------+ | | | 1. Produces Item | | 2. Puts item in Shared Buffer | | 3. Calls notify() ------------------------------> | (Wakes Up) | 4. Buffer Full -> Calls wait() (Releases Lock) | 5. Consumes Item | | 6. Calls notify() |<--------------------------------------------------| (Wakes Up)
3. Producer-Consumer Implementation Example
// Shared resource buffer class SharedQueue { private int data; private boolean hasData = false; // Producer calls put() public synchronized void put(int value) { while (hasData) { try { wait(); // Wait if buffer already has data } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } this.data = value; this.hasData = true; System.out.println("Produced: " + value); notify(); // Notify the waiting consumer } // Consumer calls get() public synchronized int get() { while (!hasData) { try { wait(); // Wait if buffer is empty } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } this.hasData = false; System.out.println("Consumed: " + data); notify(); // Notify the waiting producer return data; } } // Producer Thread class Producer extends Thread { private SharedQueue queue; Producer(SharedQueue q) { this.queue = q; } public void run() { for (int i = 1; i <= 5; i++) { queue.put(i); try { Thread.sleep(500); } catch (InterruptedException ignored) {} } } } // Consumer Thread class Consumer extends Thread { private SharedQueue queue; Consumer(SharedQueue q) { this.queue = q; } public void run() { for (int i = 1; i <= 5; i++) { queue.get(); try { Thread.sleep(800); } catch (InterruptedException ignored) {} } } } // Main Driver Class public class InterThreadDemo { public static void main(String[] args) { SharedQueue queue = new SharedQueue(); Producer p = new Producer(queue); Consumer c = new Consumer(queue); p.start(); c.start(); } }Sample Output:
Produced: 1 Consumed: 1 Produced: 2 Consumed: 2 Produced: 3 Consumed: 3 ...
4. Key Takeaways
- Thread Synchronization: Prevents race conditions and dirty reads on shared data.
- Lock Release: Calling
wait()immediately releases the object monitor lock, whereasThread.sleep()retains the lock. - Deadlock Prevention: Coordinated
wait()andnotify()calls ensure producer and consumer threads run without starvation or deadlock.
- By extending the
Q4b. Explain different string handling functions and their syntax in Java language.20207m
Module III: Basics of Web Programming
View this question on its own page →Explain different string handling functions and their syntax in Java language.
Worked SolutionAnswer: String Handling Functions in Java
1. Introduction
In Java, a String is an object of the
java.lang.Stringclass that represents a sequence of characters.- Immutability: Once created, a
Stringobject’s content cannot be modified. Any modification creates a newStringobject in memory (utilizing the String Constant Pool). - For mutable strings, Java provides
StringBuffer(thread-safe, synchronized) andStringBuilder(faster, non-synchronized).
2. Core String Handling Methods
Method & Syntax Description Example int length()Returns the number of characters in the string. "Hello".length()5char charAt(int index)Returns the character at the specified 0-based index. "Java".charAt(1)'a'String substring(int begin, int end)Returns substring from begin(inclusive) toend(exclusive)."Technology".substring(0, 4)"Tech"boolean equals(Object obj)Compares character contents for exact equality (case-sensitive). "Cat".equals("cat")falseboolean equalsIgnoreCase(String s)Compares strings ignoring uppercase/lowercase differences. "Cat".equalsIgnoreCase("cat")trueint compareTo(String s)Compares strings lexicographically ( if equal, negative if smaller, positive if greater). "A".compareTo("B")-1String concat(String str)Appends the specified string to the end. "Web".concat("Tech")"WebTech"int indexOf(String str)Returns index of first occurrence of the substring (or -1). "banana".indexOf("na")2int lastIndexOf(String str)Returns index of last occurrence of the substring. "banana".lastIndexOf("na")4String toUpperCase()Converts all characters to uppercase. "java".toUpperCase()"JAVA"String toLowerCase()Converts all characters to lowercase. "HTML".toLowerCase()"html"String trim()Eliminates leading and trailing whitespace. " test ".trim()"test"String replace(char old, char new)Replaces all occurrences of oldwithnew."Java".replace('a', 'o')"Jovo"boolean contains(CharSequence s)Checks if string contains the specified sequence. "PYQDeck".contains("Deck")trueboolean startsWith(String prefix)Checks if string begins with specified prefix. "http://".startsWith("http")trueString[] split(String regex)Splits the string into an array around matches of regex. "a,b,c".split(",")["a", "b", "c"]char[] toCharArray()Converts string into a new character array. "Hi".toCharArray()['H', 'i']
3. Java Code Demonstration
public class StringHandlingDemo { public static void main(String[] args) { String s1 = " Bihar Engineering University "; System.out.println("Original String: '" + s1 + "'"); System.out.println("Length: " + s1.length()); System.out.println("Trimmed: '" + s1.trim() + "'"); System.out.println("Uppercase: " + s1.toUpperCase()); System.out.println("Character at index 7: " + s1.charAt(7)); System.out.println("Substring (1-6): " + s1.substring(1, 6)); System.out.println("Replaced: " + s1.replace("Bihar", "State")); System.out.println("Contains 'Engineering': " + s1.contains("Engineering")); // Splitting string String languages = "HTML,CSS,JavaScript,Java,PHP"; String[] langArray = languages.split(","); System.out.println(" Split Elements:"); for (String lang : langArray) { System.out.println(" - " + lang); } } }
4.
StringvsStringBuffervsStringBuilderParameter StringStringBufferStringBuilderStorage String Constant Pool / Heap Heap Heap Mutability Immutable Mutable Mutable Thread Safety Thread-safe (due to immutability) Thread-safe (Synchronized) Not Thread-safe Performance Slow on frequent concatenation Medium Fastest Introduced Java 1.0 Java 1.0 Java 1.5 - Immutability: Once created, a
Q5. Write a program in Java to do the following: (a) To swap the two numbers without using the third variable (b) Factorial of a number using recursion202014m
Module III: Basics of Web Programming
View this question on its own page →Write a program in Java to do the following:
(a) To swap the two numbers without using the third variable
(b) Factorial of a number using recursionWorked SolutionAnswer: Java Programs — Number Swapping & Recursive Factorial
Part (a): Swap Two Numbers Without Using a Third Variable
1. Algorithm & Logic
We can swap two numbers without a temporary variable using arithmetic addition/subtraction or bitwise XOR operations:
- Step 1: (Holds sum of both)
- Step 2: (Original value of )
- Step 3: (Original value of )
2. Java Code:
import java.util.Scanner; public class SwapWithoutThirdVariable { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first number (a): "); int a = sc.nextInt(); System.out.print("Enter second number (b): "); int b = sc.nextInt(); System.out.println(" --- Before Swapping ---"); System.out.println("a = " + a + ", b = " + b); // Swapping logic using arithmetic operators a = a + b; b = a - b; a = a - b; System.out.println(" --- After Swapping ---"); System.out.println("a = " + a + ", b = " + b); sc.close(); } }3. Dry Run:
- Initial:
- Line 1 ():
- Line 2 (): ( now holds original )
- Line 3 (): ( now holds original )
- Result: (Swapped successfully!)
Part (b): Factorial of a Number Using Recursion
1. Mathematical Principle & Base Case
2. Java Code:
import java.util.Scanner; public class RecursiveFactorial { // Recursive function to calculate factorial public static long calculateFactorial(int n) { // Base Condition if (n <= 1) { return 1; } // Recursive Call return n * calculateFactorial(n - 1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a non-negative integer: "); int number = sc.nextInt(); if (number < 0) { System.out.println("Factorial is not defined for negative numbers."); } else { long result = calculateFactorial(number); System.out.println("Factorial of " + number + " (" + number + "!) = " + result); } sc.close(); } }3. Recursive Call Stack Trace (For ):
calculateFactorial(4) = 4 * calculateFactorial(3) = 3 * calculateFactorial(2) = 2 * calculateFactorial(1) = 1 (Base case reached) = 2 * 1 = 2 = 3 * 2 = 6 = 4 * 6 = 24 Output: 24
Complete Unified Program
import java.util.Scanner; public class CombinedExamDemo { public static void swap(int a, int b) { System.out.println("Before Swap: a = " + a + ", b = " + b); a = a ^ b; // Bitwise XOR swapping b = a ^ b; a = a ^ b; System.out.println("After Swap: a = " + a + ", b = " + b); } public static long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } public static void main(String[] args) { // Test (a) swap(10, 20); // Test (b) int num = 5; System.out.println("Factorial of " + num + " = " + factorial(num)); } }Q5a. Describe how the following features of Java relate to the behavior of accessor and mutator methods: (i) Fields (ii) Local variables (iii) Parameters (iv) Return values (v) Visibility modifiers Illustrate each with brief code samples.20197m
Module III: Basics of Web Programming
View this question on its own page →Describe how the following features of Java relate to the behavior of accessor and mutator methods:
(i) Fields
(ii) Local variables
(iii) Parameters
(iv) Return values
(v) Visibility modifiersIllustrate each with brief code samples.
Worked SolutionAnswer: Relationship of Java Language Features with Accessor and Mutator Methods
1. Introduction to Accessor and Mutator Methods
In Java Object-Oriented Programming, Encapsulation is achieved by keeping class data hidden and providing controlled access through:
- Accessor Methods (Getters): Public methods that retrieve/read the internal state of an object without modifying it.
- Mutator Methods (Setters): Public methods that modify/update the internal state of an object, often performing data validation.
[ External Caller ] ---> getAge() [Accessor] ---> Reads (Returns field value) ---> setAge(21) [Mutator] ---> Validates & Updates Private Field
2. Detailed Relationship with Java Features
(i) Fields (Instance Variables)
- Role: Fields hold the persistent state and data of the object.
- Relationship: To protect fields from direct unauthorized access or corruption, they are declared
private. Accessors read from these fields, while mutators write to them.
public class Account { private double balance; // Private instance field }
(ii) Local Variables
- Role: Variables declared inside the body of a method that exist only on the call stack for the duration of method execution.
- Relationship: Mutators and accessors use local variables to perform temporary calculations, formatting, or validation checks before updating or returning field values.
public String getFormattedBalance() { String currencySymbol = "Rs. "; // Local variable return currencySymbol + this.balance; }
(iii) Parameters (Formal Arguments)
- Role: Input variables defined in the method signature that receive values passed by the caller.
- Relationship: Mutator methods accept parameters representing the new desired state. The
thiskeyword is used to distinguish the instance field from the method parameter when they share the same name (shadowing).
public void setBalance(double balance) { // 'balance' is a parameter if (balance >= 0) { this.balance = balance; // 'this.balance' is the field; 'balance' is the parameter } }
(iv) Return Values
- Role: The value and data type sent back to the caller when a method completes.
- Relationship:
- Accessors: Must have a non-void return type matching or widening the field's data type (e.g.,
public double getBalance()). - Mutators: Typically have a
voidreturn type, or return abooleanto indicate if the mutation/validation succeeded.
- Accessors: Must have a non-void return type matching or widening the field's data type (e.g.,
public double getBalance() { return this.balance; // Non-void return value }
(v) Visibility Modifiers (
private,public,protected)- Role: Specify access control boundaries and information hiding.
- Relationship:
- Fields: Declared
privateto restrict direct access from outside classes. - Accessors & Mutators: Declared
publicto expose a safe, controlled interface to external callers.
- Fields: Declared
private int age; // Hidden from outside world public int getAge() { ... } // Publicly accessible read public void setAge(int a) { // Publicly accessible validated write if (a > 0 && a < 120) this.age = a; }
3. Comprehensive Integrated Code Example
public class StudentProfile { // (i) & (v) Private Instance Fields private String studentName; private int studentAge; // (iv) & (v) Public Accessor (Getter) with Return Value public String getStudentName() { return this.studentName; } // (iii), (iv) & (v) Public Mutator (Setter) with Parameter public void setStudentName(String studentName) { // (ii) Local variable used for validation boolean isValid = (studentName != null && !studentName.trim().isEmpty()); if (isValid) { this.studentName = studentName.trim(); } } // Accessor for Age public int getStudentAge() { return this.studentAge; } // Mutator for Age with validation logic public boolean setStudentAge(int studentAge) { if (studentAge >= 17 && studentAge <= 60) { this.studentAge = studentAge; return true; // (iv) Boolean return value indicating success } return false; } }Q5b. What is Inheritance? Explain its different types. Write Java program to implement multiple inheritance.20197m
Module III: Basics of Web Programming
View this question on its own page →What is Inheritance? Explain its different types. Write Java program to implement multiple inheritance.
Worked SolutionAnswer: Inheritance Types and Multiple Inheritance Implementation in Java
1. What is Inheritance?
Inheritance is an object-oriented programming feature where a new class (subclass / derived class) acquires the properties, fields, and methods of an existing class (superclass / base class) using the
extendskeyword.- It models an "IS-A" relationship (e.g., Car IS-A Vehicle).
- Enables code reusability and runtime polymorphism (method overriding).
2. Types of Inheritance in Java
1. Single 2. Multilevel 3. Hierarchical +-------+ +-------+ +-------+ | Base | | Grand | | Base | +---+---+ +---+---+ +---+---+ | | | v v +--+--+ +-------+ +-------+ | | |Derived| |Parent | v v +-------+ +---+---+ +----+ +----+ | |Sub1| |Sub2| v +----+ +----+ +-------+ | Child | +-------+- Single Inheritance: A single subclass extends a single superclass.
- Multilevel Inheritance: A class extends a derived class, creating an inheritance chain ().
- Hierarchical Inheritance: Multiple subclasses inherit from a single common superclass.
- Multiple Inheritance: A class inherits from more than one superclass. (Supported in Java through Interfaces, but not through classes).
- Hybrid Inheritance: A combination of two or more types of inheritance.
3. Why Multiple Inheritance is Disallowed in Java with Classes
Java does not support multiple inheritance with classes (
class C extends A, B) to prevent ambiguity known as the "Diamond Problem":+-------+ | ClassA| (defines display()) +---+---+ | +-----+-----+ | | +--v----+ +--v----+ |ClassB | |ClassC | (Both override display()) +--+----+ +--+----+ | | +-----+-----+ | +---v---+ |ClassD | (Which display() should ClassD inherit? Ambiguity!) +-------+Java resolves this cleanly by allowing multiple inheritance only through Interfaces, since interface methods traditionally have no conflicting state.
4. Java Program Implementing Multiple Inheritance via Interfaces
// Interface 1: Backend Server Interface interface BackendEngine { void processData(); void connectDatabase(); } // Interface 2: Frontend UI Interface interface UserInterface { void renderUI(); } // Subclass implementing multiple interfaces class WebApplication implements BackendEngine, UserInterface { private String appName; WebApplication(String name) { this.appName = name; } // Implementing BackendEngine methods @Override public void processData() { System.out.println("[" + appName + "] Processing business logic on server."); } @Override public void connectDatabase() { System.out.println("[" + appName + "] Database connected successfully."); } // Implementing UserInterface methods @Override public void renderUI() { System.out.println("[" + appName + "] Rendering responsive HTML5 interface."); } } // Driver Class public class MultipleInheritanceDemo { public static void main(String[] args) { WebApplication portal = new WebApplication("PYQDeck Portal"); System.out.println("--- Executing WebApplication Capabilities ---"); portal.connectDatabase(); portal.processData(); portal.renderUI(); } }Program Output:
--- Executing WebApplication Capabilities --- [PYQDeck Portal] Database connected successfully. [PYQDeck Portal] Processing business logic on server. [PYQDeck Portal] Rendering responsive HTML5 interface.Q6. Define a class called Fuel_Monitor that will be used to check the amount of fuel that is left over in a vehicle after travelling a certain distance. The class should have instance variables tank capacity to store initial size of the tank and efficiency to store initial efficiency of the vehicle. Also, set the variable fuel_in_tank to zero that is used to store initial fuel in tank. Include a method that returns ini_tank_size, ini_effi and fuel_in_tank. Include a method add_fuel that calculates how much fuel can be filled depending upon the fuel already in the tank and the capacity of the tank. Also, include a method drive_distance that returns how much distance can be travelled with the fuel available in the tank with the efficiency provided. Embed your class in a test program. You should decide which variables should be public, if any.201914m
Module III: Basics of Web Programming
View this question on its own page →Define a class called
Fuel_Monitorthat will be used to check the amount of fuel that is left over in a vehicle after travelling a certain distance. The class should have instance variables tank capacity to store initial size of the tank and efficiency to store initial efficiency of the vehicle. Also, set the variablefuel_in_tankto zero that is used to store initial fuel in tank. Include a method that returnsini_tank_size,ini_effiandfuel_in_tank. Include a methodadd_fuelthat calculates how much fuel can be filled depending upon the fuel already in the tank and the capacity of the tank. Also, include a methoddrive_distancethat returns how much distance can be travelled with the fuel available in the tank with the efficiency provided. Embed your class in a test program. You should decide which variables should be public, if any.Worked SolutionAnswer: Java Implementation — Fuel_Monitor Class and Test Program
1. Class Design & Requirements Breakdown
Encapsulation Strategy:
- Private Instance Variables: All state variables are declared
privateto enforce encapsulation and prevent direct unauthorized alteration.tank_capacity: Total capacity of the fuel tank (in Litres).efficiency: Fuel efficiency / mileage (in Kilometers per Litre).fuel_in_tank: Current amount of fuel available in the tank (initialized to0.0).
Public Methods:
Fuel_Monitor(double capacity, double efficiency): Parameterized constructor to initialize the vehicle specifications.getStatus(): Returns a formatted summary of initial tank size, efficiency, and current fuel.add_fuel(double amount): Safely adds fuel up to maximum capacity and calculates how much fuel was actually filled.drive_distance(double distance): Simulates driving a specified distance, calculates fuel consumed (), updates the remaining fuel in tank, and returns the actual distance travelled.max_drive_distance(): Returns the total distance the vehicle can travel with the current remaining fuel in tank ().
2. Complete Java Code
import java.util.Scanner; class Fuel_Monitor { // Private instance variables for encapsulation private double tank_capacity; // Maximum fuel tank size (Litres) private double efficiency; // Mileage (km per Litre) private double fuel_in_tank; // Current fuel in tank (Litres) // Constructor to initialize tank capacity and vehicle efficiency public Fuel_Monitor(double tank_capacity, double efficiency) { this.tank_capacity = tank_capacity; this.efficiency = efficiency; this.fuel_in_tank = 0.0; // Initialized to zero as specified } // Method to return initial specifications and current fuel status public String getStatus() { return "Initial Tank Size: " + tank_capacity + " L | " + "Initial Efficiency: " + efficiency + " km/L | " + "Current Fuel: " + fuel_in_tank + " L"; } // Accessor methods public double get_ini_tank_size() { return tank_capacity; } public double get_ini_effi() { return efficiency; } public double get_fuel_in_tank() { return fuel_in_tank; } // Method to add fuel to the tank public double add_fuel(double amount) { if (amount <= 0) { System.out.println("Invalid fuel amount. Please enter a positive value."); return 0.0; } double available_space = tank_capacity - fuel_in_tank; if (amount <= available_space) { fuel_in_tank += amount; System.out.println("Added " + amount + " L. Current fuel in tank: " + fuel_in_tank + " L"); return amount; } else { // Fill tank to maximum capacity fuel_in_tank = tank_capacity; System.out.println("Tank Full! Only " + available_space + " L could be filled. (Overflow: " + (amount - available_space) + " L discarded)"); return available_space; } } // Method to drive a given distance and compute leftover fuel public double drive_distance(double distance) { if (distance <= 0) { System.out.println("Distance must be greater than zero."); return 0.0; } // Maximum distance possible with current fuel double max_possible_distance = fuel_in_tank * efficiency; if (distance <= max_possible_distance) { double fuel_consumed = distance / efficiency; fuel_in_tank -= fuel_consumed; System.out.println("Travelled " + distance + " km. Fuel consumed: " + String.format("%.2f", fuel_consumed) + " L."); System.out.println("Fuel left in tank: " + String.format("%.2f", fuel_in_tank) + " L."); return distance; } else { System.out.println("Not enough fuel to travel " + distance + " km!"); System.out.println("Vehicle travelled maximum possible: " + String.format("%.2f", max_possible_distance) + " km before running out of fuel."); fuel_in_tank = 0.0; return max_possible_distance; } } // Method returning max distance possible with current fuel public double get_max_possible_distance() { return fuel_in_tank * efficiency; } } // Test Program public class TestFuelMonitor { public static void main(String[] args) { System.out.println("=== VEHICLE FUEL MONITOR SIMULATION === "); // Create a vehicle with 50 Litre tank capacity and 15 km/L efficiency Fuel_Monitor car = new Fuel_Monitor(50.0, 15.0); // 1. Check initial status System.out.println("1. Initial Status:"); System.out.println(car.getStatus()); System.out.println(); // 2. Add Fuel System.out.println("2. Adding 30 Litres of Fuel:"); car.add_fuel(30.0); System.out.println("Max drivable range now: " + car.get_max_possible_distance() + " km "); // 3. Drive 150 km System.out.println("3. Driving 150 km:"); car.drive_distance(150.0); System.out.println(); // 4. Drive another 200 km System.out.println("4. Driving 200 km:"); car.drive_distance(200.0); System.out.println(); // 5. Try to drive more distance than fuel permits System.out.println("5. Attempting to drive 200 km with remaining fuel:"); car.drive_distance(200.0); System.out.println(); // 6. Overfill test System.out.println("6. Refueling with 60 Litres (Exceeds capacity):"); car.add_fuel(60.0); System.out.println(car.getStatus()); } }
3. Sample Program Output
=== VEHICLE FUEL MONITOR SIMULATION === 1. Initial Status: Initial Tank Size: 50.0 L | Initial Efficiency: 15.0 km/L | Current Fuel: 0.0 L 2. Adding 30 Litres of Fuel: Added 30.0 L. Current fuel in tank: 30.0 L Max drivable range now: 450.0 km 3. Driving 150 km: Travelled 150.0 km. Fuel consumed: 10.00 L. Fuel left in tank: 20.00 L. 4. Driving 200 km: Travelled 200.0 km. Fuel consumed: 13.33 L. Fuel left in tank: 6.67 L. 5. Attempting to drive 200 km with remaining fuel: Not enough fuel to travel 200.0 km! Vehicle travelled maximum possible: 100.00 km before running out of fuel. 6. Refueling with 60 Litres (Exceeds capacity): Tank Full! Only 50.0 L could be filled. (Overflow: 10.0 L discarded) Initial Tank Size: 50.0 L | Initial Efficiency: 15.0 km/L | Current Fuel: 50.0 L- Private Instance Variables: All state variables are declared
Q6a. Describe the architecture and components of a Java Servlet.20257m
Module III: Basics of Web Programming
View this question on its own page →Describe the architecture and components of a Java Servlet.
Worked SolutionAnswer: Architecture, Life Cycle, and Components of a Java Servlet
1. What is a Java Servlet?
A Java Servlet is a server-side Java program running inside a Servlet Container (e.g., Apache Tomcat, Jetty, WildFly). It intercepts client requests, executes business logic, interacts with databases, and dynamically generates web responses (HTML, JSON, XML).
+-------------------+ 1. HTTP Request (GET/POST) +---------------------+ | Web Browser | --------------------------------------> | Web Server | | (Client) | <-------------------------------------- | (Apache Tomcat) | +-------------------+ 4. HTTP Response (HTML/JSON) +----------+----------+ | +---------------------v---------------------+ | SERVLET CONTAINER | | | | +-----------------------------------+ | | | Servlet Instance | | | | | | | | - init(ServletConfig config) | | | | - service(req, res) | | | | -> doGet() / doPost() | | | | - destroy() | | | +-----------------------------------+ | +-------------------------------------------+
2. Servlet Life Cycle Methods
The servlet life cycle is entirely managed by the servlet container through three fundamental methods:
[Load & Instantiate] ---> [init()] ---> [service() (doGet / doPost)] ---> [destroy()]- Initialization (
init(ServletConfig config)):- Invoked once when the servlet is first loaded into memory.
- Used for one-time initialization tasks (opening database connections, reading configuration parameters).
- Execution (
service(ServletRequest req, ServletResponse res)):- Invoked for every client request in a separate worker thread.
- For
HttpServlet, theservice()method dispatches the request todoGet(),doPost(),doPut(), ordoDelete()based on the HTTP method.
- Destruction (
destroy()):- Invoked once before the container takes the servlet instance out of service.
- Used to release resources, close database connections, and save state.
3. Major Components of the Servlet Architecture
1.
ServletInterface (jakarta.servlet.Servlet)- The central root interface of all Java servlets. Declares life cycle methods (
init,service,destroy,getServletConfig,getServletInfo).
2.
HttpServletAbstract Class (jakarta.servlet.http.HttpServlet)- Provides an HTTP-specific implementation. Subclassed by developers to handle standard HTTP verbs:
doGet(HttpServletRequest request, HttpServletResponse response)doPost(HttpServletRequest request, HttpServletResponse response)
3.
ServletConfig- Holds initialization parameters and configuration information specific to a single servlet instance defined in
web.xmlor via@WebServlet(initParams={...}).
4.
ServletContext- Represents the broader web application context shared by all servlets in the application.
- Used to store global application-level attributes, communicate between servlets, and access server logs.
5.
HttpServletRequest&HttpServletResponseHttpServletRequest: Encapsulates incoming request data (parameters, headers, cookies, form data, session).HttpServletResponse: Provides methods to set response headers, status codes, cookies, and obtain an output stream (PrintWriterorServletOutputStream) to write content back to the client.
6.
HttpSession- Provides stateful session tracking across multiple HTTP requests for an individual user (e.g., maintaining user login or shopping cart data).
4. Example: Simple HttpServlet Implementation
import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet("/welcome") public class WelcomeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String username = request.getParameter("name"); out.println("<!DOCTYPE html><html><body>"); out.println("<h2>Hello, " + (username != null ? username : "Guest") + "!</h2>"); out.println("</body></html>"); } }- Initialization (
Q6a. What is a constructor in Java? How many types of constructors are there in Java? Explain with examples.20207m
Module III: Basics of Web Programming
View this question on its own page →What is a constructor in Java? How many types of constructors are there in Java? Explain with examples.
Worked SolutionAnswer: Constructors in Java — Types and Examples
1. What is a Constructor in Java?
A Constructor in Java is a special member method invoked automatically at runtime when an instance (object) of a class is created using the
newkeyword. Its primary purpose is to initialize the newly created object's state (instance variables) and allocate necessary resources.+-------------------+ new Student("Rohan", 101) +-----------------------------+ | Client Code | ----------------------------------> | Constructor Invoked | +-------------------+ | Sets name = "Rohan", id=101 | +-----------------------------+Essential Rules for Constructors:
- Name Rule: The constructor name must be identical to the class name.
- No Return Type: It must not have any explicit return type (not even
void). - Modifiers: Cannot be
abstract,static,final, orsynchronized. Access modifiers (public,protected,private, default) are permitted.
2. Types of Constructors in Java
+-----------------------------+ | TYPES OF CONSTRUCTORS | +--------------+--------------+ | +------------------------+------------------------+ | | | v v v +--------------------+ +--------------------+ +--------------------+ | Default / No-Arg | | Parameterized | | Copy Constructor | | Constructor | | Constructor | | (Object Copy) | +--------------------+ +--------------------+ +--------------------+
A. Default / No-Argument Constructor
- If no constructor is defined in a class, the Java compiler automatically inserts a default no-argument constructor that initializes instance variables to default values (
0,null,false). - Programmers can also explicitly define a no-arg constructor to provide default custom values.
class Student { String name; int rollNo; // Explicit No-Argument Constructor Student() { this.name = "Unknown"; this.rollNo = 0; System.out.println("Default/No-Arg Constructor called"); } }
B. Parameterized Constructor
- A constructor that accepts one or more arguments to initialize instance variables with custom values at the time of object instantiation.
class Student { String name; int rollNo; // Parameterized Constructor Student(String name, int rollNo) { this.name = name; this.rollNo = rollNo; System.out.println("Parameterized Constructor called"); } }
C. Copy Constructor
- Java does not have a built-in copy constructor like C++, but programmers create copy constructors by passing an existing object of the same class to initialize a new object with identical attributes.
class Student { String name; int rollNo; // Copy Constructor Student(Student other) { this.name = other.name; this.rollNo = other.rollNo; System.out.println("Copy Constructor called"); } }
3. Comprehensive Code Example (Constructor Overloading & Chaining)
class Book { String title; String author; double price; // 1. No-argument Constructor Book() { this("Untitled", "Anonymous", 0.0); // Constructor chaining using this() } // 2. Parameterized Constructor (2 parameters) Book(String title, String author) { this(title, author, 199.99); } // 3. Parameterized Constructor (3 parameters) Book(String title, String author, double price) { this.title = title; this.author = author; this.price = price; } // 4. Copy Constructor Book(Book other) { this.title = other.title; this.author = other.author; this.price = other.price; } void display() { System.out.println("Title: " + title + " | Author: " + author + " | Price: Rs." + price); } } public class ConstructorDemo { public static void main(String[] args) { Book b1 = new Book(); Book b2 = new Book("Java: Complete Reference", "Herbert Schildt"); Book b3 = new Book("Web Technologies", "Achyut Godbole", 550.0); Book b4 = new Book(b3); // Copy constructor System.out.println(" --- Book Details ---"); b1.display(); b2.display(); b3.display(); b4.display(); } }Output:
--- Book Details --- Title: Untitled | Author: Anonymous | Price: Rs.0.0 Title: Java: Complete Reference | Author: Herbert Schildt | Price: Rs.199.99 Title: Web Technologies | Author: Achyut Godbole | Price: Rs.550.0 Title: Web Technologies | Author: Achyut Godbole | Price: Rs.550.0Q6b. What are Distributed Object Models? Compare CORBA, DCOM, and EJB.20257m
Module III: Basics of Web Programming
View this question on its own page →What are Distributed Object Models? Compare CORBA, DCOM, and EJB.
Worked SolutionAnswer: Distributed Object Models — Comparison of CORBA, DCOM, and EJB
1. What is a Distributed Object Model?
A Distributed Object Model (DOM) is an architectural paradigm in distributed computing where software objects located on different physical machines across a network can communicate and invoke methods on one another as if they were residing in the same local memory space.
+-----------------------+ +-----------------------+ | Client System | | Server System | | | | | | [Client Program] | | [Remote Object] | | | | | ^ | | v | | | | | [Stub/Proxy] | | [Skeleton/Adapter] | | | | | ^ | | v | | | | | [ORB / Runtime] | === Network Communication => | [ORB / Runtime] | +-----------------------+ (IIOP / RPC / RMI) +-----------------------+Core Mechanisms:
- Stub (Client Proxy): Marshals method parameters and serializes calls across the network.
- Skeleton / Dispatcher: Unmarshals parameters on the remote server, invokes the actual method, and serializes the return value back.
2. Overview of CORBA, DCOM, and EJB
A. CORBA (Common Object Request Broker Architecture)
- Specification: Defined by the Object Management Group (OMG) as an open vendor-neutral standard.
- Key Feature: Truly platform-independent and language-independent. Interfaces are defined using OMG IDL (Interface Definition Language).
- Communication: Uses an ORB (Object Request Broker) and communication protocol IIOP (Internet Inter-ORB Protocol).
B. DCOM (Distributed Component Object Model)
- Specification: Developed by Microsoft as a network extension of COM (Component Object Model).
- Key Feature: Deeply integrated into Windows OS; uses Microsoft RPC (Object RPC).
- Limitation: Windows-centric and proprietary, with limited cross-platform interoperability.
C. EJB (Enterprise JavaBeans)
- Specification: Developed by Sun Microsystems / Oracle (now part of Jakarta EE).
- Key Feature: Pure Java-centric server-side component architecture for building transactional, secure, scalable enterprise business logic.
- Container Architecture: Runs inside an EJB Container that automatically handles transactions, security, concurrency, connection pooling, and lifecycle.
3. Detailed Comparison Matrix
Parameter CORBA DCOM EJB Governing Body Object Management Group (OMG) Microsoft Sun / Oracle / Jakarta EE Platform Support Platform Independent (Unix, Linux, Windows) Windows Centric (Limited Unix support) Cross-Platform (Any Java-supported OS) Language Support Multi-language (C++, Java, Python, Ada, COBOL) Multi-language on Windows (C++, VB, C#) Java Only Interface Definition OMG IDL (Interface Definition Language) Microsoft IDL (MIDL) Java Interfaces (Local / Remote) Underlying Protocol IIOP (Internet Inter-ORB Protocol) ORPC (Object Remote Procedure Call) RMI / IIOP Enterprise Services Basic CORBA services (Naming, Event, Security) Microsoft MTS / COM+ Full Container Services (JTA, JPA, Security, Pooling) Architecture Model Client-Server with ORB middleware Binary COM components over network Component-Container model Primary Strength Universal vendor & language interoperability High performance on Windows enterprise environments Rapid enterprise development with built-in declarative services Weakness Steep learning curve, complex configuration Windows lock-in, poor firewall traversal Restricted to Java ecosystem
Conclusion
- CORBA is ideal for heterogeneous legacy integration across multiple programming languages and OS platforms.
- DCOM provided high performance in pure Microsoft Windows environments before modern Web APIs.
- EJB remains the enterprise standard for pure Java distributed systems, offering automated transactional and container-managed persistence capabilities.
Q6b. List the applications of object-oriented programming. What is the significance of Java's byte code?20207m
Module III: Basics of Web Programming
View this question on its own page →List the applications of object-oriented programming. What is the significance of Java's byte code?
Worked SolutionAnswer: Applications of OOP and Significance of Java Bytecode
Part 1: Major Applications of Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) organizes software design around data, or objects, and well-defined interfaces rather than functions and sequential logic. Major real-world applications include:
+-----------------------------+ | APPLICATIONS OF OOP | +--------------+--------------+ | +-------------------+--------------------+--------------------+-------------------+ | | | | | v v v v v +---------+ +---------+ +---------+ +---------+ +---------+ | GUI | | Real-time| | Game | | Database| | Web & | | Systems | | Simulators | Engines | | (OODBMS)| | Cloud | +---------+ +---------+ +---------+ +---------+ +---------+- Graphical User Interfaces (GUI) & Windowing Systems:
- GUI frameworks (Java Swing/JavaFX, Android SDK, Qt) model visual components (Windows, Buttons, TextBoxes, Menus) as hierarchical object classes inheriting common event-handling behaviors.
- Real-Time Simulation & Modeling:
- Complex physical systems (aerospace flight simulators, weather modeling, autonomous vehicle simulators) use objects to represent physical entities with state and physics behaviors.
- Game Development & Computer Graphics:
- Game engines (Unreal, Unity) model game worlds, characters, physics bodies, and inventory items through polymorphic classes and component inheritance.
- Enterprise Web & Distributed Cloud Systems:
- Tiered e-commerce platforms and banking applications use OOP principles (encapsulation, abstraction) to model business domains (Users, Accounts, Orders, Transactions) with secure boundaries.
- Object-Oriented Databases (OODBMS):
- Databases like db4o and ObjectDB store complex data types and direct object graphs without requiring relational Object-Relational Mapping (ORM) translation.
- Artificial Intelligence & Expert Systems:
- Models neural networks, knowledge graphs, and decision agents through specialized object hierarchies.
Part 2: Significance of Java's Bytecode
1. What is Bytecode?
Java Bytecode is the highly optimized, platform-independent intermediate instruction set generated by the Java Compiler (
javac). It is stored in binary files with a.classextension and is designed to be executed by the Java Virtual Machine (JVM).Java Source (.java) ---> [ javac ] ---> Bytecode (.class) ---> [ JVM on Windows/Linux/Mac ] ---> CPU
2. Key Significance & Advantages of Bytecode
- Platform Independence ("Write Once, Run Anywhere - WORA"):
- The developer compiles source code once into
.classbytecode. The identical bytecode file can execute on Windows, Linux, macOS, Solaris, or Android without recompilation, provided a compatible JVM is installed.
- The developer compiles source code once into
- Robust Security & Sandboxing:
- Before executing bytecode, the JVM's Bytecode Verifier checks the code for unsafe operations:
- No illegal pointer access or direct hardware memory tampering.
- Type-safety enforcement and stack overflow prevention.
- Array bounds checking.
- Before executing bytecode, the JVM's Bytecode Verifier checks the code for unsafe operations:
- Execution Performance via JIT Compilers:
- Bytecode is not purely interpreted. The JVM's Just-In-Time (JIT) Compiler compiles frequently executed bytecode blocks ("hot spots") into native CPU machine code at runtime, providing execution speeds comparable to C++.
- Polyglot Ecosystem (Multi-Language Support on JVM):
- The JVM only requires valid bytecode. Consequently, multiple modern programming languages (such as Kotlin, Scala, Groovy, and Clojure) compile directly into standard Java bytecode, sharing the entire Java ecosystem and standard libraries.
- Network Efficiency & Compactness:
- Bytecode instructions are compact (often single-byte opcodes), enabling fast transmission over networks (applets, dynamic remote class loaders, microservices).
Summary
- OOP provides modularity, maintainability, and reusability for modeling complex real-world software.
- Java Bytecode is the architectural cornerstone that grants Java its signature cross-platform portability, high security, and performance.
- Graphical User Interfaces (GUI) & Windowing Systems:
Q7. Write a program to display current cursor position of the mouse pointer on an Applet using MouseMotionListener interface.201914m
Module III: Basics of Web Programming
View this question on its own page →Write a program to display current cursor position of the mouse pointer on an Applet using MouseMotionListener interface.
Worked SolutionAnswer: Java Applet Program to Track Mouse Cursor Position
1. Overview
In Java AWT/Applet programming, tracking mouse movement is handled by the
MouseMotionListenerinterface from thejava.awt.eventpackage.The
MouseMotionListenerinterface provides two callback methods:mouseMoved(MouseEvent e): Invoked every time the mouse cursor moves within the Applet component boundaries without buttons pressed.mouseDragged(MouseEvent e): Invoked when the mouse is moved while a mouse button is pressed.
[ User Moves Mouse ] ---> [ MouseEvent Fired ] ---> [ mouseMoved(e) extracts X, Y ] ---> [ repaint() ] ---> [ paint(g) draws text ]
2. Complete Java Applet Code
import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; /* <applet code="MouseTrackerApplet.class" width="500" height="400"> </applet> */ public class MouseTrackerApplet extends Applet implements MouseMotionListener { // Variables to store mouse cursor coordinates and status private int mouseX = 0; private int mouseY = 0; private String statusMsg = "Move the mouse inside this Applet window..."; // Initialization method of Applet life cycle @Override public void init() { // Set Applet background and foreground colors setBackground(new Color(245, 246, 242)); setForeground(new Color(27, 36, 48)); setFont(new Font("SansSerif", Font.BOLD, 14)); // Register the Applet to listen to mouse motion events addMouseMotionListener(this); } // Invoked when the mouse is moved without pressing any button @Override public void mouseMoved(MouseEvent e) { mouseX = e.getX(); // Get current X coordinate mouseY = e.getY(); // Get current Y coordinate statusMsg = "Mouse Moving at: X = " + mouseX + ", Y = " + mouseY; repaint(); // Request JVM to re-render the Applet screen } // Invoked when the mouse is dragged with a button pressed @Override public void mouseDragged(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); statusMsg = "Mouse Dragged at: X = " + mouseX + ", Y = " + mouseY; repaint(); // Request JVM to re-render } // Paint method to render graphics and text on the screen @Override public void paint(Graphics g) { // Display header banner g.setColor(new Color(31, 75, 67)); g.fillRect(20, 20, 460, 40); g.setColor(Color.WHITE); g.drawString("JAVA APPLET MOUSE POSITION TRACKER", 80, 45); // Display current cursor coordinates g.setColor(new Color(178, 58, 46)); g.drawString(statusMsg, 30, 100); // Draw crosshair indicator at current cursor position if (mouseX > 0 && mouseY > 0) { g.setColor(Color.BLUE); g.drawOval(mouseX - 10, mouseY - 10, 20, 20); // Circle around cursor g.drawLine(mouseX - 15, mouseY, mouseX + 15, mouseY); // Horizontal line g.drawLine(mouseX, mouseY - 15, mouseX, mouseY + 15); // Vertical line // Draw small coordinate tooltip near cursor g.setFont(new Font("Monospaced", Font.PLAIN, 11)); g.drawString("(" + mouseX + ", " + mouseY + ")", mouseX + 12, mouseY - 8); } } }
3. HTML Code to Embed the Applet (
index.html)<!DOCTYPE html> <html> <head> <title>Mouse Motion Applet</title> </head> <body> <h2>Java Applet: Real-Time Mouse Pointer Coordinates</h2> <applet code="MouseTrackerApplet.class" width="500" height="400"> Your browser does not support Java Applets. </applet> </body> </html>
4. Execution Steps
- Compile the Applet:
javac MouseTrackerApplet.java - Run using AppletViewer (JDK tool):
(Or openappletviewer MouseTrackerApplet.javaindex.htmlin an applet-compatible browser environment).
5. Method Responsibilities Summary
Method Role init()Configures background color and attaches addMouseMotionListener(this).mouseMoved(MouseEvent e)Extracts using e.getX()ande.getY()when cursor is moving freely, then callsrepaint().mouseDragged(MouseEvent e)Extracts during drag gestures. paint(Graphics g)Draws status text and crosshair graphics using coordinates onto the graphics context. Q7a. With suitable code segments, illustrate various uses of 'final' keyword. Discuss about anonymous inner classes.20207m
Module III: Basics of Web Programming
View this question on its own page →With suitable code segments, illustrate various uses of 'final' keyword. Discuss about anonymous inner classes.
Worked SolutionAnswer: Uses of 'final' Keyword and Anonymous Inner Classes in Java
Part 1: Various Uses of the 'final' Keyword in Java
In Java, the
finalnon-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.
finalVariable (Constants)- A
finalvariable'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.
finalMethod (Prevents Method Overriding)- Declaring a method as
finalprevents 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.
finalClass (Prevents Inheritance)- A
finalclass 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
.javaclass 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:
- No Constructor: Since it has no name, it cannot define a constructor.
- Access Rules: Can access instance variables of the enclosing class and local variables in scope (provided the local variables are
finalor effectively final). - Compiled Name: The compiler generates class files with numbering:
OuterClassName2.class.
- A
Q7b. What are the benefits of inheritance? Explain the various forms of inheritance with suitable code segments.20207m
Module III: Basics of Web Programming
View this question on its own page →What are the benefits of inheritance? Explain the various forms of inheritance with suitable code segments.
Worked SolutionAnswer: 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
extendskeyword. It models an "IS-A" relationship.
2. Benefits of Inheritance
- Code Reusability: Subclasses automatically inherit existing, tested methods from parent classes without re-writing code.
- Runtime Polymorphism: Enables dynamic method dispatch through method overriding (
@Override), allowing polymorphic code behavior. - Data Encapsulation & Hierarchy: Organizes classes into clear, logical, and maintainable domain hierarchies (e.g.,
Vehicle -> Car -> ElectricCar). - 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 ()
- 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 ()
- 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 ( and )
- 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
implementskeyword.
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."); } }Q8. Write an Applet application which will display colours in list box and a scrolling banner which scrolls from left to right within a browser. When user selects any color from the list, it changes the color of scrolling banner.201914m
Module III: Basics of Web Programming
View this question on its own page →Write an Applet application which will display colours in list box and a scrolling banner which scrolls from left to right within a browser. When user selects any color from the list, it changes the color of scrolling banner.
Worked SolutionAnswer: Java Applet Application — Color List Box & Scrolling Banner
1. Problem Requirements Breakdown
- Color List Box (
java.awt.List): Displays multiple color names (e.g., Red, Green, Blue, Magenta, Orange) allowing user selection. - Scrolling Banner: A text banner that continuously scrolls horizontally from left to right across the Applet screen using a background
Thread(Runnableinterface). - Dynamic Color Change (
ItemListener): When the user selects a color from the list, the banner's text/fill color dynamically updates to the selected color.
+-------------------------------------------------------------+ | [ Color List Box ] SCROLLING BANNER TEXT -----> | | | Red | (Updates X position in Thread) | | | Green | | | | Blue | (Selected color updates text) | | | Magenta | | +-------------------------------------------------------------+
2. Complete Java Applet Source Code
import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.List; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; /* <applet code="ColorBannerApplet.class" width="650" height="350"> </applet> */ public class ColorBannerApplet extends Applet implements Runnable, ItemListener { // GUI List Box for selecting colors private List colorList; // Scrolling Banner properties private String bannerText = "Welcome to Bihar Engineering University - Web Technology Exam Archive"; private int bannerX = -300; // Starting X coordinate (left) private int bannerY = 220; // Y coordinate private Color bannerColor = Color.RED; // Default banner color // Animation thread private Thread animationThread = null; private volatile boolean running = false; // Applet Initialization @Override public void init() { setLayout(null); // Absolute positioning layout setBackground(new Color(245, 246, 242)); // 1. Create and populate the Color List Box colorList = new List(5, false); // 5 visible rows, single selection colorList.add("Red"); colorList.add("Green"); colorList.add("Blue"); colorList.add("Magenta"); colorList.add("Orange"); colorList.add("Dark Teal"); colorList.add("Black"); // Set position and dimensions of the list box colorList.setBounds(30, 60, 140, 110); colorList.select(0); // Select 'Red' by default // Register ItemListener to capture user selection colorList.addItemListener(this); // Add component to Applet add(colorList); } // Applet Start: Launch Animation Thread @Override public void start() { if (animationThread == null) { running = true; animationThread = new Thread(this); animationThread.start(); } } // Animation Loop: Scrolls Banner from Left to Right @Override public void run() { while (running) { // Move banner coordinate to the right bannerX += 5; // When the banner scrolls off the right edge, wrap back to the left if (bannerX > getWidth()) { bannerX = -gEstimateTextWidth(); } repaint(); // Request screen redraw try { Thread.sleep(60); // Control scrolling speed (approx 16 FPS) } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } // Rough text width estimation for wrapping private int gEstimateTextWidth() { return bannerText.length() * 10; } // Applet Stop: Stop Thread cleanly @Override public void stop() { running = false; animationThread = null; } // Event Handler for List Box Selection @Override public void itemStateChanged(ItemEvent e) { String selected = colorList.getSelectedItem(); if ("Red".equalsIgnoreCase(selected)) { bannerColor = new Color(178, 58, 46); } else if ("Green".equalsIgnoreCase(selected)) { bannerColor = new Color(34, 139, 34); } else if ("Blue".equalsIgnoreCase(selected)) { bannerColor = new Color(0, 102, 204); } else if ("Magenta".equalsIgnoreCase(selected)) { bannerColor = new Color(180, 0, 180); } else if ("Orange".equalsIgnoreCase(selected)) { bannerColor = new Color(230, 120, 0); } else if ("Dark Teal".equalsIgnoreCase(selected)) { bannerColor = new Color(31, 75, 67); } else if ("Black".equalsIgnoreCase(selected)) { bannerColor = Color.BLACK; } repaint(); // Immediately redraw with new color } // Screen Paint Rendering @Override public void paint(Graphics g) { // UI Labels g.setColor(new Color(27, 36, 48)); g.setFont(new Font("SansSerif", Font.BOLD, 15)); g.drawString("Select Banner Color:", 30, 45); // Banner Track Area Box g.setColor(new Color(235, 237, 231)); g.fillRect(10, 185, getWidth() - 20, 70); g.setColor(new Color(219, 223, 215)); g.drawRect(10, 185, getWidth() - 20, 70); // Draw Scrolling Banner g.setColor(bannerColor); g.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 20)); g.drawString(bannerText, bannerX, bannerY); } }
3. HTML Deployment File (
banner.html)<!DOCTYPE html> <html> <head> <title>Color Banner Applet Demo</title> </head> <body> <h2>Java Applet: Scrolling Banner with Color Selector</h2> <applet code="ColorBannerApplet.class" width="650" height="350"> Java Applets are not supported in your environment. </applet> </body> </html>
4. Lifecycle & Flow Explanation
init(): Creates theListcomponent, populates color names, sets absolute bounds (setBounds), and registersaddItemListener(this).start()/run(): Starts the background thread that continuously incrementsbannerXby 5 pixels and invokesThread.sleep(60)to produce smooth left-to-right scrolling.itemStateChanged(): Triggers immediately when a user clicks any color in the list, maps the selection to ajava.awt.Colorobject, and updatesbannerColor.paint(): Renders the background container and draws the text at dynamic position(bannerX, bannerY)withbannerColor.
- Color List Box (
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
View this question on its own page →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.
Worked SolutionAnswer: 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()returningdouble.
- Instance variables:
- Subclasses:
Rectangle: Overridesarea()to compute .Triangle: Overridesarea()to compute .
- 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
- Inheritance (
extends&super): The subclasses inherit fieldsdim1anddim2and pass values usingsuper(dim1, dim2). - Method Overriding (
@Override): Subclasses provide specific implementations of the inheritedarea()method. - Runtime Polymorphism / Dynamic Method Dispatch: The Java Virtual Machine resolves the call
figRef.area()dynamically at runtime based on the actual object type referenced byfigRef, rather than the reference type.
- Superclass:
Q9. Write short notes on any two of the following: (a) AWT (b) Exception Handling (c) DHTML and HTML (d) API201914m
Module III: Basics of Web Programming
View this question on its own page →Write short notes on any two of the following:
(a) AWT
(b) Exception Handling
(c) DHTML and HTML
(d) APIWorked SolutionAnswer: Short Notes on Core Web & Java Concepts
(a) AWT (Abstract Window Toolkit)
AWT (
java.awt) is Java's original, platform-dependent Graphical User Interface (GUI) toolkit introduced in JDK 1.0.+-----------------------------+ | Component (Base Class) | +--------------+--------------+ | +------------------------+------------------------+ | | v v +--------------------+ +--------------------+ | Basic Controls | | Container | | Button, Checkbox, | | (Panel, Window, | | TextField, List | | Frame, Dialog) | +--------------------+ +--------------------+Key Architectural Characteristics:
- Heavyweight Peer Components: AWT components map directly to native operating system peer widgets (e.g., a
Buttonin AWT creates a Windows button on Windows and a Motif button on Solaris). - Container Hierarchy:
Frame: Top-level application window with title bar, border, and control icons.Panel: Nested container used to group and layout UI elements.
- Layout Managers: Automatically calculates layout coordinates across different screen resolutions (
BorderLayout,FlowLayout,GridLayout,GridBagLayout). - Event Delegation Model: Decouples event sources from event listeners using interfaces like
ActionListener,MouseListener, andKeyListener.
(b) Exception Handling in Java
Exception Handling in Java is a robust mechanism to intercept, handle, and recover from runtime errors (e.g.,
NullPointerException,ArithmeticException,IOException,SQLException), ensuring the normal flow of the application does not abruptly crash.+-----------------------------+ | Throwable | +--------------+--------------+ | +------------------------+------------------------+ | | v v +--------------------+ +--------------------+ | Exception | | Error | | (Can be Handled) | | (Unrecoverable OS/ | | Checked & Unchecked| | JVM System Fail) | +--------------------+ +--------------------+The 5 Core Keywords:
try: Encloses code that might throw an exception.catch: Handles the specific thrown exception.finally: Executes cleanup code (closing files/connections) regardless of whether an exception occurred.throw: Explicitly throws a custom or standard exception instance.throws: Declares exceptions a method might throw to caller methods.
try { int result = 50 / 0; // Throws ArithmeticException } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero: " + e.getMessage()); } finally { System.out.println("Cleanup executed regardless of exception."); }
(c) Comparison: HTML vs. DHTML
Parameter HTML (HyperText Markup Language) DHTML (Dynamic HTML) Definition Standard static markup language for structuring web pages. Combination of HTML, CSS, JavaScript, and DOM. Interactivity Static display of text, images, and links. Rich interactivity, client-side animation, drag-and-drop. Server Dependence Requires page refresh/server request to change content. Updates content dynamically in-place without page reload. Technologies Pure HTML markup tags ( <h1>,<p>,<table>).HTML + CSS Positioning + JavaScript + DOM API. Complexity Simple, easy to learn and parse. Moderate to complex scripting logic.
(d) API (Application Programming Interface)
An API (Application Programming Interface) is a formal set of defined rules, protocols, data structures, and functions that allows one software application to communicate, exchange data, and interact with another software system.
[ Client App / Frontend ] <==== (JSON / REST API over HTTP) ====> [ Server API / Database ]Major Categories of APIs:
- Language / Library APIs: Built-in SDK classes (e.g., Java Collections API, Java Stream API, Python
mathmodule). - Web APIs (RESTful / GraphQL / SOAP): Network endpoints that exchange structured JSON/XML data over HTTP (e.g., Stripe Payment API, Google Maps API, Weather API).
- Operating System APIs: Low-level system routines providing hardware and file access (e.g., Windows Win32 API, POSIX system calls).
Key Benefits of APIs:
- Modularity & Reusability: Developers can integrate complex functionality (payments, maps, AI models) without building from scratch.
- Security & Controlled Access: Exposes only necessary data/endpoints while hiding internal implementation details and database logic.
- Heavyweight Peer Components: AWT components map directly to native operating system peer widgets (e.g., a