2023 question paper
Web Technology
23 questions
Q1(a). What is scriptlet?20232m
Module III: Basics of Web Programming
View this question on its own page →What is scriptlet?
Worked SolutionA scriptlet is a block of Java code embedded directly inside a JSP (JavaServer Pages) page, written between
<%and%>. The code runs on the server each time the page is requested, and its output becomes part of the HTML sent to the browser.<% int count = 5; for (int i = 1; i <= count; i++) { out.println("Line " + i + "<br>"); } %>Related JSP elements: declaration
<%! ... %>, expression<%= ... %>, and directive<%@ ... %>.Q1(b). Explain the role of web browser.20232m
Module II: Browser and Apache Web Server Architecture
View this question on its own page →Explain the role of web browser.
Worked SolutionA web browser is client software that lets a user request, retrieve, and view web resources.
- Sends requests: builds HTTP/HTTPS requests for a URL and sends them to the web server.
- Receives responses: downloads the HTML, CSS, JavaScript, images, and other resources.
- Renders pages: parses HTML into the DOM and CSS into the CSSOM, then lays out and paints the page.
- Runs scripts: executes JavaScript through its engine (e.g. V8) to make pages interactive.
- Manages state and security: stores cookies, cache, and history, and enforces the same-origin policy and TLS.
Examples: Chrome, Firefox, Safari, Edge.
Q1(c). What are interfaces in JAVA.20232m
Module III: Basics of Web Programming
View this question on its own page →What are interfaces in JAVA.
Worked SolutionAn interface in Java is a reference type that declares abstract methods (and constants) without providing a full implementation. A class that
implementsthe interface must define all its methods.interface Shape { double area(); // implicitly public abstract } class Circle implements Shape { double r; Circle(double r) { this.r = r; } public double area() { return Math.PI * r * r; } }Key points:
- Achieves 100% abstraction (before Java 8) and supports multiple inheritance of type, since a class can implement many interfaces.
- Since Java 8 an interface can also contain
defaultandstaticmethods. - Fields are implicitly
public static final.
Q1(d). Explain cookies.20232m
Module III: Basics of Web Programming
View this question on its own page →Explain cookies.
Worked SolutionA cookie is a small piece of data (name=value, up to ~4 KB) that a server sends to the browser, which stores it and returns it with every later request to the same site. It is used to make the stateless HTTP protocol remember a user.
Uses: session management (login state), personalization (theme, language), and tracking (analytics, ads).
Attributes:
Expires/Max-Age,Path,Domain,Secure,HttpOnly,SameSite.Set-Cookie: theme=dark; Max-Age=86400; Path=/; HttpOnly; SecureQ1(e). What is the role of query string in web communication?20232m
Module III: Basics of Web Programming
View this question on its own page →What is the role of query string in web communication?
Worked SolutionThe query string is the part of a URL after
?that carries data to the server asname=valuepairs joined by&.https://example.com/search?q=web+tech&page=2Role in web communication:
- Passes parameters from client to server in HTTP GET requests (form input, search terms, filters, pagination).
- Lets the same resource return different content based on the parameters.
- The server reads it (e.g.
$_GET['q']in PHP,req.query.qin Express). - URLs with query strings can be bookmarked and shared.
Limitation: data is visible in the URL and logs and length-limited, so never send passwords through it.
Q1(f). What are advantages of a content management system?20232m
Module III: Basics of Web Programming
View this question on its own page →What are advantages of a content management system?
Worked SolutionA Content Management System (CMS) lets users create, edit, organize, and publish web content without writing code (e.g. WordPress, Drupal, Joomla).
Advantages:
- No coding needed: non-technical users can update content through a WYSIWYG editor.
- Separation of content and design: themes and templates control layout, so content can be changed independently.
- Multi-user workflow: roles, permissions, drafts, and approval before publishing.
- Faster development: ready-made plugins and modules for SEO, forms, and e-commerce.
- Consistency: one template keeps the whole site uniform.
- Easy maintenance: version history, backups, and centralized updates.
- Scalability: pages and features can be added easily as the site grows.
Q1(g). Differentiate cookies from session variables.20232m
Module III: Basics of Web Programming
View this question on its own page →Differentiate cookies from session variables.
Worked SolutionBasis Cookies Session variables Storage location Client (browser) Server (only a session ID is kept on the client, usually in a cookie) Security Less secure; user can view or modify them More secure; data stays on the server Capacity About 4 KB per cookie Limited only by server memory or storage Lifetime Persistent until the expiry date, or session-only Ends when the browser closes, on timeout, or on session_destroy()Data types Strings only Any data type, including arrays and objects Performance Sent with every request Uses server resources PHP access setcookie(),_SESSIONQ1(h). Explain Inheritance.20232m
Module III: Basics of Web Programming
View this question on its own page →Explain Inheritance.
Worked SolutionInheritance is an OOP mechanism in which a new class (subclass or child) acquires the fields and methods of an existing class (superclass or parent). It promotes code reuse and models an is-a relationship.
class Animal { void eat() { System.out.println("eating"); } } class Dog extends Animal { void bark() { System.out.println("barking"); } } // Dog d = new Dog(); d.eat(); d.bark();Types: single, multilevel, and hierarchical (Java supports multiple inheritance only through interfaces).
Benefits: reusability, easier maintenance, and method overriding for runtime polymorphism.
Q1(i). What is polymorphism?20232m
Module III: Basics of Web Programming
View this question on its own page →What is polymorphism?
Worked SolutionPolymorphism means "many forms": one interface or method name behaving differently depending on the object or arguments.
1. Compile-time (static): method overloading, where the same name has different parameter lists.
int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; }2. Runtime (dynamic): method overriding, where the subclass redefines a parent method and the JVM picks the version from the actual object type.
Animal a = new Dog(); a.sound(); // calls Dog's sound()It makes code flexible and extensible.
Q1(j). Differentiate between block tags and inline tags with suitable example.20232m
Module I: Introduction to Web Technologies and Architectures
View this question on its own page →Differentiate between block tags and inline tags with suitable example.
Worked SolutionBasis Block tags Inline tags Layout Start on a new line and take the full available width Stay in the line and take only as much width as their content Width/height Can be set Ignored (width/height have no effect) Contains Block and inline elements Only text and other inline elements Examples <div>,<p>,<h1>,<ul>,<table><span>,<a>,<b>,<img>,<em><div>Block one</div> <div>Block two</div> <!-- two separate lines --> <p>Text with <span>inline</span> and <a href="#">link</a> in one line.</p>- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q2(a). How does the use of cookies help in server-side scripting? Give examples for data stored using cookies.20237m
Module III: Basics of Web Programming
View this question on its own page →How does the use of cookies help in server-side scripting? Give examples for data stored using cookies.
Worked SolutionHow cookies help in server-side scripting
HTTP is stateless: the server treats every request as new. A server-side script (PHP, Node.js, JSP) can use cookies to recognise a returning client.
Flow:
- The script sends a
Set-Cookieheader in its response. - The browser stores the cookie.
- The browser sends it back in the
Cookieheader on every later request to that site. - The script reads it (
$_COOKIEin PHP,req.cookiesin Express) and customises the response.
Benefits for server-side scripts:
- Session tracking: a session ID cookie identifies the logged-in user.
- Personalisation: language, theme, layout.
- Remember me: keeps the user signed in across visits.
- Shopping carts and tracking: cart contents, visited pages, analytics.
Examples of data stored in cookies: username, session ID, preferred language, theme (dark/light), cart ID, last visited page, consent choice.
PHP example:
<?php setcookie("username", "raiyan", time() + 86400 * 7, "/"); // 7 days if (isset($_COOKIE["username"])) { echo "Welcome back, " . $_COOKIE["username"]; } ?>Express (JavaScript) example:
res.cookie('theme', 'dark', { maxAge: 86400000, httpOnly: true }); const theme = req.cookies.theme;Caution: cookies are visible to the client, so never store passwords or sensitive data in them. Use
HttpOnly,Secure, andSameSiteflags.- The script sends a
Q2(b). How can CSS be used to display a XML document? Illustrate with an example.20237m
Module I: Introduction to Web Technologies and Architectures
View this question on its own page →How can CSS be used to display a XML document? Illustrate with an example.
Worked SolutionDisplaying XML with CSS
XML has no predefined tags, so a browser does not know how to show them. CSS supplies the presentation: link a stylesheet to the XML file with a processing instruction, then style each element by its tag name.
Step 1: link the stylesheet in the XML file
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/css" href="books.css"?> <library> <book> <title>Web Technology</title> <author>A. Kumar</author> <price>450</price> </book> <book> <title>Data Mining</title> <author>S. Rao</author> <price>520</price> </book> </library>Step 2: write books.css
library { display: block; font-family: Arial, sans-serif; } book { display: block; margin: 10px; padding: 8px; border: 1px solid #999; } title { display: block; font-size: 20px; font-weight: bold; color: #1a4fa0; } author { display: block; font-style: italic; } price { display: block; color: green; }The
displayproperty is essential because XML elements have no default display type. Without it, the content appears as one unformatted line.Limitations: CSS cannot reorder, filter, or compute content or add text; for that, XSLT is used.
Q3(a). Design a simple HTML form to input a string and to display whether it is Armstrong or not within the form submitted. Use a PHP script.20237m
Module III: Basics of Web Programming
View this question on its own page →Design a simple HTML form to input a string and to display whether it is Armstrong or not within the form submitted. Use a PHP script.
Worked SolutionArmstrong number checker (HTML form + PHP)
An Armstrong number equals the sum of its digits each raised to the power of the number of digits (e.g. 153 = 1³ + 5³ + 3³; 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴).
armstrong.php (form and result on the same page)
<!DOCTYPE html> <html> <head><title>Armstrong Number Check</title></head> <body> <h2>Armstrong Number Checker</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"> <label>Enter a number: <input type="text" name="num" required> </label> <input type="submit" value="Check"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { _POST["num"]); if (!ctype_digit($input)) { echo "<p>Please enter digits only.</p>"; } else { input); // number of digits $sum = 0; for (i < i++) { input[n); } if (input) { echo "<p><b>$input</b> is an Armstrong number.</p>"; } else { echo "<p><b>$input</b> is NOT an Armstrong number.</p>"; } } } ?> </body> </html>How it works:
- The form posts the value to the same script (
PHP_SELF). - PHP reads it from
$_POST['num']and validates that it contains only digits. - It counts the digits, sums each digit raised to that power, and compares the sum with the original number.
- The result is printed below the form, so the answer appears within the submitted page.
Sample: input
153→ 1 + 125 + 27 = 153 → Armstrong. Input123→ 1 + 8 + 27 = 36 → not Armstrong.- The form posts the value to the same script (
Q3(b). What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?20237m
Module III: Basics of Web Programming
View this question on its own page →What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?
Worked SolutionSignificance of cookies
HTTP is stateless, so cookies give websites a memory. They enable:
- Session management: login state, shopping carts.
- Personalisation: language, theme, preferences.
- Tracking and analytics: counting visits, behaviour, advertising.
- Convenience: "remember me" and auto-filled details.
Creating a cookie in PHP
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);It must be called before any output (before
<html>), because cookies travel in HTTP headers.<?php // Create: valid for 1 hour setcookie("user", "Raiyan", time() + 3600, "/"); ?> <html><body> <?php if (isset($_COOKIE["user"])) { echo "Hello, " . $_COOKIE["user"]; // available from the next request } else { echo "Cookie not set yet."; } ?> </body></html>Destroying a cookie in PHP
There is no delete function. Set the same cookie with an expiry time in the past (same name, path, and domain):
<?php setcookie("user", "", time() - 3600, "/"); unset($_COOKIE["user"]); // also remove it from the current request ?>The browser sees the cookie has expired and removes it.
Q4. What are various Internet Addressing modes? Explain.202314m
Module I: Introduction to Web Technologies and Architectures
View this question on its own page →What are various Internet Addressing modes? Explain.
Worked SolutionInternet addressing modes
Every device on the Internet needs an address so data can be delivered to it. Addressing works at four levels: physical (MAC), logical (IP), port, and domain name.
1. Physical (MAC) address
- 48-bit hardware address burned into the network card, written in hex (e.g.
00:1A:2B:3C:4D:5E). - Works at the Data Link layer and identifies a device inside a local network.
2. Logical (IP) address
Works at the Network layer and identifies a host across networks.
IPv4: 32 bits, written in dotted decimal (e.g.
192.168.1.10), about 4.3 billion addresses.Class First octet range Use A 1–126 Very large networks (8-bit network, 24-bit host) B 128–191 Medium networks (16/16) C 192–223 Small networks (24/8) D 224–239 Multicast E 240–255 Reserved / experimental IPv6: 128 bits, written in hex groups (e.g.
2001:0db8::1), a vastly larger address space.Address types by delivery:
- Unicast: one sender to one receiver.
- Broadcast: one to all hosts in a network.
- Multicast: one to a selected group.
- Anycast (IPv6): one to the nearest of a group.
Private vs public: private ranges (
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16) are used inside LANs; public addresses are globally routable. NAT translates between them.3. Port address
- 16-bit number (0–65535) at the Transport layer that identifies the application/process on a host.
- Examples: HTTP 80, HTTPS 443, FTP 21, SMTP 25, DNS 53.
- Socket address = IP address + port, e.g.
192.168.1.10:80.
4. Domain names (URL/DNS addressing)
- Humans use names like
www.example.com; DNS translates them to IP addresses. - A URL gives the full address of a resource:
protocol://host:port/path?query#fragment.
Summary
Level Address Layer Size Physical MAC Data Link 48 bits Logical IPv4 / IPv6 Network 32 / 128 bits Port Port number Transport 16 bits Name Domain / URL Application text - 48-bit hardware address burned into the network card, written in hex (e.g.
Q5. Define session. How it works and what are its advantages?202314m
Module III: Basics of Web Programming
View this question on its own page →Define session. How it works and what are its advantages?
Worked SolutionDefinition
A session is a way to store information about a user on the server across multiple page requests. Since HTTP is stateless, a session gives each visitor a unique session ID so the server can associate later requests with the same user (login state, cart, preferences).
How it works
- Start: the user first visits; the script calls
session_start()(PHP) or creates a session (Express, JSP). - ID generation: the server creates a unique random session ID.
- Cookie sent: the ID is sent to the browser, usually as a cookie (
PHPSESSID), or in the URL if cookies are disabled. - Data stored on the server: values go into
$_SESSIONand are kept in a file, memory, or database, keyed by the ID. - Later requests: the browser returns the ID; the server loads the matching data.
- End: the session ends on logout (
session_destroy()), timeout, or when the browser closes.
<?php session_start(); $_SESSION["user"] = "raiyan"; // page 1 // page 2 session_start(); echo "Logged in as " . $_SESSION["user"]; // logout session_unset(); session_destroy(); ?>Express equivalent:
req.session.user = 'raiyan'usingexpress-session.Advantages
- More secure than cookies: data stays on the server; the client holds only an ID.
- Large storage: no 4 KB limit, and any data type (arrays, objects) can be stored.
- Works across pages: data is available anywhere within the site during the visit.
- Authentication and authorization: keeps users logged in and controls access.
- Automatic expiry: sessions time out, limiting misuse.
- Client-independent data: the user cannot directly edit stored values.
Drawbacks
Uses server memory or storage, needs the ID transmitted safely (use HTTPS, regenerate the ID on login to stop session fixation), and is harder to scale across multiple servers without a shared store such as Redis.
- Start: the user first visits; the script calls
Q6(a). How to do pattern Matching in PHP?20237m
Module III: Basics of Web Programming
View this question on its own page →How to do pattern Matching in PHP?
Worked SolutionPattern matching in PHP
PHP does pattern matching mainly with regular expressions, using the PCRE (
preg_*) functions. A pattern is written between delimiters, e.g./pattern/flags.Main functions
Function Purpose preg_match(s, mpreg_match_all(s, $m)Finds all matches preg_replace(r, $s)Replaces matches preg_split(s)Splits a string on a pattern preg_grep(arr)Filters array elements that match Common syntax
.any character,\ddigit,\wword character,\swhitespace^start,$end*0+,+1+,?0 or 1,{n,m}range[abc]character class,(a|b)alternation,( )capture group- Flags:
icase-insensitive,mmultiline
Examples
<?php // 1. Simple match if (preg_match("/web/i", "Web Technology")) { echo "Found"; } // 2. Validate an email $email = "user@example.com"; if (preg_match("/^[\w.+-]+@[\w-]+\.[a-z]{2,}email)) { echo "Valid email"; } // 3. Extract digits with a capture group preg_match("/(\d{3})-(\d{4})/", "Call 555-1234", $m); echo m[2]; // 5551234 // 4. Replace echo preg_replace("/\s+/", " ", "too many spaces"); // too many spaces // 5. Find all numbers preg_match_all("/\d+/", "a1 b22 c333", $all); print_r($all[0]); // 1, 22, 333 ?>Simple (non-regex) matching
For plain text, use
strpos(),str_contains(),str_starts_with(), andstrcmp(). Usefnmatch()for shell-style wildcards.Use
preg_*for flexible patterns and the simple functions when a fixed substring is enough (they are faster).Q6(b). Write a PHP script to count the instances of words in string?20237m
Module III: Basics of Web Programming
View this question on its own page →Write a PHP script to count the instances of words in string?
Worked SolutionPHP script to count word instances in a string
Method 1: built-in functions
<?php $text = "the quick brown fox jumps over the lazy dog the end"; // lower-case, then extract words (letters, digits, apostrophes) text), 1); // count occurrences of each word words); // sort by frequency (highest first) arsort($counts); echo "<table border='1'><tr><th>Word</th><th>Count</th></tr>"; foreach (word => $count) { echo "<tr><td>count</td></tr>"; } echo "</table>"; ?>Output (top rows): the → 3, quick → 1, brown → 1, fox → 1, ...
Method 2: manual loop
<?php $text = "to be or not to be"; text)); $count = []; foreach (w) { w, ".,!?;:"); if ($w === "") continue; if (isset(w])) { w]++; } else { w] = 1; } } foreach (w => $c) { echo "c<br>"; } ?>Output: to : 2, be : 2, or : 1, not : 1
Explanation
strtolower()makes counting case-insensitive.str_word_count($s, 1)(orexplode) splits the text into an array of words.array_count_values()builds an associative array of word → frequency; the manual loop does the same with anissetcheck.arsort()orders the result by frequency.
Q7. Explain simple and complex data types in XML with suitable example?202314m
Module I: Introduction to Web Technologies and Architectures
View this question on its own page →Explain simple and complex data types in XML with suitable example?
Worked SolutionData types in XML Schema (XSD)
XML Schema defines the structure and data types of an XML document. Types are either simple or complex.
1. Simple types
A simple type holds only text/data. It has no child elements and no attributes.
Built-in simple types:
xs:string,xs:integer,xs:decimal,xs:boolean,xs:date,xs:time,xs:float.<xs:element name="name" type="xs:string"/> <xs:element name="age" type="xs:integer"/> <xs:element name="dob" type="xs:date"/>Matching XML:
<name>Ravi</name> <age>21</age> <dob>2004-05-12</dob>User-defined simple type (restriction):
<xs:simpleType name="marksType"> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="100"/> </xs:restriction> </xs:simpleType> <xs:element name="marks" type="marksType"/>Simple types can also be created as a list or union of other types.
2. Complex types
A complex type may contain child elements, attributes, or both, so it describes structured data.
<xs:element name="student"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="age" type="xs:integer"/> <xs:element name="marks" type="xs:integer"/> </xs:sequence> <xs:attribute name="roll" type="xs:string" use="required"/> </xs:complexType> </xs:element>Matching XML:
<student roll="CS101"> <name>Ravi</name> <age>21</age> <marks>88</marks> </student>Content models:
xs:sequence(fixed order),xs:choice(one of several),xs:all(any order). Complex types can also mix text and elements (mixed="true") or be empty with only attributes.Comparison
Feature Simple type Complex type Child elements No Yes Attributes No Yes Content Text value only Elements, attributes, or both Example <age>21</age><student roll="1">...</student>Reuse Named simpleTypeNamed complexTypeNote that an attribute itself always has a simple type.
Q8(a). External style sheets are usually preferred over other kinds of style sheets. Why?20237m
Module I: Introduction to Web Technologies and Architectures
View this question on its own page →External style sheets are usually preferred over other kinds of style sheets. Why?
Worked SolutionWhy external style sheets are preferred
CSS can be applied in three ways: inline (
style="..."on an element), internal (a<style>block in the page), and external (a separate.cssfile linked with<link rel="stylesheet" href="style.css">).Reasons for preferring external CSS
- Reusability: one file styles every page of the site.
- Easy maintenance: a change in one file updates the whole site instantly.
- Separation of concerns: HTML holds structure and content, CSS holds presentation, so both stay cleaner and readable.
- Faster loading through caching: the browser downloads the file once and caches it, so later pages load faster and use less bandwidth.
- Consistency: a uniform look and feel across all pages.
- Smaller HTML files: no repeated style code in each page.
- Team work: designers edit CSS while developers edit HTML.
- Media adaptability: different files or
mediaqueries can serve screen, print, or mobile.
Comparison
Type Scope Reuse Maintenance Inline One element None Hard Internal One page Single page Moderate External Whole website Full Easy <head> <link rel="stylesheet" href="styles/main.css"> </head>Minor drawback: an extra HTTP request on the first load, and the page may briefly appear unstyled if the file fails to load. The benefits far outweigh this.
- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q8(b). Illustrate with suitable code samples, the different ways of Array declaration in Java Script. Arrays in Java Script are said to be more flexible, why?20237m
Module III: Basics of Web Programming
View this question on its own page →Illustrate with suitable code samples, the different ways of Array declaration in Java Script. Arrays in Java Script are said to be more flexible, why?
Worked SolutionWays to declare arrays in JavaScript
1. Array literal (most common)
const fruits = ["apple", "banana", "mango"]; const empty = [];2.
new Array()constructorconst a = new Array("red", "green", "blue"); const b = new Array(5); // 5 empty slots (length 5)Caution:
new Array(3)makes an array of length 3, whereasnew Array(3, 4)makes[3, 4].3.
Array.of()const c = Array.of(3); // [3]4.
Array.from()const d = Array.from("abc"); // ['a','b','c'] const e = Array.from({length: 4}, (_, i) => i * 2); // [0,2,4,6]5. Spread syntax
const f = [...fruits, "kiwi"]; // copy and extend6. Declaring then filling by index
const g = []; g[0] = 10; g[1] = 20;Why JavaScript arrays are called flexible
- Dynamic size: they grow or shrink automatically; there is no fixed length. Use
push,pop,shift,unshift,splice, or setlength. - Mixed types: one array can hold numbers, strings, booleans, objects, functions, or other arrays.
const mix = [1, "two", true, {id: 3}, [4, 5], () => 6]; - No need to declare a size or type up front.
- Sparse arrays: indexes can be skipped (
g[100] = 1leaves gaps). - Rich built-in methods:
map,filter,reduce,forEach,sort,slice,find,includes. - Behave like objects: they can carry extra properties, and
lengthcan be changed directly.
This flexibility comes at a small performance cost compared to fixed-type arrays in languages like Java or C.
- Dynamic size: they grow or shrink automatically; there is no fixed length. Use
Q9(a). Explain the concept of Exception Handling. How will you create your own exception?20237m
Module III: Basics of Web Programming
View this question on its own page →Explain the concept of Exception Handling. How will you create your own exception?
Worked SolutionException handling
An exception is an abnormal event during execution (divide by zero, invalid input, missing file) that disrupts the normal flow. Exception handling is the mechanism to detect and handle such events gracefully so the program does not crash.
Keywords in Java:
try,catch,finally,throw,throws.try { int r = 10 / 0; // risky code } catch (ArithmeticException e) { // handler System.out.println("Error: " + e.getMessage()); } finally { System.out.println("Always runs"); // cleanup }try: contains code that may throw.catch: handles a specific exception type (multiple catch blocks allowed).finally: runs whether or not an exception occurred (close files, connections).throw: explicitly throws an exception object.throws: declares that a method may throw a checked exception.
Types: checked (checked at compile time, e.g.
IOException), unchecked (runtime, e.g.NullPointerException), and errors (e.g.OutOfMemoryError).Creating your own (user-defined) exception
Extend
Exception(checked) orRuntimeException(unchecked), thenthrowit where the condition occurs.class InvalidAgeException extends Exception { InvalidAgeException(String message) { super(message); } } class Demo { static void validate(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be at least 18"); System.out.println("Valid age"); } public static void main(String[] args) { try { validate(15); } catch (InvalidAgeException e) { System.out.println("Caught: " + e.getMessage()); } } }Output:
Caught: Age must be at least 18Steps: (1) create a class extending
Exception, (2) add a constructor that passes the message tosuper, (3) throw it withthrow new ..., (4) declare it withthrowsif checked, (5) catch it withtry/catch.JavaScript equivalent:
class InvalidAgeError extends Error { constructor(msg) { super(msg); this.name = 'InvalidAgeError'; } } try { throw new InvalidAgeError('Age must be at least 18'); } catch (e) { console.log(e.name + ': ' + e.message); }Q9(b). What are the drawbacks of HTML? How are they addressed in XML?20237m
Module I: Introduction to Web Technologies and Architectures
View this question on its own page →What are the drawbacks of HTML? How are they addressed in XML?
Worked SolutionDrawbacks of HTML
- Fixed, predefined tags: you cannot create custom tags that describe your own data.
- Content mixed with presentation: tags like
<b>,<font>, and<center>blend structure and looks. - No data meaning (no semantics for data):
<td>450</td>does not say whether 450 is a price or a roll number, so machines cannot understand it. - Not designed for data exchange: it is meant for display, not for transporting structured data between systems.
- Lenient syntax: browsers accept unclosed tags, missing quotes, and wrong nesting, leading to inconsistent rendering and hard-to-parse documents.
- No validation: there is no built-in way to enforce a required structure.
- Poor searching and reuse: the same content cannot be easily reformatted for other devices or purposes.
- Not extensible: new needs require changes to the standard itself.
How XML addresses them
HTML drawback XML solution Fixed tags Extensible: authors define their own tags, e.g. <price>,<author>Content and style mixed Separates data from presentation; styling is done with CSS or XSLT No data meaning Self-descriptive tags give data meaning: <price>450</price>Not for data exchange Designed for storing and transporting data (used in web services, configuration, RSS) Lenient syntax Strict, well-formed rules: every tag closed, correct nesting, quoted attributes, one root, case-sensitive No validation DTD or XML Schema validate structure and data types Poor reuse One XML source can be transformed to HTML, PDF, or other formats with XSLT <book> <title>Web Technology</title> <price currency="INR">450</price> </book>XML does not replace HTML: HTML displays data, while XML describes and carries data.
PYQDeck for Android
Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.