2020 question paper
Web Technology
20 questions
Q1a. Who is making the Web standards? (i) Mozilla (ii) Microsoft (iii) The World Wide Web Consortium (iv) NVDIA20202m
Module I: Introduction to Web Technologies & Architectures
View this question on its own page →Who is making the Web standards?
(i) Mozilla
(ii) Microsoft
(iii) The World Wide Web Consortium
(iv) NVDIAWorked SolutionCorrect Answer: (iii) The World Wide Web Consortium (W3C)
Explanation:
- The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web, founded in 1994 by Tim Berners-Lee.
- W3C develops open standards (recommendations) such as HTML, CSS, XML, SVG, and WAI-ARIA to ensure the long-term growth and interoperability of the Web.
- Mozilla and Microsoft are commercial/non-profit software vendors that build web browsers and participate as members in standards bodies (like W3C and WHATWG).
- NVIDIA is a semiconductor and GPU hardware company.
Q1b. If you want to align text to the right side of a block element in a cascading style sheet (CSS), then which of...20202m
Module I: Introduction to Web Technologies & Architectures
View this question on its own page →If you want to align text to the right side of a block element in a cascading style sheet (CSS), then which of...
Worked SolutionCorrect Answer:
text-align: right;Explanation:
- In Cascading Style Sheets (CSS), the
text-alignproperty specifies the horizontal alignment of inline content (like text, images, or inline blocks) within a block element or table-cell box. - Setting
text-align: right;aligns the text flush with the right edge of the containing block element.
Syntax & Example:
p { text-align: right; }Common
text-alignValues:left: Aligns text to the left margin (default in LTR languages).right: Aligns text to the right margin.center: Centers the text horizontally.justify: Stretches lines so that every line has equal width.
- In Cascading Style Sheets (CSS), the
Q1c. Markup tags tell the Web browser (i) how to organize the page (ii) how to display the page (iii) how to display message box on page (iv) None of the above20202m
Module I: Introduction to Web Technologies & Architectures
View this question on its own page →Markup tags tell the Web browser
(i) how to organize the page
(ii) how to display the page
(iii) how to display message box on page
(iv) None of the aboveWorked SolutionCorrect Answer: (ii) how to display the page
Explanation:
- Markup tags (HTML tags such as
<h1>,<p>,<table>,<img>) are keywords enclosed in angle brackets that instruct the web browser on how to format, structure, and display text, multimedia, and layout elements on the screen. - The browser reads markup tags to construct the Document Object Model (DOM) and render the visual page according to the specified semantics and styling.
- Markup tags (HTML tags such as
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. Which of the following is an advantage of putting presentation information in a separate CSS file rather than in HTML itself? (i) The content becomes easy to manage (ii) Becomes easy to make site for different devices like mobile by making separate CSS files (iii) CSS files are generally cached and therefore decrease server load and network traffic (iv) All of the above20202m
Module I: Introduction to Web Technologies & Architectures
View this question on its own page →Which of the following is an advantage of putting presentation information in a separate CSS file rather than in HTML itself?
(i) The content becomes easy to manage
(ii) Becomes easy to make site for different devices like mobile by making separate CSS files
(iii) CSS files are generally cached and therefore decrease server load and network traffic
(iv) All of the aboveWorked SolutionCorrect Answer: (iv) All of the above
Explanation:
Separating presentation rules into an external
.cssfile provides several key advantages:- Maintainability & Separation of Concerns (i): HTML structure is decoupled from visual styling, allowing sitewide design changes by editing a single CSS file.
- Device Independence & Responsiveness (ii): Enables targeting distinct devices (mobiles, tablets, print) through separate stylesheets or CSS media queries (
@media). - Browser Caching & Performance (iii): External CSS files are cached by the browser after the first download, drastically reducing bandwidth consumption, network traffic, and server load on subsequent page requests.
Therefore, (iv) All of the above is the correct option.
Q1i. What does error 404 or Not Found error while accessing a URL mean? (i) The server could not find the requested URL (ii) Requested HTML file is not available (iii) The path to the interpreter of the script is not valid (iv) The requested HTML file does not have sufficient permissions20202m
Module II: Browser & Apache Web Server Architecture; Common Protocols
View this question on its own page →What does error 404 or Not Found error while accessing a URL mean?
(i) The server could not find the requested URL
(ii) Requested HTML file is not available
(iii) The path to the interpreter of the script is not valid
(iv) The requested HTML file does not have sufficient permissionsWorked SolutionCorrect Answer: (i) The server could not find the requested URL
Explanation:
- The HTTP 404 Not Found status code is a standard client-side error response indicating that the origin web server successfully received the client's request, but could not locate the requested resource (URL/endpoint) on the server.
- Common causes: Broken/dead links, mistyped URL paths, deleted pages, or missing URL rewrite routing rules.
Other Related HTTP Status Codes:
- 401 Unauthorized / 403 Forbidden: The user lacks sufficient permissions to access the resource.
- 500 Internal Server Error: The server encountered an unexpected error or script interpreter failure.
- 502 Bad Gateway: An upstream server failed to respond properly.
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
Q2a. Explain about domain name, IP address and WWW.20207m
Module I: Introduction to Web Technologies & Architectures
View this question on its own page →Explain about domain name, IP address and WWW.
Worked SolutionAnswer: Domain Name, IP Address, and the World Wide Web (WWW)
1. Introduction
The internet relies on standardized addressing systems and information retrieval architectures to enable global communication between millions of interconnected computers. IP Addresses, Domain Names, and the World Wide Web (WWW) form the core foundation of this ecosystem.
+-------------------+ DNS Resolution +-------------------+ | Domain Name | ------------------------> | IP Address | | (www.example.com) | <------------------------ | (93.184.216.34) | +-------------------+ +---------+---------+ | | | HTTP/HTTPS Request | Connects over +-----------------------------------------------> TCP/IP Network | +---------v---------+ | WWW Resource | | (Web Page / HTML) | +-------------------+
2. IP Address (Internet Protocol Address)
An IP address is a unique numerical identifier assigned to every device connected to a computer network that uses the Internet Protocol for communication.
Key Characteristics:
- Addressing & Routing: Acts as a network identifier and location address to deliver packets to their destination.
- Versions of IP:
- IPv4 (32-bit): Formatted as 4 octets separated by dots (e.g.,
192.168.1.1). Provides addresses. - IPv6 (128-bit): Formatted as 8 groups of hexadecimal digits separated by colons (e.g.,
2001:0db8:85a3::8a2e:0370:7334) to overcome IPv4 exhaustion.
- IPv4 (32-bit): Formatted as 4 octets separated by dots (e.g.,
- Static vs. Dynamic IP:
- Static IP: Permanent address configured for servers.
- Dynamic IP: Temporarily leased address assigned by DHCP.
3. Domain Name
A Domain Name is a human-readable alias used to access websites without needing to remember numeric IP addresses (e.g.,
google.cominstead of142.250.190.46).Structure of a Domain Name:
https:// subdomain . second-level-domain . top-level-domain (TLD) ( www . example . com )- Top-Level Domain (TLD): Generic (
.com,.org,.edu) or country-code (.in,.uk,.us). - Second-Level Domain (SLD): The organization or brand name (
google,wikipedia). - Subdomain: Specific section or server (
mail.google.com,api.example.com).
DNS (Domain Name System):
The global hierarchical database that translates human-friendly domain names into machine-routable IP addresses.
4. WWW (World Wide Web)
Invented in 1989 by Tim Berners-Lee at CERN, the World Wide Web (WWW) is an interconnected system of public hypertext documents and multimedia resources accessible over the Internet via the HTTP/HTTPS protocol.
Core Architectural Pillars of the WWW:
- URI/URL (Uniform Resource Locator): Standardized global address to locate any document (e.g.,
https://www.example.com/index.html). - HTTP/HTTPS: The application-layer communication protocol for exchanging web documents.
- HTML (HyperText Markup Language): The standard formatting language used to structure web content and hyperlinks.
- Web Browsers & Web Servers: The client software that renders pages and the server software that delivers them.
5. Summary Comparison
Concept Nature Function Example IP Address Numerical identifier Identifies physical machine on network 142.250.190.46Domain Name Human-friendly text name Mapped to IP for user convenience www.google.comWWW Global information system Application running on the Internet Web pages, hypermedia, web apps Q2b. What are logical and physical tags in HTML? What is CSS?20207m
Module I: Introduction to Web Technologies & Architectures
View this question on its own page →What are logical and physical tags in HTML? What is CSS?
Worked SolutionAnswer: Physical vs Logical Tags in HTML and Introduction to CSS
1. Physical vs. Logical Tags in HTML
HTML tags used for formatting text are historically categorized into Physical Tags and Logical Tags:
+-----------------------------+ | HTML FORMATTING TAGS | +--------------+--------------+ | +------------------------+------------------------+ | | v v +--------------------+ +--------------------+ | PHYSICAL TAGS | | LOGICAL TAGS | | (Visual Appearance)| | (Semantic Meaning) | | <b>, <i>, <u> | | <strong>, <em> | +--------------------+ +--------------------+
A. Physical Tags
- Definition: Physical tags tell the browser strictly how to visually render the enclosed text (its appearance/style) without conveying any semantic meaning, importance, or context.
- Characteristics: Focused entirely on visual layout; ignored by assistive screen readers in terms of vocal inflection.
- Examples:
<b>Text</b>: Renders text in bold style.<i>Text</i>: Renders text in italicized style.<u>Text</u>: Underlines the text.<s>Text</s>or<strike>: Renders text with a strikethrough line.<tt>Text</tt>: Displays text in fixed-width teletype font.<sub>/<sup>: Subscript and superscript formatting.
B. Logical Tags (Semantic Tags)
- Definition: Logical tags describe the semantic meaning, purpose, or structural importance of the enclosed content to the browser, search engines, and screen readers.
- Characteristics: The browser standardly provides default formatting (e.g.,
<strong>is bolded,<em>is italicized), but screen readers adjust voice tone and emphasis accordingly. - Examples:
<strong>Text</strong>: Indicates strong importance or urgency (default rendered as bold).<em>Text</em>: Indicates emphasized stress (default rendered as italic).<code>Text</code>: Defines a snippet of computer code (monospace).<cite>Text</cite>: References the title of a creative work or author.<mark>Text</mark>: Highlights relevant text for reference.<abbr title="World Health Organization">WHO</abbr>: Defines an abbreviation or acronym.
C. Comparison Table
Parameter Physical Tags Logical (Semantic) Tags Focus Visual appearance and styling Meaning, context, and structural value Accessibility (Screen Readers) Treated as normal text without vocal change Read with appropriate vocal stress and emphasis SEO Impact Minimal search engine value High value for search engine indexers W3C Recommendation Deprecated in modern HTML5 (use CSS instead) Strongly recommended in modern semantic HTML Examples <b>,<i>,<u>,<tt>,<big><strong>,<em>,<code>,<cite>,<abbr>
2. What is CSS (Cascading Style Sheets)?
CSS (Cascading Style Sheets) is a style sheet language used to describe the visual presentation, layout, colors, typography, and responsive design of a document written in HTML or XML.
CSS Rule Syntax:
/* Selector { Property: Value; } */ h1 { color: #b23a2e; font-size: 24px; text-align: center; }Three Ways to Apply CSS in HTML:
- Inline CSS: Applied directly to an element via the
styleattribute:<p style="color: red; font-size: 14px;">Inline Styled Text</p> - Internal (Embedded) CSS: Written inside
<style>tags within the<head>section:<style> body { background-color: #f5f6f2; } </style> - External CSS (Best Practice): Stored in a separate
.cssfile and linked in<head>:<link rel="stylesheet" href="styles.css">
Key Benefits of CSS:
- Separation of Content and Design: Keeps HTML clean and easy to maintain.
- Faster Page Load: External stylesheets are cached by browsers.
- Responsive Layouts: Media queries (
@media) allow dynamic adaptation across mobile, tablet, and desktop viewports.
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 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)); } }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. 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:
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. 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 the following : (a) HTML commands (b) DHTML dragging and drooping (c) AWT (d) JDBC202014m
Module I: Introduction to Web Technologies & Architectures
View this question on its own page →Write short notes on the following :
(a) HTML commands
(b) DHTML dragging and drooping
(c) AWT
(d) JDBCWorked SolutionAnswer: Short Notes on Web & Java Technologies
(a) HTML Commands (Tags & Elements)
HTML (HyperText Markup Language) commands (commonly referred to as HTML tags and elements) are syntax keywords enclosed within angle brackets (
<tagname>) used to define the structure, content, and hypermedia links of a webpage.Core HTML Command Categories:
- Document Skeleton Commands:
<!DOCTYPE html>: Declares HTML5 document type.<html>,<head>,<body>: Defines the root, metadata, and visible document body.
- Text Formatting Commands:
<h1>to<h6>: Headings;<p>: Paragraph;<br>: Line break;<hr>: Horizontal rule.
- Hyperlinks & Media Commands:
<a href="...">: Creates clickable hyperlinks.<img src="..." alt="...">: Embeds images.
- Lists & Tables:
<ul>,<ol>,<li>: Unordered (bulleted) and ordered (numbered) lists.<table>,<tr>,<th>,<td>: Renders structured tabular data.
- Interactive Forms:
<form>,<input>,<select>,<button>,<textarea>: Collects user data.
(b) DHTML Dragging and Dropping
DHTML (Dynamic HTML) is not a standalone language, but rather the synergistic combination of HTML, CSS, JavaScript, and the Document Object Model (DOM) to create interactive, animated web pages.
Drag and Drop Mechanism:
Drag and Drop allows users to click, grab an onscreen element, drag it over a target zone, and drop it.
[Draggable Element] -- (dragstart) --> [Dragging Over Target] -- (drop) --> [Dropped Element] (draggable="true") (event.preventDefault()) (dataTransfer)Core HTML5 / DHTML Drag-and-Drop Events:
dragstart: Fires when the user starts dragging an element. Usesevent.dataTransfer.setData("text", target.id)to store data.dragover: Fires continuously when a dragged element is over a valid drop target. Must invokeevent.preventDefault()to allow dropping.drop: Fires when the dragged item is released over the drop target. Retrieves data viaevent.dataTransfer.getData("text").
<div id="dragItem" draggable="true" ondragstart="event.dataTransfer.setData('text', this.id)"> Drag Me </div> <div id="dropZone" ondragover="event.preventDefault()" ondrop="this.appendChild(document.getElementById(event.dataTransfer.getData('text')))"> Drop Zone </div>
(c) AWT (Abstract Window Toolkit)
AWT (
java.awt) is Java's original, platform-dependent Graphical User Interface (GUI) framework introduced in JDK 1.0.+-----------------------------+ | Component | +--------------+--------------+ | +------------------------+------------------------+ | | v v +--------------------+ +--------------------+ | Basic Controls | | Container | | Button, Checkbox, | | (Panel, Window, | | Label, TextField | | Frame, Dialog) | +--------------------+ +--------------------+Key Features of AWT:
- Heavyweight Components: AWT components rely directly on the underlying operating system's native GUI peer widgets (e.g., a
java.awt.Buttoncreates a native Windows button on Windows and a Motif button on Unix). - Container Hierarchy:
Frame: Top-level window with a title bar, border, and minimize/maximize buttons.Panel: Space-allocating container used to group components.
- Layout Managers: Automatically arrange component geometry (
FlowLayout,BorderLayout,GridLayout,GridBagLayout). - Event Delegation Model: Decouples event sources (e.g.,
Button) from event listeners (ActionListener,MouseListener).
(d) JDBC (Java Database Connectivity)
JDBC (
java.sql/javax.sql) is the standard Java API specification that enables Java applications to interact independently with relational database management systems (RDBMS like MySQL, Oracle, PostgreSQL).+-----------------------+ | Java Application | +-----------+-----------+ | (JDBC API Calls) v +-----------------------+ | JDBC DriverManager | +-----------+-----------+ | v +-----------------------+ | JDBC Driver (MySQL) | +-----------+-----------+ | (Database Protocol) v +-----------------------+ | RDBMS Database | +-----------------------+Standard 5 Steps to Execute JDBC Operations:
- Load Driver Class:
Class.forName("com.mysql.cj.jdbc.Driver"); - Establish Database Connection:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "password"); - Create Statement:
Statement stmt = con.createStatement(); // Or PreparedStatement for parameterized SQL - Execute SQL Query:
ResultSet rs = stmt.executeQuery("SELECT * FROM students"); while (rs.next()) { System.out.println(rs.getInt("roll_no") + " : " + rs.getString("name")); } - Close Resources:
rs.close(); stmt.close(); con.close();
- Document Skeleton Commands: