0% found this document useful (0 votes)
609 views177 pages

Question Bank With Solution Web Technology (BCS-502)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
609 views177 pages

Question Bank With Solution Web Technology (BCS-502)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

Web Technology((BCS-502) Questions Bank (CO-wise)

Ques. COs
No.
Questions
Define Protocol. Provide the name of protocols governing web.
1 CO1

What is a web project?Explain web development strategies. Also explain Web Team?
2 CO1

What is client server relationship? How it is implemented? How client server paradigm is different from peer to peer
3 CO1 paradigm?

Differentiate between Internet and WWW? What are the different services provided by Internet?
4 CO1

Create an HTML code to create a web page that contains the user registration form with following details user name,
5 CO1 user date of birth, user address, user gender, user email id, user mobile number.

What is a Form? Explain method and action attribute of a Form.


6 CO1

Differentiate between an Ordered list and an Unordered list?


7 CO1

What do you understand by hyperlinks in HTML? Write mark-up for an image hyperlink
8 CO1

Write HTML code to design “a form for online Railway Reservation Website” (Make Assumptions). OR Write the HTML
9 CO1 code to design a Student registration form. (Assume fields).

Discuss a frame and its advantages.

10 CO1

Explain <iframe> and frameset. Explain the anchor and table tag in HTML?
11 CO1

Explain Table tag with attributes.


12 CO1

Design a XML DTD for self describing weather report having following details: Date, location, temperature range
(Location describes city, state and its country. Country code is unique and not left blank. Temperature range describes
13 CO1
high and low temp. in Fahrenheit or Celsius)

Write an example of XML DTD. What are rules for writing DTD? Schema.
14 CO1

Write suitable XML markup to display the data of books with title, author, publisher and price. Explain well formed and
15 CO1 valid xml?

Design HTML document that divides the browser screen into two frames. The frame on the left will be a menu consisting
16 CO1 of hyperlinks. Clicking on any one of these links will lead to a new page open in the target frame on right hand side.

Differentiate between HTML and XML


17 CO1

Explain with the help of an example of a book catalog details.


18 CO1

What is DTD? Discuss its differences with XML


19 CO1

Differentiate between SAX and DOM parsers in detail.


20 CO1

CO2 Write a program with external style sheet with CSS.


21

CO2 Describe the advantages of CSS.


22

CO2 Create a css rule that makes all the text 2 times larger than the base font of the system. Mention can you integrate css
23 on a web page.
CO2 What is CSS? Discuss the different ways to create CSS. Explain with example.
24
CO2 Explain the difference between id and class selector in css?
25

CO2 Explain inline and block level element with example.


26

CO2 Explain different types of selectors in css.


27

CO2 Write the syntax of CSS property that can be used to remove the underline from a hyperlink.
28

CO2 Construct a web page using CSS to show the 3 horizontal and 3 vertical navigation bars that links to the different web
29 pages
CO2 Explain box model in CSS. Design a web page with a table of 6 rows. Use nthchild property of CSS to color Odd rows and
30 even rows in different colors. Highlight the even rows on mouse over.
CO2 Explain cascading and the style precedence rules when using multiple approaches.
31

CO2 Explain image spites with example. Explain Float css property.
32

CO2 Explain border and margin css properties. Explain Z-index


33

CO2 Explain navigation bar with example. Explain position


34

CO2 Differentiate between display :inline & display: inline block


35

CO2 Explain Website layout with example.


36

CO2 Explain different types of border with example.


37

CO2 Write code to create different types of link using pseudo-class selector.
38

CO2 Explain CSS position property with example.


39

CO2 Explain different combinators selector in CSS


40

CO3 Construct a JavaScript program using text boxes, two for inputs and others for output, implement four operations
41 addition, subtraction, multiplication and division on two input numbers on clicking of buttons ‘add’, ‘subtract’, ‘multiply’
and ‘divide’. Print the result in text box.

CO3 Discuss in brief how to perform Client Side Validation like Mandatory fields and Email field using Java Script? Justify with
42 a suitable example.
CO3 Design a JavaScript program to display the current day and time in the following format. Today is : Monday. Current time
43 is : 11 AM : 50 : 58
CO3 Why do we need client side scripting languages like Java Script? How AJAX like technologies is so useful these days? How
44 AJAX is used for single page processing?
CO3 Illustrate Array in JavaScript. Create a program in JavaScript to implement an array of five elements and perform the
45 operationspush, pop, shift, unshift and join on the array.
CO3 Write a program in JavaScript to print first n terms of Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, 21, 34…)
46

CO3 Explain the various event handlers in JavaScript with an example .


47

48 CO3 Explain Website layout and navigation bar.


CO3 Design a HTML form with name, address, pincode and password. Outline a JavaScript code that can validate on following
constraints: a. No fields must be left blank b. Pincode must be numeric and contain 6 digits c. Password field (i) At least
49
contains 1 Capital letter. (ii) Minimum length 8 characters

CO3 Discuss function in Java Script. Outline a JS function that takes 4 variables, a, b, c, d, and prints true in an alert box if
50 input a > input b and input c > input d. Else, print false in an alert box
CO3 What is AJAX? Explain its advantage and its working? Explain with example?
51
CO3 Describe various applications of JavaScript as a client side scripting language.
52

CO3 Illustrate and compare various dialog boxes in JavaScript with suitable JavaScript code.
53

CO3 Describe URL class in Java. Write a Java code display protocol, port number, host of given url with the help of this class.
54

CO3 Create a JavaScript program to make an arithmetic calculator.


55

CO3 What are the different data types present in javascript?


56

CO3 Explain Socket Programming with example


57

CO3 Explain Factory methods with example.Create a Java program to find out the IP address of your machine
58

CO4 Explain the EJB Architecture . Explain session bean, message bean and entity beans. Also explain the drawbacks of EJBs.
59

CO4 Illustrate Java Bean. Explain Properties of java Bean. Give example.
60

CO4 What is Node.js?


61

CO4 What is the purpose of Node.js?


62

CO4 What are the advantages of Node.js?


63

CO4 Explain Node.js web application architecture?


64

CO4 Difference between JavaScript and Node.js


65

CO4 Explain the working of Node.js?


66

CO4 Explain NPM.


67

CO4 Write a short note on Restful API


68

CO4 What is REPL terminal?


69

CO4 What is MongoDB?


70

CO4 How is MongoDB better than other SQL databases?


71

CO4 What are some of the advantages of MongoDB?


72

CO4 What are the data types in MongoDB?How do you Delete a Document?
73

CO4 How to perform queries in MongoDB?


74

CO4 What is the Mongo Shell?Explain $eq,$ne,$gt,$in and $lt .


75

CO4 What are Databases in MongoDB?


76

CO4 What is a Document in MongoDB?Explain InsertOne and InsertMany command in MongoDB with example.
77

CO4 What is a Collection in MongoDB?Explain updateOne and updateMany command in monodb.


78

CO4 Explain Logical operator with example in MongoDB.


79
CO4 What are NoSQL databases? What are the different types of NoSQL databases?
80

CO5 What is difference between Get and Post method?


81

CO5 Difference between forward() method and sendRedirect() method ?


82

CO5 What are the advantages of Servlet over CGI?


83

CO5 Discuss the implicit objects available to JSP page.


84

CO5 Explain the architecture and lifecycle of a JavaServer Page (JSP) within a web application.
85

CO5 Write a short note on tomcat server.


86

CO5 Explain types of Cookies with example.


87

CO5 Discuss the different types of standard action tags used in JSP.
88

CO5 Define the advantages of servlet over CGI? Explain with an example
89

CO5 Illustrate why the session is required in web applications. Mention all the session tracking techniques in servlet with their
90 pros and cons. Also give example of each.
CO5 Describe Servlet. Explain types of Servlet. Give an example of HttpServlet. Write steps to execute the servlet.
91

CO5 What are Java Server Pages? Explain life cycle of a JSP page? How JSP are better than Servlets?
92

CO5 Explain implicit objects available in jsp with example?


93

CO5 What are JSP directives? Explain various types of directives with example?
94

CO5 What are standard actions in JSP? Illustrate with example


95

CO5 Explain the Life cycle of servlet? Also write a servlet for displaying a string “HELLO WORLD!”
96

CO5 What are java Beans? Why they are used? Write a JSP page and use an existing java bean in JSP page by using the
97 standard action. Write the program with describing the output?
CO5 Discuss the role of the HttpServletRequest and HttpServletResponse interfaces in servlet programming.
98

CO5 Discuss the compilation process of JSP files into servlets and how they are executed by the servlet container.
99

CO5 Provide examples of how you can use these interfaces to retrieve request parameters, set response headers, and send
100 data back to the client.
Web Technology((BCS-502)
Unit -1 Question Bank With Solution

Q1. Define Protocol. Provide the name of protocols governing the web.
A protocol is a set of rules that explain how to conduct oneself in formal situations or
how to transmit data between entities. Protocols can be implemented by software or
hardware, but they are not software or hardware themselves.
Types of Internet Protocol

● TCP/IP(Transmission Control Protocol/ Internet Protocol)


● SMTP(Simple Mail Transfer Protocol)
● PPP(Point-to-Point Protocol)
● FTP (File Transfer Protocol)
● SFTP(Secure File Transfer Protocol)
● HTTP(HyperText Transfer Protocol)
● HTTPS(HyperText Transfer Protocol Secure)
● TELNET(Terminal Network)

Q.2.What is a web project?Explain web development strategies. Also explain Web


Team?
A web project is a collection of web resources that are used to create, maintain, and
develop web applications. The web project environment is where activities like testing,
building, link-checking, and publishing are performed.
Web development strategies are the guidelines for creating websites, and a web development
team is responsible for building and launching websites and applications. Here are some web
development strategies and some things to consider when building a web development team:

Web development strategies


Some strategies include:
● Content management and SEO: Using keywords, meta tags, and other techniques
to improve search engine rankings
● Testing: Testing the site on different devices and conducting unit, integration, and
system tests to ensure the website is error-free
● Progressive Web Apps (PWAs): Combining online and mobile app features to create
cross-platform apps with quick loading times and offline capabilities

Web Team: the collection of workers who are brought together in order to create digital-
based content. Within that team, there can be a number of roles. The number is varied and
could actually change depending on the task given to the team.

Q.3.What is client server relationship? How it is implemented? How client server paradigm is
different from peer to peer paradigm?

The client-server relationship is a networking model where a client program requests a service
or resource from a server program. The client and server communicate using a request-
response pattern, where the client sends a request and the server responds. The client and
server must follow a common communications protocol to ensure they know what to expect.

Here are some ways the client-server relationship is implemented:

Communications protocol
The client and server use a common communications protocol to define the rules,
language, and dialog patterns for communication. TCP/IP is a common protocol used for
client-server communication.
Application programming interface (API)
The server may use an API to formalize data exchange. An API is an abstraction layer that
restricts communication to a specific content format.
Scheduling system
The server uses a scheduling system to prioritize incoming requests from clients.
Server software
The server software may limit availability to clients to prevent abuse and maximize
availability.

The client-server relationship differs from the peer-to-peer relationship in several ways:

Client and server distinction


In a client-server network, there is a clear distinction between clients and servers, while
in a peer-to-peer network, there is no clear distinction.
Data storage
In a client-server network, data is typically stored in a centralized server, while in a peer-
to-peer network, each peer holds its own data.
Service requests
In a client-server network, the server responds to the service requests made by the
client, while in a peer-to-peer network, each node can both request and provide
services.
Network stability
Client-server networks provide a more stable network configuration, while peer-to-peer
networks offer less stability.
Network size
Client-server networks can be employed in both small and large networks, while peer-
to-peer networks are mainly used for smaller networks.

The main difference between the client-server and peer-to-peer paradigms is that in a client-
server network, clients request services from a server, while in a peer-to-peer network, each
node can request and provide services:

Here are some other differences between the two paradigms:

Network type
A client-server network is centralized, while a peer-to-peer network is decentralized.
Cost
A client-server network is more expensive to set up, while a peer-to-peer network doesn't
require as much equipment.
Reliability and security
A client-server network is more reliable and secure than a peer-to-peer network.
Load balancing
In a client-server network, load balancing distributes network traffic across multiple
servers. In a peer-to-peer network, an algorithm balances load, and peers with modest
resources can help share the load.

Both client-server and peer-to-peer networks use dedicated servers, TCP/PP-based protocols,
and support devices in both client and server roles.

Q.4. Differentiate between the Internet and WWW? What are the different services provided
by the Internet?
The main difference between the internet and the World Wide Web (WWW) is that the
internet is a network of computers that the WWW runs on, while the WWW is a service offered
by the internet:

The internet
A global network of computers that connects devices all over the world using copper
wires, fiber optic connections, or wireless networks. The internet is a public network
that anyone can connect to. It's a superset of the WWW, and is administered by
organizations like the Internet Assigned Numbers Authority (IANA).
The WWW
A service that allows users to access online information structured in HTML over the HTTP
protocol. The WWW is a subset of the internet, and is more software-oriented than the
internet, which is primarily based on hardware. The WWW's existence depends on the
internet.

The internet provides many services, including:

● Information dissemination: The internet allows people to share and exchange resources
and information.
● Data availability: The internet makes data resources available.
Q.5.Create an HTML code to create a web page that contains the user registration form with
following details user name, user date of birth, user address, user gender, user email id, user
mobile number.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
width: 50%;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
}
label {
display: block;
margin: 10px 0 5px;
color: #333;
}
input[type="text"], input[type="email"], input[type="date"], input[type="tel"], textarea {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 20px;
}
input[type="radio"], input[type="checkbox"] {
margin-right: 10px;
}
.form-group {
margin-bottom: 15px;
}
.gender-group {
display: inline-block;
}
.btn {
display: inline-block;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
.btn:hover {
background-color: #45a049;
}
</style>
</head>
<body>

<div class="container">
<h2>User Registration Form</h2>
<form action="#" method="post">
<!-- User Name -->
<div class="form-group">
<label for="username">User Name:</label>
<input type="text" id="username" name="username" required>
</div>

<!-- Date of Birth -->


<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
</div>

<!-- User Address -->


<div class="form-group">
<label for="address">Address:</label>
<textarea id="address" name="address" rows="4" required></textarea>
</div>

<!-- Gender -->


<div class="form-group gender-group">
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label>
<input type="radio" id="other" name="gender" value="Other">
<label for="other">Other</label>
</div>

<!-- User Email -->


<div class="form-group">
<label for="email">Email ID:</label>
<input type="email" id="email" name="email" required>
</div>

<!-- Mobile Number -->


<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="tel" id="mobile" name="mobile" pattern="[0-9]{10}" required
placeholder="1234567890">
</div>

<!-- Submit Button -->


<div class="form-group">
<button type="submit" class="btn">Register</button>
</div>
</form>
</div>

</body>
</html>

Q.6.What is a Form? Explain method and action attribute of a Form.

In web development, a form is an HTML element that allows users to input data, which can
then be sent to a server for processing. Forms are used to collect data from users such as text,
selection choices, dates, numbers, and more. Common examples include login forms,
registration forms, search boxes, feedback forms, and contact forms.

A form typically consists of various input elements (like text fields, checkboxes, radio buttons,
dropdowns, etc.) and is usually enclosed within the <form> HTML tag. When the user submits
the form, the data entered in the form is sent to a web server for further processing (such as
storing in a database, sending an email, etc.).

Summary of the method and action Attributes

Attribute Description Example

method Defines how the data will be sent to the server. method="POST"
Common values are GET (appends data to the URL)
and POST (sends data in the request body).

action Specifies the URL where the form data will be action="process_form.php"
submitted. This can be a server-side script, the
same page, or an external URL.
● Use POST when dealing with sensitive or large data.
● Use GET for search forms or when you want to pass parameters in the URL.
● Always set the action attribute to the correct endpoint for data processing.

Q.7.Differentiate between an Ordered list and an Unordered list?

In HTML, lists are used to group related items together. There are two main types of lists:

1. Ordered List (<ol>): This list is used when the order of the list items is important. It
displays items in a numbered or alphabetized sequence.
2. Unordered List (<ul>): This list is used when the order of the list items is not important.
It displays items with bullet points (or other symbols) instead of numbers or letters.

Here is a comparison of the two:

Feature Ordered List (<ol>) Unordered List (<ul>)

Purpose Used when the order of items matters Used when the order of items
(e.g., steps in a process, rankings). does not matter (e.g., a list of
features).

HTML Tag <ol> (Ordered List) <ul> (Unordered List)

List Marker Displays a numbered list (default is Displays a bullet point (typically
numeric, but can be customized to a circle).
Roman numerals, letters, etc.).

List Items <li> (List Item) inside <ol> <li> (List Item) inside <ul>

Example <ol><li>First item</li><li>Second <ul><li>First


item</li></ol> item</li><li>Second
item</li></ul>

Default Display Numbers (e.g., 1, 2, 3, ...) Bullets (•, ◦, or similar symbols)

Customization Can be customized to show letters (a, b, Bullet style can be customized
c, ...) or Roman numerals (i, ii, iii, ...). to use square boxes, circles, or
other shapes.
Use Cases When order or ranking matters (e.g., When order is not important
instructions, ranking lists). (e.g., lists of features,
ingredients).

Q.8.What do you understand by hyperlinks in HTML? Write mark-up for an image hyperlink

Hyperlinks in HTML are used to link one page to another or to specific sections within a page.
They are created using the <a> tag. To create an image hyperlink, you wrap the <img> tag inside
an <a> tag. Here’s an example:

<a href="https://www.example.com">
<img src="image.jpg" alt="Description of Image">
</a>

Q.9. Write HTML code to design “a form for online Railway Reservation Website” (Make
Assumptions). OR Write the HTML code to design a Student registration form. (Assume
fields).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}
.container {
width: 50%;
margin: 50px auto;
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
}
label {
display: block;
margin: 10px 0 5px;
font-weight: bold;
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="tel"],
select,
textarea {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin-right: 10px;
}
button {
background-color: #4CAF50;
color: white;
border: none;
padding: 12px 20px;
cursor: pointer;
border-radius: 4px;
width: 100%;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>Student Registration Form</h2>
<form action="/submit" method="POST">
<!-- Personal Information Section -->
<label for="first-name">First Name:</label>
<input type="text" id="first-name" name="first_name" required>

<label for="last-name">Last Name:</label>


<input type="text" id="last-name" name="last_name" required>

<label for="email">Email Address:</label>


<input type="email" id="email" name="email" required>

<label for="phone">Phone Number:</label>


<input type="tel" id="phone" name="phone" pattern="[0-9]{10}" required
placeholder="1234567890">

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob" required>

<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male" required>
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>

<!-- Address Section -->


<label for="address">Address:</label>
<textarea id="address" name="address" rows="4" required></textarea>

<!-- Course Selection Section -->


<label for="course">Select Course:</label>
<select id="course" name="course" required>
<option value="computer-science">Computer Science</option>
<option value="electrical-engineering">Electrical Engineering</option>
<option value="mechanical-engineering">Mechanical Engineering</option>
<option value="civil-engineering">Civil Engineering</option>
<option value="biotechnology">Biotechnology</option>
</select>

<label for="terms">
<input type="checkbox" id="terms" name="terms" required>
I agree to the <a href="#">terms and conditions</a>.
</label>

<button type="submit">Register</button>
</form>
</div>
</body>
</html>

Q.10.Discuss a frame and its advantages.

HTML Frames

In HTML, a frame is used to display multiple, independent sections or documents within a single
web page. Frames are typically used to divide a browser window into different sections, where
each section can independently load different web pages. This technique allows for more
interactive or complex page layouts. Frames were traditionally created using the <frame> and
<frameset> elements in HTML.

However, HTML frames are now considered obsolete in modern web design, and they have
been replaced by more flexible techniques such as CSS and JavaScript. Despite this, it’s still
useful to understand how they worked historically and their advantages.

Frameset and Frame Elements


● <frameset>: Used to define a container for multiple frames. It replaced the normal
<body> tag and allowed for splitting the browser window into multiple sections.
● <frame>: Defines the individual frames within a <frameset>. Each <frame> element can
display a different HTML document.

<frameset cols="50%, 50%">

<frame src="page1.html">

<frame src="page2.html">

</frameset>

Advantages of Frames :

1. Multiple Views in One Window:


○ Frames allowed users to view multiple pages within the same browser window,
which was useful for applications or websites that required constant navigation,
like a site with a persistent sidebar or a menu.
2. Persistent Navigation:
○ The use of frames made it possible to have a fixed navigation section (like a
sidebar) that wouldn't reload every time a user clicked on a link. This kept the
navigation structure visible while the content in another frame could change.
3. Reduced Page Reloads:
○ When a user clicked a link within a frame, only the content inside that frame
would reload, not the entire page. This reduced page loading times and
improved the user experience for certain types of content, like image galleries or
catalog interfaces.
4. Independent Document Structure:
○ Frames allowed different HTML documents to be loaded independently in each
frame. This made it easier to structure complex layouts without having to use
multiple browser windows or iframes.
5. Simplified Complex Layouts:
○ Before the widespread use of CSS for layout, frames offered a way to create
complex page structures (such as a header, sidebar, and main content area)
without needing to rely on tables or floats, which were commonly used at the
time.
Q.11. Explain <iframe> and frameset. Explain the anchor and table tag in HTML?

<iframe> (Inline Frame)

An iframe (inline frame) is an HTML element used to embed another HTML document inside
the current document. Unlike traditional frames (which were used to divide a browser window
into multiple sections), the <iframe> is used to display a separate document within a designated
area of a page.

Syntax:

<iframe src="https://www.example.com" width="600" height="400"></iframe>

<frameset>

The <frameset> element was used in earlier versions of HTML (HTML 4) to create a layout with
multiple, independent frames within a page. It replaced the <body> tag and allowed for dividing
the browser window into multiple sections (rows or columns). Each section could load a
different HTML document.
<frameset cols="50%, 50%">
<frame src="page1.html">
<frame src="page2.html">
</frameset>

The <a> (Anchor) Tag in HTML

The <a> tag, also known as the anchor tag, is used to create hyperlinks that allow users to
navigate from one page to another or to a specific part of a page. It is one of the most essential
elements for web navigation.

<a href="https://www.example.com">Click Here</a>


Q.12. Explain Table tag with attributes.

The <table> Tag in HTML

The <table> tag is used to display tabular data (rows and columns). Tables are useful for
presenting structured information like lists, schedules, statistics, and more.

Elements Used in a Table:

● <table>: Defines the table element.


● <tr>: Defines a table row.
● <th>: Defines a table header cell (bold and centered by default).
● <td>: Defines a table data cell (contains actual data).
● <caption>: Defines a caption for the table (usually appears above it).
● <thead>, <tbody>, <tfoot>: Group elements for header, body, and footer sections of a
table. This helps in organizing large tables and improving accessibility.
● colspan and rowspan: Used in <td> or <th> to merge cells across columns or rows.

Attributes:

● border: Specifies whether the table has a border (usually set with CSS).
● cellpadding: Defines the space between the cell content and the cell border.
● cellspacing: Defines the space between individual cells.
● width, height: Specifies the dimensions of the table.
● style: Allows you to add CSS for styling the table.

Use Cases:

● Displaying data in a structured, row-and-column format.


● Creating forms or layouts that require tabular alignment.

<table border="1">
<caption>Student Information</caption>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>18</td>
<td>A</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>17</td>
<td>B</td>
</tr>
</tbody>
</table>

Q.13.Design a XML DTD for self describing weather report having following details: Date,
location, temperature range (Location describes city, state and its country. Country code is
unique and not left blank. Temperature range describes high and low temp. in Fahrenheit or
Celsius)

<!ELEMENT WeatherReport (Date, Location, TemperatureRange)>


<!ELEMENT Date (#PCDATA)>
<!ELEMENT Location (City, State, Country)>
<!ELEMENT City (#PCDATA)>
<!ELEMENT State (#PCDATA)>
<!ELEMENT Country (#PCDATA)>
<!ATTLIST Country code ID #REQUIRED>
<!ELEMENT TemperatureRange (High, Low)>
<!ELEMENT High (#PCDATA)>
<!ELEMENT Low (#PCDATA)>
<!ATTLIST High unit (Fahrenheit | Celsius) #REQUIRED>
<!ATTLIST Low unit (Fahrenheit | Celsius) #REQUIRED>
Explanation of the DTD elements:

● WeatherReport: This is the root element, which contains Date, Location, and
TemperatureRange.
● Date: Contains the date information (a textual value, such as "2024-12-06").
● Location: Contains three sub-elements: City, State, and Country.
○ City: The city name (e.g., "Los Angeles").
○ State: The state name (e.g., "California").
○ Country: The country name (e.g., "USA") with an attribute code, which is a
unique ID for the country (e.g., "US").
● TemperatureRange: Contains two sub-elements: High and Low, which describe the high
and low temperatures.
○ High and Low both have a unit attribute that specifies whether the temperature
is in Fahrenheit or Celsius.
○ High: The high temperature (e.g., "75").
○ Low: The low temperature (e.g., "60").
○ unit attribute for both High and Low: This attribute specifies the temperature
unit, and it can either be "Fahrenheit" or "Celsius".

Example of an XML file that conforms to this DTD:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE WeatherReport SYSTEM "weatherreport.dtd">
<WeatherReport>
<Date>2024-12-06</Date>
<Location>
<City>Los Angeles</City>
<State>California</State>
<Country code="US">United States</Country>
</Location>
<TemperatureRange>
<High unit="Fahrenheit">75</High>
<Low unit="Fahrenheit">60</Low>
</TemperatureRange>
</WeatherReport>

Q.14. Write an example of XML DTD. What are the rules for writing DTD? .
Rules for Writing DTD (Document Type Definition):

1. Elements Declaration:
○ Use the <!ELEMENT> keyword to define elements and their content models.
○ Content Models:
■ #PCDATA (Parsed Character Data) is used for text content within an
element.
■ Parentheses () are used to group elements and define the sequence.
■ A + sign means that the element appears one or more times (e.g.,
<Library> (Book+) means a Library must contain one or more books).
■ A * sign means that the element can appear zero or more times.
■ A ? sign means that the element is optional (can appear zero or one
time).
2. Attributes Declaration:
○ Use the <!ATTLIST> keyword to define attributes for elements.

3.Entities Declaration (Optional):

● Use <!ENTITY> to define reusable entities for special characters or text.


● This allows you to reference &copyright; in the XML document.

4.Comments:

● Comments in DTD can be added using the syntax <!-- comment -->.

5.External/Internal DTD:

● External DTD: Stored in a separate file (e.g., library.dtd), and referenced in the XML file.
● Internal DTD: Defined within the XML file itself, typically between <!DOCTYPE> and the
root element.

Q.15.Write suitable XML markup to display the data of books with title, author, publisher and
price. Explain well formed and valid xml?

<?xml version="1.0" encoding="UTF-8"?>


<Books>
<Book>
<Title>The Catcher in the Rye</Title>
<Author>J.D. Salinger</Author>
<Publisher>Little, Brown and Company</Publisher>
<Price currency="USD">19.99</Price>
</Book>
<Book>
<Title>To Kill a Mockingbird</Title>
<Author>Harper Lee</Author>
<Publisher>J.B. Lippincott & Co.</Publisher>
<Price currency="USD">14.99</Price>
</Book>
<Book>
<Title>1984</Title>
<Author>George Orwell</Author>
<Publisher>Secker & Warburg</Publisher>
<Price currency="GBP">12.99</Price>
</Book>
</Books>

Explanation:

1. <?xml version="1.0" encoding="UTF-8"?>: The XML declaration at the beginning


defines the XML version and the character encoding used in the document.
2. <Books>: The root element that contains all the book data.
3. <Book>: Represents each book. It is the parent element of the Title, Author, Publisher,
and Price elements.
4. <Title>: Contains the title of the book.
5. <Author>: Contains the name of the author.
6. <Publisher>: Contains the name of the publisher.
7. <Price>: Contains the price of the book. It also has an attribute currency to specify the
currency of the price (e.g., "USD", "GBP").

This XML file has three books, each with the required information.
Q.16.Design HTML document that divides the browser screen into two frames. The frame on
the left will be a menu consisting of hyperlinks. Clicking on any one of these links will lead to
a new page open in the target frame on right hand side.

To create an HTML document that divides the browser screen into two frames, where the left
side acts as a menu containing hyperlinks, and the right side displays the content corresponding
to the selected link, you can use the <frameset> element. However, please note that the
<frameset> element is deprecated in HTML5 in favor of more modern layout techniques like
CSS Flexbox or CSS Grid.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frame Layout Example</title>
</head>
<body>

<frameset cols="25%, 75%">


<!-- Left Frame (Menu) -->
<frame src="menu.html" name="menu">

<!-- Right Frame (Content) -->


<frame src="home.html" name="content">
</frameset>

</body>
</html>

Explanation:
1. <frameset>: The <frameset> tag defines a set of frames. In this case, it divides the
screen into two columns. The cols="25%, 75%" attribute means the left column will take
up 25% of the screen width, and the right column will take up 75%.
2. Left Frame (<frame src="menu.html" name="menu">): This frame contains the menu,
and it is named "menu". The src attribute specifies the content of the left frame (e.g.,
menu.html).
3. Right Frame (<frame src="home.html" name="content">): This frame is where the
content will appear based on the selected link from the menu. The name="content"
attribute allows links in the left frame (menu) to target this specific frame.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Menu</title>

</head>

<body>

<ul>

<li><a href="page1.html" target="content">Page 1</a></li>

<li><a href="page2.html" target="content">Page 2</a></li>

<li><a href="page3.html" target="content">Page 3</a></li>

</ul>

</body>

</html

Explanation of menu.html:
● The menu consists of an unordered list (<ul>).
● Each list item (<li>) contains a hyperlink (<a>). The target="content" attribute ensures
that when a link is clicked, the corresponding content is loaded in the right frame
(content).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page 1</title>
</head>
<body>
<h1>Welcome to Page 1</h1>
<p>This is the content of Page 1.</p>
</body>
</html>

Q.17. Differentiate between HTML and XML

Feature HTML XML

Purpose Web page structure and Data storage, transportation, and


presentation structure

Tags Predefined tags (e.g., <h1>, <p>) Custom tags defined by the user

Tag Closing Not always required (some tags are Strictly requires closing or self-
self-closing) closing tags

Strictness Lenient (browser fixes some errors) Strict (errors prevent processing)
Validation Optional validation (HTML5 Mandatory validation via DTD or
specification) XSD

Data vs. Presentation-focused Data-focused


Presentation

Error Handling Tolerates errors and tries to render Fails if the syntax is incorrect

Q.18.Explain with the help of an example of a book catalog details.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Catalog</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Book Catalog</h1>
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Price</th>
</tr>
<tr>
<td>Learn HTML</td>
<td>John Doe</td>
<td>2022</td>
<td>$25.99</td>
</tr>
<tr>

Explanation of HTML Example:

● Purpose: The HTML document displays a book catalog on a webpage, which includes a
table with book details such as title, author, year of publication, and price.
● Presentation: HTML focuses on the layout and presentation of the content, including
the use of <table>, <th>, and <td> tags to define the structure of the table.
● Tags: The tags used here are predefined HTML tags that are used for page layout and
display. There is no focus on the underlying data structure; the goal is to present the
information in a user-friendly format.

In contrast, XML is used for storing and transporting the data in a structured format. It allows
data to be easily exchanged between systems, applications, or services. Here is an XML
representation of the same book catalog:

<?xml version="1.0" encoding="UTF-8"?>


<catalog>
<book>
<title>Learn HTML</title>
<author>John Doe</author>
<year>2022</year>
<price>25.99</price>
</book>
<book>
<title>Advanced CSS</title>
<author>Jane Smith</author>
<year>2021</year>
<price>30.00</price>
</book>
<book>
<title>JavaScript Essentials</title>
<author>Mark Taylor</author>
<year>2023</year>
<price>40.50</price>
</book>
</catalog>

Explanation of XML Example:

● Purpose: The XML document is structured data that represents a book catalog. It stores
information about the books in a hierarchical format, which can be used by computers
or applications to process or exchange the data.
● Data-Oriented: XML focuses on the data itself (book title, author, year, price) without
concerning itself with how the data will be presented. It provides a way to represent the
structure of the information in a machine-readable format.
● Tags: Unlike HTML, XML allows custom tags such as <catalog>, <book>, <title>,
<author>, etc. These tags are not predefined and are designed to represent the data in a
meaningful way. The data is stored inside these tags, and the structure of the document
is defined by the user or the system.

Q.19 What is DTD? Discuss its differences with XML

DTD (Document Type Definition) is a set of rules that defines the structure, the legal elements,
attributes, and their relationships in an XML document. It is a way to specify the allowed
structure and content of an XML document, essentially serving as a "blueprint" or "contract" for
how XML data should be structured.

A DTD defines:

1. Which elements are allowed in the XML document.


2. The order of elements and whether they are optional or mandatory.
3. Attributes that elements can have.
4. The type of data that an element can contain (e.g., text, another element).

In essence, a DTD specifies the rules for creating valid XML documents, ensuring that the XML
conforms to a specific structure.

Types of DTD

1. Internal DTD: The DTD is included within the same XML file, like in the first example
above.
2. External DTD: The DTD is stored in a separate file, referenced by the XML document
using the DOCTYPE declaration. In the above example, the XML document references an
external DTD file called books.dtd.

Differences Between DTD and XML

While DTD and XML are closely related, they serve different purposes and have some key
differences:

Aspect DTD (Document Type XML (eXtensible Markup Language)


Definition)

Purpose Defines the structure and rules A markup language used to store and
for an XML document. transport data.

Nature A specification or "blueprint" A flexible, self-descriptive language used


that describes how XML data to define, store, and transport data.
should be structured.

Data vs. Defines the structure of XML Defines the data and its content in a
Structure documents, i.e., which structured way, but does not enforce
elements are allowed and how any structure or rules.
they relate.

Error Handling DTD is used to validate the XML data does not validate its structure
structure of XML, ensuring that automatically; it only stores the data.
XML follows predefined rules. You need to validate XML with DTD,
XSD, or other mechanisms.
Flexibility Less flexible: DTD has strict More flexible: XML can represent any
rules and a limited set of kind of structured data, and you can
features for defining data types define your own tags without
and constraints. limitations.

Tags DTD defines rules for the XML uses custom-defined tags that
allowed tags in XML. It does represent data. It is used for storing and
not contain any actual data. transporting the actual data.

Support for Data DTD has limited support for XML does not define data types but can
Types data types (e.g., text, numbers) be validated using external schemas like
but cannot handle complex XSD (XML Schema Definition), which
data types. supports complex data types.

Definition of DTD can define element XML alone does not define relationships
Relationships relationships, like child or constraints, but these can be
elements, ordering, and enforced through validation tools like
occurrence constraints (e.g., +, DTD or XSD.
*).

Extensibility DTD is not very extensible and XML is extensible and allows you to
does not support complex data create custom tags to define and store
validation. data.

Q.20.Differentiate between SAX and DOM parsers in detail.

SAX vs. DOM Parsers

When working with XML documents in programming, two of the most common ways to parse
XML data are through SAX (Simple API for XML) and DOM (Document Object Model). These are
two distinct approaches to parsing XML, each with its own characteristics, advantages, and use
cases.

Here's a detailed comparison between SAX and DOM parsers:

Feature SAX Parser (Simple API for XML) DOM Parser (Document Object Model)
Parsing Event-based: SAX parses XML Tree-based: DOM loads the entire XML
Approach sequentially and triggers events document into memory as a tree
(like start or end of elements, text structure with nodes representing
content) as it encounters them. elements, attributes, and data.

Memory Usage Low memory usage: SAX High memory usage: DOM loads the
processes the XML document entire XML document into memory,
sequentially and does not need to creating a tree structure, which
load the entire document into requires more memory, especially for
memory. large documents.

Speed Faster for large XML documents Slower for large XML documents
since it doesn’t require loading because it must load the entire
the entire document into document into memory before parsing.
memory. It processes the However, it is faster for certain
document as it reads it. operations once the document is in
memory.

Document Sequential Access: SAX is a Random Access: DOM allows access to


Access streaming parser, meaning it any part of the XML document at any
reads the document from the time. Once the document is loaded as a
start to the end. You cannot move tree, any node can be accessed,
backward or re-read elements. modified, or traversed.

Memory Memory-efficient: Since SAX does Memory-intensive: Since DOM creates


Efficiency not store the entire XML in an in-memory tree structure of the
memory, it is well-suited for large entire XML document, it is less suitable
XML documents or when memory for very large XML files or when
is a concern. memory is limited.

Ease of Use Complex: SAX requires handling Easier: DOM provides a straightforward
events through callback methods interface to navigate and manipulate
(e.g., startElement, endElement). the XML structure. You can directly
Developers must manage the access and modify elements in the
state of parsing manually. document.
Use Cases Best for streaming, large XML Best for small to medium-sized XML
documents, or when only part of documents that require frequent
the document is needed. Suitable access to the entire document. Useful
for applications like XML feeds, for applications where the entire
log files, and when parsing one document must be loaded and
element at a time is enough. manipulated in memory (e.g., editors,
document generators).

Modification of Not suitable for modification: SAX Suitable for modification: DOM allows
Document is primarily a read-only parser, you to modify the XML structure, add
and you cannot modify the or remove nodes, and save the changes
document while parsing it. back to the XML file.

Error Handling Limited: SAX provides error Better control: DOM allows better error
notifications during the parsing handling because it loads the entire
process (e.g., malformed XML), document into memory first. You can
but there is less control over error manipulate the tree, perform
recovery because it's streaming validations, and handle errors more
data. easily.

Event Handling Event-driven: SAX is event-driven, Non-event-driven: DOM is not event-


meaning the application must driven. It provides direct access to the
define handlers (callbacks) to entire XML structure and allows
handle various XML events, such navigation and modification of the tree
as the start or end of an element. as needed.
Unit 2 Questions and their solutions
Q 21 Write a program of CSS using external stylesheet.

Ans :With an external style sheet, you can change the look of an entire website by changing just
one file!

Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.

Example

External styles are defined within the <link> element, inside the <head> section of an HTML
page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

<h1>Welcome to designing.</h1>
<p> An external style sheet can be written in any text editor, and must be saved with a .css
extension.<br>

The external .css file should not contain any HTML tags

.</p>

</body>
</html>

An external style sheet can be written in any text editor, and must be saved with a .css extension.

The external .css file should not contain any HTML tags.

Here is how the "mystyle.css" file looks:

"mystyle.css"

body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Q22 :Describe the advantages of CSS.

Ans: Advantages are

CSS saves time − You can write CSS once and then reuse same sheet in
multiple HTML pages. You can define a style for each HTML element and apply it
to as many Web pages as you want.
∙ Pages load faster − If you are using CSS, you do not need to write HTML
tag ,attributes every time. Just write one CSS rule of a tag and apply it to all
the occurrences of that tag. So less code means faster download times.
∙ Easy maintenance − To make a global change, simply change the style, and
all elements in all the web pages will be updated automatically.
∙ Superior styles to HTML − CSS has a much wider array of attributes than
HTML, so you can give a far better look to your HTML page in comparison to
HTML attributes.
∙ Multiple Device Compatibility − Style sheets allow content to be optimized
for more than one type of device. By using the same HTML document,
different versions of a website can be presented for handheld devices such as
PDAs and cell phones or for printing.
∙ Global web standards − Now HTML attributes are being deprecated and it is
being recommended to use CSS. So its a good idea to start using CSS in all the
HTML ages to make them compatible to future browsers.

Q23: Create a css rule that makes all the text 2 times larger than the base font of the system.
Mention can you integrate css on a web page.

Ans Syntax: font-size:2rem

Yes,we can integrate CSS into three ways in a web page

 Internal CSS
 Inline CSS
 External CSS

Q24: What is CSS? Discuss the different ways to create CSS. Explain with example.

Ans Cascading Style Sheet, fondly referred to as CSS, is a simple design language intended
to simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out,
what background images or colors are used, layout designs, variations in display for different
devices and screen sizes as well as a variety of other effects.

Three Ways to Insert CSS

There are three ways of inserting a style sheet:

 External CSS
 Internal CSS
 Inline CSS

External CSS

With an external style sheet, you can change the look of an entire website by changing just one
file!

Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.

Example

External styles are defined within the <link> element, inside the <head> section of an HTML
page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

<h1>Welcome to designing.</h1>
<p> An external style sheet can be written in any text editor, and must be saved with a .css
extension.<br>

The external .css file should not contain any HTML tags

.</p>

</body>
</html>
An external style sheet can be written in any text editor, and must be saved with a .css extension.

The external .css file should not contain any HTML tags.

Here is how the "mystyle.css" file looks:

"mystyle.css"

body {
background-color: lightblue;
}

h1 {
color: navy;
margin-left: 20px;
}

Internal CSS

An internal style sheet may be used if one single HTML page has a unique style.

The internal style is defined inside the <style> element, inside the head section.

Example

Internal styles are defined within the <style> element, inside the <head> section of an HTML
page:

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}

h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>

<h1>Welcome to designing.</h1>
<p> An style sheet can be written in any text editor, and must be saved with a .css
extension.<br>

.</p>

</body>
</html>

Inline CSS

An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can contain
any CSS property.

Example

Inline styles are defined within the "style" attribute of the relevant element:

<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>


<p style="color:red;">This is a paragraph.</p>

</body>
</html>
Explain the difference between id and class selector in css.

Q 25 Differences between Class and Id

Ans

Class Id
We can apply a class to various elements so that it The Id is unique in a page, and we can
could be numerous times on a single page. only apply it to one specific element.
The class is assigned to an element and its name The name of the Id starts with the "#"
starts with "." followed by the name of the class. symbol followed by a unique id name.
We can attach only one ID selector to an
We can attach multiple class selectors to an element.
element.
Syntax: Syntax:
.class{ #id{
// declarations of CSS // declarations of CSS
} }
CSS id Selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique
element!

To select an element with a specific id, write a hash (#) character, followed by the id of the
element.

#para1 {
text-align: center;
color: red;
}

<!DOCTYPE html>

<html>

<head>

<style>

#para1 {

text-align: center;

color: red;

</style>

</head>

<body>

<p id="para1">Hello World!</p>

<p>This paragraph is not affected by the style.</p>

</body>

</html>
Output: Hello World!

This paragraph is not affected by the style.

Class Selector

The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the class name.

Example

In this example all HTML elements with class="center" will be red and center-aligned:

.center {
text-align: center;
color: blue;
}

<!DOCTYPE html>
<html> <head>
<style>
.example {
text-align: center;
color: blue;
font-size: 25px;
}
</style>
</head>
<body>
<h1 class="example">This heading is blue and center-aligned.</h1>
<p class="example">This paragraph is blue and center-aligned.</p>
</body>
</html>

Q 26:Explain inline and block level element with example.

Ans Block-level Elements

A block-level element always starts on a new line, and the browsers automatically add some
space (a margin) before and after the element.

A block-level element always takes up the full width available (stretches out to the left and right
as far as it can).
Two commonly used block elements are: <p> and <div>.

The <p> element defines a paragraph in an HTML document.

The <div> element defines a division or a section in an HTML document.

The <p> element is a block-level element.

The <div> element is a block-level element.


Example:
<!DOCTYPE html>
<html>
<style>
div {
background-color: #FFF4A3;
}
</style>
<body>

<h1>HTML DIV Example</h1>

<div>
<h2>London</h2>
<p>London is the capital city of England.</p>
<p>London has over 13 million inhabitants.</p>
</div>

<p>The yellow background is added to demonstrate the footprint of the DIV element.</p>

</body>
</html>

block-level elements in HTML:

<address> <article> <aside> <blockquote> <canvas> <dd> <div>


<dl> <dt> <fieldset> <figcaption> <figure> <footer> <form> <h1>-<h6>
<header> <hr> <li> <main> <nav> <noscript> <ol> <p> <pre> <section> <table> <tfoot> <ul>
<video>

Inline Elements

An inline element does not start on a new line.

An inline element only takes up as much width as necessary.


This is a <span> element inside a paragraph.

<!DOCTYPE html>

<html>

<body>

<h1>The span element</h1>

<p>My mother has <span style="color:blue;font-weight:bold;">blue</span> eyes and my father


has <span style="color:darkolivegreen;font-weight:bold;">dark green</span> eyes.</p>

</body>

</html>

inline elements in HTML:

<a> <abbr> <acronym> <b> <bdo> <big> <br> <button> <cite> <code> <dfn> <em> <i>
<img> <input> <kbd> <label> <map>
<object> <output> <q> <samp> <script> <select> <small> <span> <strong> <sub>
<sup> <textarea> <time> <tt> <var>

Q 27 Explain different types of selectors in css.


Ans CSS Selectors

CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

 Simple selectors (select elements based on name, id, class)


 Combinator selectors (select elements based on a specific relationship between them)
 Pseudo-class selectors (select elements based on a certain state)
 Pseudo-elements selectors (select and style a part of an element)
 Attribute selectors (select elements based on an attribute or attribute value)

Simple selectors:
Select element to style on the basis of the name of tag select .In below example ,we
select a <p>(para tag) on which apply the CSS properties.

Example:

p{
text-align: center;
color: red;
}

<!DOCTYPE html>

<html>

<head>

<style>

p{

text-align: center;

color: red;

</style>

</head>

<body>

<p>Every paragraph will be affected by the style.</p>

<p id="para1">Me too!</p>

<p>And me!</p>

</body>

</html>

Output:
Every paragraph will be affected by the style.

Me too!

And me!

CSS id Selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique
element!

To select an element with a specific id, write a hash (#) character, followed by the id of the
element.

#para1 {
text-align: center;
color: red;
}

Class Selector

The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the class name.

Example

In this example all HTML elements with class="center" will be red and center-aligned:

.center {
text-align: center;
color: blue;
}

CSS Universal Selector

The universal selector (*) selects all HTML elements on the page.

Example
The CSS rule below will affect every HTML element on the page:

*{
text-align: center;
color: blue;
}

CSS Grouping Selector

The grouping selector selects all the HTML elements with the same style definitions.

Example

In this example we have grouped the selectors from the code above:

h1, h2, p {
text-align: center;
color: red;
}

CSS Combinators
• A combinator is something that explains the relationship between the selectors.
• A CSS selector can contain more than one simple selector. Between the
simple selectors, we can include a combinator.
There are four different combinators in CSS:
• descendant selector (space)
• child selector (>)
• adjacent sibling selector (+)
• general sibling selector (~)

1. Descendent Selectors: This Selector targets both direct and indirect children of a parent tag.
The symbol is (space)
Syntax: parent_tag child_tag{property: value;}

2. Child Selectors: This Selector targets the only the direct children of the parent tag. The symbol
is > (greater than)
Syntax: parent_tag > child_tag{property: value;}
3. Adjacent Selectors: This Selector targets the element which is the first sibling of the targeted
HTML tag or element.
This Selector targets the element which is exactly adjacent to the targeted HTML tag or element.
The symbol is + (plus)
Syntax: parent_tag + target_tag{property: value;}

4. General Sibling Selectors: This Selector targets all the siblings of the target HTML tag or
element.
This Selector targets all the adjacent tags of the target HTML tag or element.
The symbol is ~ (tilde)
Syntax: parent_tag ~ target_tag{property: value;}

Q 28 Write the syntax of CSS property that can be used to remove the underline from a hyperlink

Ans: Syntax:

a:link {
text-decoration: none;
}

Q 29 Construct a web page using CSS to show the 3 horizontal and 3 vertical navigation bars
that links to the different web pages

Ans:
<!DOCTYPE html>
<html>
<head>
<style>

.horizontal-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
margin-right: 10px;
border-radius: 5px;
}

.horizontal-nav {
display: inline;
flex-direction: row;
background-color: #333;
padding: 10px; margin-bottom: 20px; }

.vertical-nav
{
display: block;
flex-direction: column;
background-color: #333;
padding: 10px;
}
.vertical-nav a {
color: white;
text-decoration: none;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
</style>
</head>
<body>

<div class="horizontal-nav">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
</div>

<div class="vertical-nav">
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</div>

</body>
</html>
}

Q30.Explain box model in CSS. Design a web page with a table of 6 rows. Use nthchild property
of CSS to color Odd rows and even rows in different colors. Highlight the even rows on mouse
over.

Ans

In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It consists of:
content, padding, borders and margins. The image below illustrates the box model:

Explanation of the different parts:

 Content - The content of the box, where text and images appear
 Padding - Clears an area around the content. The padding is transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is transparent

Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 15px solid green;
padding: 100px;
margin: 50px;
}
</style>
</head>
<body>

<h2>Demonstrating the Box Model</h2>

<p>The CSS box model is essentially a box that wraps around every HTML element. It consists
of: borders, padding, margins, and the actual content.</p>
<div>This text is the content of the b`ox. We have added a 50px padding, 20px margin and a
15px green border
</body>
</html>
Use nthchild property of CSS to color Odd rows and even rows in different colors. Highlight the
even rows on mouse over.

<!DOCTYPE html>
<html lang="en">
<head>
<title>
To set alternate table row color using CSS
</title>
<style>
.highlight { background-color: #8888FF }
.normal { background-color: #c8e6c9}

table {
width: 20%;
border-collapse: collapse;
}
th {
background-color: #04af2f;
color:white;
}
th, td {
padding: 10px;
border: 1px solid #ccc;
text-align: center;
}
tr:nth-of-type(even) {
background-color: #c8e6c9;
onMouseOver: "this.className='highlight'";
onMouseOut:"this.className='normal'";

}
tr:nth-of-type(odd) {
background-color: #e8f5e9;
}
</style>
</head>
<body>
<h3>
To Set Alternate Table Row Color Using CSS
</h3>
<p>
In this example we have used <strong>nth-of-type
</strong> psuedo-class selector to set alternate
table row color using CSS.
</p>
<table>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
<tr>
<td>Ravi</td>
<td>7045689765</td>
</tr>
<tr>
<td>Amit</td>
<td>9876543210</td>
</tr>
<tr>
<td>Priya</td>
<td>9123456789</td>
</tr>
<tr>
<td>Sunil</td>
<td>8234567890</td>
</tr>
<tr>
<td>Neha</td>
<td>9654321098</td>
</tr>
</table>
</body>
</html>

Q31 Explain cascading and the style precedence rules when using multiple approaches.

Ans

 Inline style: Inline style has highest priority among all.


 Id Selector: It has second highest priority.
 Classes, pseudo-classes and attributes: These selectors has lowest priority.
Q 32 Explain image spites with example. Explain Float css property.

Ans: Image Sprites: image sprite is a collection of images put into a single image.

A web page with many images can take a long time to load and generates multiple server
requests.

Using image sprites will reduce the number of server requests and save bandwidth.

Example;

!DOCTYPE html>
<html>
<head>
<style>
#home {
width: 46px;
height: 44px;
background: url(img_navsprites.gif) 0 0;
}

#next {
width: 43px;
height: 44px;
background: url(img_navsprites.gif) -91px 0;
}
</style>
</head>
<body>

<img id="home" src="img_trans.gif" width="1" height="1">


<img id="next" src="img_trans.gif" width="1" height="1">

</body>
</html>
Float:
The float property specifies whether an element should float to the left, right, or not at all.

Syntax:

float: none|left|right|initial|inherit;

<!DOCTYPE html>
<html>
<head>
<style>
img {
float: left;
}
</style>
</head>
<body>
<h1>The float Property</h1>
</body>

</html>

Q 33 Explain border and margin css properties. Explain Z-index.

Ans The CSS border properties allow you to specify the style, width, and color of an element's
border.

The border-style property specifies what kind of border to display.

The following values are allowed:

 dotted - Defines a dotted border


 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
 hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border,
bottom border, and the left border).

Margin:
Margins are used to create space around elements, outside of any defined borders.

CSS has properties for specifying the margin for each side of an element:

 margin-top
 margin-right
 margin-bottom
 margin-left
If the margin property has four values:

 margin: 25px 50px 75px 100px;


o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px

If the margin property has three values:

 margin: 25px 50px 75px;


o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px

If the margin property has two values:

 margin: 25px 50px;


o top and bottom margins are 25px
o right and left margins are 50px

z-index property specifies the stack order of an element.

An element with greater stack order is always in front of an element with a lower stack order.

Note: z-index only works on positioned elements (position: absolute, position: relative, position:
fixed, or position: sticky) and flex items (elements that are direct children of display:flex
elements).

Q 34 Explain navigation bar with example. Explain position.

Ans A navigation bar is basically a list of links, so using the <ul> and <li> elements makes
perfect sense:
<!DOCTYPE html>
<html>
<body>

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>

<p>Note: We use href="#" for test links. In a real web site this would be URLs.</p>

</body>
</html>
Example for horizontal navigation
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
}

li {
display: inline;
}
</style>
</head>
<body>

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>

</body>
</html>
Position

The position property specifies the type of positioning method used for an element.

There are five different position values:

 static
 relative
 fixed
 absolute
 sticky
HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned
according to the normal flow of the page.

Syntax: postion:static;

Q 35 Differentiate between display :inline & display: inline block.

Ans:

display: inline display: inline-block

The width and height of the display: inline elements The width and height of the display:
can’t be changed. inline-block elements can be changed.
It can have padding and margin in the horizontal
It can have padding and margin in all four
direction. But, with respect to the vertical direction,
directions.
it does not have a margin and padding.

It cannot have a child block element. It can have a child block element.

Q 36 Explain Website layout with example.

Ans A website can be divided into various sections comprising of header, menus, content, and
footer based on which there are many different layout designs available for developers. Different
layouts can be created by using a div tag and using CSS property to style it.

Structure of Website Layout


1. Header Section

A header is usually located at the top of the website (or right below a top navigation menu). It
often contains a logo or the website name.

2.Navigation Bar

A navigation bar contains a list of links to help visitors navigating through your website.

Content Section

The content section is the main body of the website. The user can divide the content section in an
n-column layout.
The most common layouts are:

 1 Column Layout: It is mostly used for mobile layout.


 2 Column Layout: This website layout is mostly used for tablets or laptops.

 3 Column Layout: This website layout is mostly used for desktops.


The user can also create a responsive layout where the layout will get changed as per screen size.
Consider the below example where if the idth of the screen is more than 600px then there will be
a 3-column layout and if the width of the screen is between 400px to 600px then there will be a 2-
column layout and if the screen size is less than 400px then the 1-column layout will display.

Footer

The footer is placed at the bottom of your page. It often contains information like copyright and
contact info.

Example:

<!DOCTYPE html>

<html lang="en">

<head>

<title>CSS Website Layout</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>

*{

box-sizing: border-box;

color:white;

}
body {

margin: 0;

background-image:url("desert.jpg");

color:white;

/* Style the header */

.header {

background-color: #f1f1f1;

padding: 20px;

text-align: center;

background-image:url("Hydrangeas.jpg");

color:white;

/* Style the top navigation bar */

.topnav {

overflow: hidden;

background-color: #333;

/* Style the topnav links */

.topnav a {

float: left;
display: block;

color: #f2f2f2;

text-align: center;

padding: 14px 16px;

text-decoration: none;

/* Change color on hover */

.topnav a:hover {

background-color: #ddd;

color: red;

/* Create three equal columns that floats next to each other */

.column {

float: left;

width: 33.33%;

padding: 15px;

/* Clear floats after the columns */

.row::after {

content: "";

display: table;
clear: both;

/* Responsive layout - when the screen is less than 800px wide, make the two columns stack on
top of each other instead of next to each other */

@media screen and (max-width: 800px) {

.leftcolumn, .rightcolumn {

width: 100%;

padding: 0;

/* Responsive layout - when the screen is less than 400px wide, make the navigation links stack
on top of each other instead of next to each other */

@media screen and (max-width: 400px) {

.topnav a {

float: none;

width: 100%;

.footer {

padding: 20px;

align: center;

background: #ddd;
margin-top: 20px;

text-align: center;

</style>

</head>

<body>

<div class="header">

<h1>Header</h1>

<p>Resize the browser window to see the responsive effect.</p>

</div>

<div class="topnav">

<a href="#">Link</a>

<a href="#">Link</a>

<a href="#">Link</a>

</div>

<div class="row">

<div class="column">

<h2>Responsive web page design</h2>

<p>Responsive Web design is the approach that suggests that design and development should
respond to the user’s behavior and environment based on screen size, platform and
orientation.</p>
</div>

<div class="column">

<h2>Resposive architecture</h2>

<p>Recently, an emergent discipline called “responsive architecture” has begun asking how
physical spaces can respond to the presence of people passing through them. Through a
combination of embedded robotics and tensile materials, architects are experimenting with art
installations and wall structures that bend, flex, and expand as crowds approach them. Motion
sensors can be paired with climate control systems to adjust a room’s temperature and ambient
lighting as it fills with people. Companies have already produced “smart glass technology” that
can automatically become opaque when a room’s occupants reach a certain density threshold,
giving them an additional layer of privacy.”</p>

</div>

<div class="column">

<h2>Flexible Images</h2>

<p>The data-fullsrc is a custom HTML5 attribute.</p>

</div>

</div>

<div class="footer">

<h2>Footer</h2>

</div>

</body>

</html>
Q37 Explain different types of border with example.

Ans The CSS border properties allow you to specify the style, width, and color of an element's
border.

The border-style property specifies what kind of border to display.

The following values are allowed:

 dotted - Defines a dotted border


 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
 hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border,
bottom border, and the left border).

Example:

<!DOCTYPE html>

<html>

<head>

<style>

p.dotted {border-style: dotted;}

p.dashed {border-style: dashed;}

p.solid {border-style: solid;}

p.double {border-style: double;}

p.groove {border-style: groove;}

p.ridge {border-style: ridge;}

p.inset {border-style: inset;}


p.outset {border-style: outset;}

p.none {border-style: none;}

p.hidden {border-style: hidden;}

p.mix {border-style: dotted dashed solid double;}

</style>

</head>

<body>

<h2>The border-style Property</h2>

<p>This property specifies what kind of border to display:</p>

<p class="dotted">A dotted border.</p>

<p class="dashed">A dashed border.</p>

<p class="solid">A solid border.</p>

<p class="double">A double border.</p>

<p class="groove">A groove border.</p>

<p class="ridge">A ridge border.</p>

<p class="inset">An inset border.</p>

<p class="outset">An outset border.</p>

<p class="none">No border.</p>

<p class="hidden">A hidden border.</p>

<p class="mix">A mixed border.</p>


</body>

</html>

Q38 Write code to create different types of link using pseudo-class selector.

Ans A pseudo-class is used to define a special state of an element.

A pseudo-class can be defined as a keyword which is combined to a selector that defines the
special state of the selected elements. It is added to the selector for adding an effect to the
existing elements based on their states. For example, The ":hover" is used for adding special
effects to an element when the user moves the cursor over the element.

For example, it can be used to:

 Style an element when a user mouse over it


 Style visited and unvisited links differently
 Style an element when it gets focus

Syntax:

selector:pseudo-class {
property: value;
}
Dynamic Pseudo Classes
Pseudo Class Selector specifies the special state of the content.
The Pseudo Class Selector are:
1. Link
2. Visited
3. Hover
4. Active
5. Focus
o Each dynamic pseudo class selector is declared with the single colon :
o Link, Visited only applicable for anchor tag.
o Link is used to style the unvisited link
o Link doesn’t style the already visited link.
o Active applies the style at the time of click event.
o Hover is applicable for all the HTML elements.
o Focus styles when the element is focused.
o Focus selector is applicable for <a> tag and also for the elements which takes user input
that is for <input> and textarea> tag.
o While using all the Link, Visited, Hover and Active selectors. Hover should be declared
after Link and Visited. Along with that the Active should be declared after Hover,
because to make the elements effective.

Example:
a : link {
color: aqua;
background-color : red;
}

a : visited {
color : green;
}

a : hover {
color : yellow;
}

a : active {
color : chocolate;
}

input : focus{
color : red;
background-color : yellow;
}

Example:
<!DOCTYPE html>

<html>

<head>

<style>

/* unvisited link */

a:link {

color: red;

/* visited link */

a:visited {

color: green;

/* mouse over link */

a:hover {

color: hotpink;

/* selected link */

a:active {

color: blue;

}
</style>

</head>

Example:

<html>

<head>

<style>

p{

display: none;

background-color: yellow;

padding: 20px;

div:hover p {

display: block;

</style>

</head>

<body>

<div>Hover over this div element to show the p element

<p>Tada! Here I am!</p>

</div>
</body>

</html>

Q39 Explain CSS position property with example.

Ans The position property specifies the type of positioning method used for an element.

There are five different position values:

 static
 relative
 fixed
 absolute
 sticky

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned
according to the normal flow of the page.

Syntax: postion:static;

This <div> element has position: static;

An element with position: fixed; is positioned relative to the viewport, which means it always
stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are
used to position the element.

A fixed element does not leave a gap in the page where it would normally have been located.

Syntax: position: fixed;

An element with position: relative; is positioned relative to its normal position.

Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it
to be adjusted away from its normal position.

Syntax: position :relative;


An element with position: absolute; is positioned relative to the nearest positioned ancestor
(instead of positioned relative to the viewport, like fixed).

However if an absolute positioned element has no positioned ancestors, it uses the document
body, and moves along with page scrolling.

Synatx: position:absolute;

Example:

<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
background-image:url("lighthouse.jpg");
}

div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: absolute;</h2>

<p>An element with position: absolute; is positioned relative to the nearest positioned ancestor
(instead of positioned relative to the viewport, like fixed):</p>

<div class="relative">This div element has position: relative;


<div class="absolute">This div element has position: absolute;</div>
</div>

</body>
</html>
Q 40 Explain different combinators selector in CSS

Ans CSS Combinators


• A combinator is something that explains the relationship between the selectors.
• A CSS selector can contain more than one simple selector. Between the
simple selectors, we can include a combinator.
There are four different combinators in CSS:
• descendant selector (space)
• child selector (>)
• adjacent sibling selector (+)
• general sibling selector (~)

1. Descendent Selectors: This Selector targets both direct and indirect children of a parent tag.
The symbol is (space)
Syntax: parent_tag child_tag{property: value;}

2. Child Selectors: This Selector targets the only the direct children of the parent tag. The symbol
is > (greater than)
Syntax: parent_tag > child_tag{property: value;}

3. Adjacent Selectors: This Selector targets the element which is the first sibling of the targeted
HTML tag or element.
This Selector targets the element which is exactly adjacent to the targeted HTML tag or element.
The symbol is + (plus)
Syntax: parent_tag + target_tag{property: value;}

4. General Sibling Selectors: This Selector targets all the siblings of the target HTML tag or
element.
This Selector targets all the adjacent tags of the target HTML tag or element.
The symbol is ~ (tilde)
Syntax: parent_tag ~ target_tag{property: value;}
41.Construct a JavaScript program using text boxes, two for inputs and others for output,
implement four operations addition, subtraction, multiplication and division on two input
numbers on clicking of buttons ‘add’, ‘subtract’, ‘multiply’ and ‘divide’. Print the result in text
box.
<!doctype html>
<html>
<head>
<script>
var numOne, numTwo, res, temp;
function fun()
{
numOne = parseInt(document.getElementById("one").value);
numTwo = parseInt(document.getElementById("two").value);
if(numOne && numTwo)
{
temp = document.getElementById("res");
temp.style.display = "block";
res = numOne + numTwo;
document.getElementById("add").value = res;
res = numOne - numTwo;
document.getElementById("subtract").value = res;
res = numOne * numTwo;
document.getElementById("multiply").value = res;
res = numOne / numTwo;
document.getElementById("divide").value = res;
}
}
</script>
</head>
<body>

<p id="input">Enter First Number: <input id="one">


<br/><br/>
Enter Second Number: <input id="two"></p>
<p><button onclick="fun()">Add, Subtract, Multiply, Divide</button></p>
<p id="res" style="display:none;">
Addition Result = <input id="add"><br/><br/>
Subtraction Result = <input id="subtract"><br/><br/>
Multiplication Result = <input id="multiply"><br/><br/>
Division Result = <input id="divide"></p>

</body>
</html>

Here is its output:


42.Discuss in brief how to perform Client Side Validation like Mandatory fields and Email field
using Java Script? Justify with a suitable example.

<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>

43.Design a JavaScript program to display the current day and time in the following format.
Today is : Monday. Current time is : 11 AM : 50 : 58

// Get the current date and time


var today = new Date();

// Get the day of the week (0-6, where 0 is Sunday and 6 is Saturday)
var day = today.getDay();
// Array of day names
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

// Display the current day


console.log("Today is: " + daylist[day] + ".");

// Get the current hour, minute, and second


var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();

// Determine if it's AM or PM
var prepand = (hour >= 12) ? " PM " : " AM ";

// Convert 24-hour format to 12-hour format


hour = (hour >= 12) ? hour - 12 : hour;

// Check for special cases when hour is 0


if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}

// Check for special cases when hour is 0


if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}

// Display the current time


console.log("Current Time: " + hour + prepand + " : " + minute + " : " + second);

44. Why do we need client side scripting languages like Java Script? How AJAX like technologies
is so useful these days? How AJAX is used for single page processing?

Why do we need client-side scripting language?


Client side scripting is used for validation purpose. If the user enters incorrect credentials on the login
page, the web page displays an error message on the client machine without submitting it to the web
server. To create ad banners that interact with the user, rather than simply displaying graphics.
AJAX (asynchronous JavaScript and XML) is a set of web development techniques that are useful
because they improve the performance and usability of web applications. AJAX is a universally used
technique and an essential part of front-end development.

Asynchronous JavaScript and XML (AJAX) is used for single page processing by allowing web pages
to be updated without reloading the entire page. This is done by exchanging small amounts of data with
the server behind the scenes.
Here's how AJAX works for single page processing:
1. Event occurs: A user performs an action on the web page, such as clicking a button
2. JavaScript creates an XMLHttpRequest object: This object sends a request to the web server
3. Server processes the request: The server uses a server-side scripting language like PHP, Java, Ruby, or
Python to process the request
4. Server sends a response: The server sends the requested HTML, XML, or JavaScript data back to the
web page
5. JavaScript reads the response: JavaScript performs the proper action, such as updating the page
AJAX allows for quick website interaction because only parts of the page are reloaded and
refreshed. Some examples of applications that use AJAX include Google Maps, Gmail, YouTube, and
Facebook tabs.

45. Illustrate Array in JavaScript. Create a program in JavaScript to implement an array of five
elements and perform the operations push, pop, shift, unshift and join on the array.

JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

● push(): Add elements to the end of an Array


● pop(): Remove an element from end of an Array
● shift(): Remove an Element from the front of an Array
● unshift(): Add elements to the front of an Array

push(): Add elements to the end of an Array

Using push() we can add elements to the end of an array.

let arr = [ 1, 2, 3 ];
arr.push(4);
console.log(arr);
// [ 1, 2, 3, 4 ]
push() returns length of the new array.

let arr = [ 1, 2, 3, 4 ];
let arrLength = arr.push( 5, 6, 7 );
console.log(arrLength);
// 7

pop(): Remove an element from end of an Array

● Pop remove the last element in an Array.

let arr = [1, 2, 3, 4];


arr.pop();
console.log(arr);
// [ 1, 2, 3 ]
pop() returns the removed element.

let arr = [ 1, 2, 3, 4 ];
let removedElement = arr.pop();
console.log(removedElement);
// 4

shift(): Remove an Element from the front of an Array

Shift remove the first element in an Array.

let arr = [ 0, 1, 2, 3 ];
arr.shift();
console.log(arr);
// [ 1, 2, 3 ]
shift() returns the removed element from the array.

let arr = [ 0, 1, 2, 3 ];
let removedElement = arr.shift();
console.log(removedElement);
// 0

unshift(): Add elements to the front of an Array

Using unshift() we can add elements to the front of an array.

let arr = [ 1, 2, 3 ];
arr.unshift(0);
console.log(arr);
// [ 0, 1, 2, 3 ]
unshift() returns length of the new array.

let arr = [ 4, 5, 6 ];
let arrLength = arr.unshift( 0, 1, 2, 3 );
console.log(arrLength);
// 7
46.Write a program in JavaScript to print first n terms of Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, 21,
34…)
/ program to generate fibonacci series up to n terms

// take input from the user


const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;

console.log('Fibonacci Series:');

for (let i = 1; i <= number; i++) {


console.log(n1);
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}
Enter the number of terms: 4
Fibonacci Series:
0
1
1
2
47.Explain the various event handlers in JavaScript with an example .
HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

● An HTML web page has finished loading


● An HTML input field was changed
● An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

In the example above, the JavaScript code changes the content of the element with id="demo".

In the next example, the code changes the content of its own element (using this.innerHTML):

Example
<button onclick="this.innerHTML = Date()">The time is?</button>
Common HTML Events
Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

JavaScript Event Handlers

Event handlers can be used to handle and verify user input, user actions, and browser actions:

● Things that should be done every time a page loads


● Things that should be done when the page is closed
● Action that should be performed when a user clicks a button
● Content that should be verified when a user inputs data
● And more ...

Many different methods can be used to let JavaScript work with events:
● HTML event attributes can execute JavaScript code directly
● HTML event attributes can call JavaScript functions
● You can assign your own event handler functions to HTML elements
● You can prevent events from being sent or being handled
● And more ...

48.Explain Website layout and navigation bar.


Navigation Bar = List of Links

A navigation bar needs standard HTML as a base.

In our examples we will build the navigation bar from a standard HTML list.

A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect sense:

Example
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>

HTML Layout Elements

HTML has several semantic elements that define the different parts of a web page:

● <header> - Defines a header for a document or a


section
● <nav> - Defines a set of navigation links
● <section> - Defines a section in a document
● <article> - Defines an independent, self-contained
content
● <aside> - Defines content aside from the content (like
a sidebar)
● <footer> - Defines a footer for a document or a
section
● <details> - Defines additional details that the user can
open and close on demand
● <summary> - Defines a heading for
the <details> element

You can read more about semantic elements in our HTML


Semantics chapter.

49.Design a HTML form with name, address, pincode and password. Outline a JavaScript code that can
validate on following constraints: a. No fields must be left blank b. Pincode must be numeric and
contain 6 digits c. Password field (i) At least contains 1 Capital letter. (ii) Minimum length 8 characters

<html>
<head>
<script>
function fun()
{
let x = document.forms["f1"]["t1"].value;
let y = document.forms["f1"]["t2"].value;
if (x.length<6)
{
alert("error1");
}
if (!isNaN(x))
{
alert("error2");
}
if (y.length<6)
{
alert("error3");
}
}
</script>
</head>
<body>
<form name="f1">
Name<input type="text" name="t1" ><br>
Password<input type="password" name="t2">
<input type="button" onclick="fun()" value="ok">
</form>
</body>
</html>

Pincode Validation

<!DOCTYPE html>

<html>

<head>

<title>Pincode Validation</title>

</head>

<body style="color:blue; background-color:cyan"><form name="form1">

<h1 align="center">

Enter Pincode value:-<input type="text" name="t1"><br><br>

<input type="button" value="Submit pincode" onClick="validate()">

</h1>

<script type="text/javascript">

function validate()

var pincode;

pincode=form1.t1.value;

if(pincode.length==0)

alert("please check the pincode");

form1.t1.focus();

else if(Number.isInteger(pincode))
{

alert("please enter the the number only");

form1.t1.focus();

else if(pincode.length<6||pincode.length>8)

alert("pincode should be 6 or 8 numbers");

form1.t1.focus();

else

alert("Pincode accepted");

</script>

</body>

</html>

Password Validation

<!DOCTYPE html>
<html>

<body>

<h3>Password Validation</h3>
<p>Try to submit the form.</p>

<div>
<form action="/action_page.php">

<label >Password</label>
<input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more
characters" required>
<input type="submit" value="Submit">
</form>
</div>

<div >
<h3>Password must contain the following:</h3>
<p >A <b>lowercase</b> letter</p>
<p >A <b>capital (uppercase)</b> letter</p>
<p >A <b>number</b></p>
<p >Minimum <b>8 characters</b></p>
</div>

<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");

// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}

// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}

// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}

// Validate capital letters


var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}

// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}

// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>

</body>
</html>
50.Discuss function in Java Script. Outline a JS function that takes 4 variables, a, b, c, d, and
prints true in an alert box if input a > input b and input c > input d. Else, print false in an alert
box
A JavaScript function is a block of code designed to perform a particular task.
Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}

Example

Calculate the product of two numbers, and return the result:

// Function is called, the return value will end up in x


let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

<script language="JavaScript">
function question9(a,b,c,d)
{
if (a>b&&c>d) {
alert("true")
}
else {
alert("false")
}
}
</script>
51.What is AJAX? Explain its advantage and its working? Explain with example?

AJAX tutorial covers concepts and examples of AJAX technology for beginners and professionals.
AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related
technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc.
What is AJAX?
AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.
AJAX allows you to send only important information to the server not the entire page. So only valuable
data from the client side is routed to the server side. It makes your application interactive and faster.
Where it is used?
There are too many web applications running on the web that are using ajax technology
like gmail, facebook,twitter, google map, youtube etc.

Understanding Synchronous vs Asynchronous

Before understanding AJAX, let’s understand classic web application model and ajax web application
model first.
Synchronous (Classic Web-Application Model)
A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In such
case, javascript engine of the browser is blocked.
Figure 3.3 Synchronous Model
As you can see in the above image, full page is refreshed at request time and user is blocked until
request completes.

Figure 3.4 Synchronous communication


Asynchronous (AJAX Web-Application Model)
An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can
perform another operations also. In such case, javascript engine of the browser is not blocked.

Figure 3.5 ASynchronous Model


As you can see in the above image, full page is not refreshed at request time and user gets response from
the ajax engine.
Let's try to understand asynchronous communication by the image given below.

Figure 3.6 ASynchronous Communication

AJAX Technologies

As describe earlier, ajax is not a technology but group of inter-related technologies. AJAX technologies
includes:
● HTML/XHTML and CSS
● DOM
● XML or JSON
● XMLHttpRequest
● JavaScript

Understanding XMLHttpRequest

An object of XMLHttpRequest is used for asynchronous communication between client and server.
It performs following operations:
1. Sends data from the client in the background
2. Receives the data from the server
3. Updates the webpage without reloading it.

How AJAX works?

AJAX communicates with the server using XMLHttpRequest object. Let's try to understand the flow of
ajax or how ajax works by the image displayed below.

Figure 3.7 AJAX


As you can see in the above example, XMLHttpRequest object plays a important role.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
52.Describe various applications of JavaScript as a client side scripting language.

● It can be used both in the front-end and back-end of web development

● Serves everyone from beginners to intermediate and even advanced developers


● Can run on all devices

● It does not need an environment setup

● Standardized and gets frequently updated with new versions

● Open Standards and Community

● Works with Document Object Model (DOM) for response to user interactions

● Transformed web browsers into application platforms

● Wide range of frameworks and libraries to help build complex applications.

1. Web Development
2. Web Applications
3. Presentations
4. Server Applications
5. Web Servers
6. Games
7. Art
8. Smartwatch Apps
9. Mobile Apps
10. Flying Robots
53.Illustrate and compare various dialog boxes in JavaScript with suitable JavaScript code.

JavaScript uses 3 kinds of dialog boxes:


● Alert
● Prompt
● Confirm
Alert Box: An alert box is used on the website to show a warning message to the user that they have
entered the wrong value other than what is required to fill in that position. Nonetheless, an alert box can
still be used for friendlier messages. The alert box gives only one button “OK” to select and proceed.
Example:
● JavaScript

function Warning() {

alert ("Warning danger you have not filled everything");


console.log ("Warning danger you have not filled everything");

Confirm box: A confirm box is often used if you want the user to verify or accept something. When a
confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed. If the user clicks
on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button,
then confirm() returns false and will show null.
Example:
● JavaScript

function Confirmation() {

var Val = confirm("Do you want to continue ?");

if (Val == true) {

console.log(" CONTINUED!");

return true;

} else {

console.log("NOT CONTINUED!");

return false;

Prompt Box: A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after
entering an input value. If the user clicks the OK button, the window method prompt() will return the
entered value from the text box. If the user clicks the Cancel button, the window
method prompt() returns null.
Example:
● JavaScript

function Value(){

var Val = prompt("Enter your name : ", "Please enter your name");

console.log("You entered : " + Val);

54.Describe URL class in Java. Write a Java code display protocol, port number, host of given url
with the help of this class.

Java URL

The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to
a resource on the World Wide Web. For example:

1. https://www.javatpoint.com/java-tutorial

A URL contains many information:

Protocol: In this case, http is the protocol.

Server name or IP Address: In this case, www.javatpoint.com is the server name.

Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80


is the port number. If port number is not mentioned in the URL, it returns -1.

File Name or directory name: In this case, index.jsp is the file name.

//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}
Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
55. Create a JavaScript program to make an arithmetic calculator.

<!-
- Create a simple Program to build the Calculator in JavaScript using with HTML and CSS web languages. -
->
<!DOCTYPE html>
<html lang = "en">
<head>
<title> JavaScript Calculator </title>

<style>
h1 {
text-align: center;
padding: 23px;
background-color: skyblue;
color: white;
}

#clear{
width: 270px;
border: 3px solid gray;
border-radius: 3px;
padding: 20px;
background-color: red;
}

.formstyle
{
width: 300px;
height: 530px;
margin: auto;
border: 3px solid skyblue;
border-radius: 5px;
padding: 20px;
}

input
{
width: 20px;
background-color: green;
color: white;
border: 3px solid gray;
border-radius: 5px;
padding: 26px;
margin: 5px;
font-size: 15px;
}

#calc{
width: 250px;
border: 5px solid black;
border-radius: 3px;
padding: 20px;
margin: auto;
}

</style>

</head>
<body>
<h1> Calculator Program in JavaScript </h1>
<div class= "formstyle">
<form name = "form1">

<!-- This input box shows the button pressed by the user in calculator. -->
<input id = "calc" type ="text" name = "answer"> <br> <br>
<!-- Display the calculator button on the screen. -->
<!-- onclick() function display the number prsses by the user. -->
<input type = "button" value = "1" onclick = "form1.answer.value += '1' ">
<input type = "button" value = "2" onclick = "form1.answer.value += '2' ">
<input type = "button" value = "3" onclick = "form1.answer.value += '3' ">
<input type = "button" value = "+" onclick = "form1.answer.value += '+' ">
<br> <br>

<input type = "button" value = "4" onclick = "form1.answer.value += '4' ">


<input type = "button" value = "5" onclick = "form1.answer.value += '5' ">
<input type = "button" value = "6" onclick = "form1.answer.value += '6' ">
<input type = "button" value = "-" onclick = "form1.answer.value += '-' ">
<br> <br>

<input type = "button" value = "7" onclick = "form1.answer.value += '7' ">


<input type = "button" value = "8" onclick = "form1.answer.value += '8' ">
<input type = "button" value = "9" onclick = "form1.answer.value += '9' ">
<input type = "button" value = "*" onclick = "form1.answer.value += '*' ">
<br> <br>

<input type = "button" value = "/" onclick = "form1.answer.value += '/' ">


<input type = "button" value = "0" onclick = "form1.answer.value += '0' ">
<input type = "button" value = "." onclick = "form1.answer.value += '.' ">
<!-- When we click on the '=' button, the onclick() shows the sum results on the calculator screen. -->
<input type = "button" value = "=" onclick = "form1.answer.value = eval(form1.answer.value) ">
<br>
<!-- Display the Cancel button and erase all data entered by the user. -->
<input type = "button" value = "Clear All" onclick = "form1.answer.value = ' ' " id= "clear" >
<br>

</form>
</div>
</body>
</html>
56.What are the different data types present in javascript?

JavaScript Data Types

JavaScript has 8 Datatypes

String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object

Examples
// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

57.Explain Socket Programming with example

Java Socket Programming

Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.

Here, we are going to make one-way client and server communication. In this application, client sends a
message to the server, server reads the message and prints it. Here, two classes are being used: Socket and
ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read
and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket
class blocks the console until the client is connected. After the successful connection of client, it returns
the instance of Socket at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used
to create a socket.

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket


ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

returns the socket and establish a connection between


1) public Socket accept()
server and client.

2) public synchronized void close() closes the server socket.

File: MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
58.Explain Factory methods with example.Create a Java program to find out the IP address of
your machine.

The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one
of the available factory methods. Factory methods are merely a convention whereby static methods in a
class return an instance of that class. This is done in lieu of overloading a constructor with various
parameter lists when having unique method names makes the results much clearer.
Three commonly used InetAddress factory methods are shown here:
static InetAddress getLocalHost( ) throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException

The getLocalHost( ) method simply returns the InetAddress object that represents the local host. The
getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to
resolve the host name, they throw an UnknownHostException.
On the Internet, it is common for a single name to be used to represent several machines. In the world of
web servers, this is one way to provide some degree of scaling. The getAllByName( ) factory method
returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It
will also throw an UnknownHostException if it can’t resolve the name to at least one address.
InetAddress also includes the factory method getByAddress( ), which takes an IP address and returns an
InetAddress object. Either an IPv4 or an IPv6 address can be used.
The following example prints the addresses and names of the local machine and two Internet web sites:
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.HerbSchildt.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Java program to find IP address of your computer

/ Java program to find IP address of your computer


// java.net.InetAddress class provides method to get
// IP of any host name
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.InetAddress;

public class JavaProgram


{
public static void main(String args[]) throws Exception
{
// Returns the instance of InetAddress containing
// local host name and address
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("System IP Address : " +
(localhost.getHostAddress()).trim());
// Find public IP address
String systemipaddress = "";
try
{
URL url_name = new URL("http://bot.whatismyipaddress.com");
BufferedReader sc =
new BufferedReader(new InputStreamReader(url_name.openStream()));
// reads system IPAddress
systemipaddress = sc.readLine().trim();
}
catch (Exception e)
{
systemipaddress = "Cannot Execute Properly";
}
System.out.println("Public IP Address: " + systemipaddress +"\n");
}
}

Output:
System IP Address : 10.0.8.204
Public IP Address : 35.166.48.97
59.Explain the EJB Architecture . Explain session bean, message bean and entity beans. Also
explain the drawbacks of EJBs.

EJB Architecture Java

Java beans incorporate a set of objects into one accessible object that can be accessed easily from any
application. This single accessible object is maintainable, customizable, and reusable. The setter/getter
method and the single public constructor are used to govern that single accessible object. We can update
and read the value of any variable of any object by using the setter and getter, respectively.

The EJB stands for Enterprise Java beans that is a server-based architecture that follows the
specifications and requirements of the enterprise environment. EJB is conceptually based on the Java
RMI(Remote Method Invocation) specification. In EJB, the beans are run in a container having four-tier
architecture. This architecture consists of four layers, i.e., Client layer, Web layer, Application layer, and
Data layer.

Architecture
The EJB architecture has two main layers, i.e., Application Server and EJB Container, based on which
the EJB architecture exist. The graphical representation of the EJB architecture is given below.

In the above diagram, the logical representation of how EJBs are invoked and deployed by using
RMI(Remote Method Invocation) is defined. The containers of the EJB cannot be self-deployed. In
order to deploy the containers, it requires the Application server.

Application Server
In the EJB architecture, the Application server is the outermost layer that holds or contains the Container
to be deployed. The application layer plays an important role in executing the application developed using
the beans. It provides the necessary environment to execute those applications. Some most popular
application servers are Web-logic, Tomcat, JBoss, Web-sphere, Wildfly, and Glass-finish. The main tasks
of the application server are:

1. Manage Interfaces
2. Execution of the processes
3. Connecting to the database
4. Manage other resources.

Container
In EJB architecture, the Container is the second outermost layer. It is a very important layer for enterprise
beans that are contained in it. For the enterprise bean, the Container provides various supporting services,
which are as follows:

o It provides support for transactional services such as registering the objects, assign remote
interfaces, purge the instances.
o It provides support for monitoring the object's activities and coordinating distributed components.
o It provides support for security services.
o It provides support for the pooling of resources.
o It provides support for managing the Life-cycle of beans and their concurrency.
o It provides support to concentrate on business logic.
Beans
Java beans of the enterprise are installed in the Container in the same way as a Plain old java object (POJO)
is installed and registered to the Container. For developing secured, large scale and robust business
applications, beans provide business logic.

Types of EJB
There are three types of Enterprise Java Beans or EJB available, which are as follows:

1. Stateless Enterprise Java Beans


2. Stateful Enterprise Java Beans
3. Message-driven Enterprise Java Beans

Stateless EJB
In order to implement the stateless business logic, the stateless EJBs are primarily used. Storing a user's
physical address into an inventory system's database is an example of the stateless EJB. In addition, a
stateless bean would be perfect for this type of business logic because it is not necessary to have more
than two forms on the user interface at all stages of the transaction.

Stateful EJB
The Stateful EJB is just opposite to the Stateless EJB. The Stateful EJBs are used when we have to
maintain the state of the application on the backend during the user session. The shopping cart of an online
shopping application is an example of the Stateful EJB. In order to achieve such application, we will use
the following steps:

1. We will create the stateful session bean.


2. After that, for temporarily storing the selected products that are within the user session on the
backend, we have to create a global variable collection of type products.
3. Next, we will create a method through which we will add all the selected products to the collection
that we create in the previous step.
4. We also create a method through which we will remove the product from the collection.
5. In the end, we will create a checkout method for the selected products to process.

Message-driven EJB
Another special type of EJB that is used for sending and receiving messages from message brokers
implements the JMS specification. The systems based on the broker are loosely coupled. The components
that communicate through the broker have the advantage of not waiting for one request to finish before
submitting another request because the broker by nature is asynchronous.

Disadvantages of EJB

1. Requires application server


2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop ejb applications.

60.Illustrate Java Bean. Explain Properties of java Bean. Give example.

JavaBean

In any programming language, reusability is the main concern. To achieve the same concern, Java
introduced the concept of JavaBean. It is a software component that has been designed to be reusable in
a variety of environments. In this section, we will dive into the topic and understand the horizons of
concept in this what is JavaBeans, its advantages, disadvantages, Life cycle.

In other words, JavaBeans are classes that encapsulate multiple objects into a single object. It also helps
in accessing these object from multiple places. It contains several elements like Constructors, getter and
setter methods and much more.

A JavaBean is a Java class that should follow the following conventions:

o Class Definition: They are defined as public classes.


o Serializability (Optional): While not mandatory, they often implement the Serializable interface
to allow object data to be converted into a stream of bytes for storage or transmission.
o No-argument Constructor: JavaBeans must have a public constructor that takes no arguments
(often called a no-arg constructor). It simplifies object creation.
o Data Encapsulation: They encapsulate data using private member variables (fields) to store the
object's state.
o Getter and Setter Methods: For each private field, there should be a corresponding public getter
and setter method:
o Getter methods (usually prefixed with get or is for booleans) retrieve the value of a field.
o Setter methods (usually prefixed with set) modify the value of a field.
Why use JavaBean?
According to Java white paper, it is a reusable software component. A bean encapsulates many objects
into one object so that we can access this object from multiple places. Moreover, it provides easy
maintenance.

Simple Example of JavaBean Class


File Name: Employee.java

//Employee.java

package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}

How to access the JavaBean class?


To access the JavaBean class, we should use getter and setter methods.

File Name: Test.java

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
Note: There are two ways to provide values to the object. One way is by constructor and second is by
setter method.

JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The feature can be
of any Java data type, containing the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through
two methods in the JavaBean's implementation class:
Properties of setter Methods

1. It must be public in nature.


2. The return type a should be void.
3. The setter method uses prefix set.
4. It should take some argument.

Properties of getter Methods

1. It must be public in nature.


2. The return type should not be void.
3. The getter method uses prefix get.
4. It does not take any argument.

For Boolean properties getter method name can be prefixed with either "get" or "is". But recommended
to use "is".

Advantages of JavaBean
The following are the advantages of JavaBean:

o It is portable, compact, and easy.


o The JavaBean properties and methods can be exposed to another application.
o It provides an easiness to reuse the software components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it cannot take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead to the boilerplate code.
Question 61: What is Node.js?

Answer. Node.js is an open-source, cross-platform runtime environment that allows


developers to execute JavaScript code outside of a web browser. It is built on Google Chrome's
V8 JavaScript engine and is designed to build scalable network applications, particularly for
server-side and networking tasks.

Key Features of Node.js:

1. Non-blocking I/O:
o Node.js uses an event-driven, non-blocking I/O model, making it efficient and
lightweight for handling multiple simultaneous connections.
2. Single-threaded, Event-driven Architecture:
o Despite being single-threaded, Node.js handles many concurrent connections
using events and callbacks, making it ideal for I/O-heavy tasks like real-time
applications or APIs.
3. Package Management (npm):
o Node.js includes npm (Node Package Manager), a vast ecosystem of libraries
and modules that developers can use to add functionality to their applications.
4. Cross-platform:
o Node.js works on various operating systems like Windows, macOS, and Linux.
5. Fast Execution:
o Being powered by the V8 engine, it compiles JavaScript to machine code,
leading to fast execution of code.
6. Asynchronous Programming:
o Node.js supports asynchronous programming using callbacks, promises, and
async/await, which are ideal for building high-performance applications.

Common Uses of Node.js:

● Web Servers and APIs: Build RESTful APIs and web servers that can handle a high
number of simultaneous requests.
● Real-time Applications: Applications like chat apps, collaboration tools, and gaming
platforms, where real-time data transmission is critical.
● Command-line Tools: Create scripts and command-line applications for automating
tasks.
● Microservices: Develop microservices for scalability and modular development.

Why Use Node.js?

● High performance for handling concurrent connections.


● A unified development stack (using JavaScript on both the client and server sides).
● A large, active community and extensive library support.
Example of a Simple Server in Node.js:

const http = require('http');

const server = http.createServer((req, res) => {


res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
});

server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});

Question 62: What is the purpose of Node.js?


Answer: The primary purpose of Node.js is to enable developers to use JavaScript to build
scalable and high-performance server-side applications. Traditionally, JavaScript was used
only for client-side development in web browsers, but Node.js extended its functionality to the
server, creating a unified development environment.

Here are the main purposes of Node.js:

1. Server-side Development

● Node.js allows developers to create server-side applications using JavaScript, handling


HTTP requests, APIs, and database operations efficiently.

2. Real-time Applications

● It is well-suited for applications that require real-time communication, such as:


o Chat applications
o Collaboration tools (e.g., Google Docs-like apps)
o Online gaming platforms

3. Building APIs

● With frameworks like Express.js, Node.js simplifies the development of RESTful APIs
and GraphQL APIs. These APIs can serve data to web and mobile applications.

4. Handling High Concurrent Connections

● Node.js's non-blocking, event-driven architecture makes it ideal for handling


applications with a high number of concurrent users, like:
o File uploads
o Streaming services (e.g., Netflix)
o Message queues (e.g., Slack)

5. Microservices Architecture
● Node.js is commonly used for developing microservices, where applications are broken
into smaller, independently deployable services. This ensures better scalability and fault
isolation.

6. Command-line Tools and Automation

● Node.js enables developers to create scripts and automation tools (e.g., build tools, task
runners) that simplify workflows.

7. Scalability

● Its asynchronous architecture and ability to handle many connections with low
overhead make it a great choice for applications requiring scalability.

8. Cross-platform Development

● With tools like Electron.js, Node.js can also be used to build cross-platform desktop
applications (e.g., Slack, Visual Studio Code).

9. Speed and Efficiency

● Node.js leverages Google’s V8 JavaScript engine, which compiles JavaScript to


machine code for fast execution, making it efficient for I/O-bound and computation-
light tasks.

10. Unified Development Stack

● Using Node.js, developers can use JavaScript for both frontend and backend,
simplifying development and enabling code reuse.

Question 63: What are the advantages of Node.js?


Answer: Node.js offers several advantages, particularly for developing high-performance,
scalable, and real-time applications. Here’s a detailed look at its benefits:

1. Fast and Efficient

● Powered by V8 Engine: Node.js is built on Google’s V8 JavaScript engine, which


compiles JavaScript into machine code, ensuring high speed and performance.
● Event-driven Architecture: Its non-blocking, asynchronous nature makes it highly
efficient for handling multiple tasks simultaneously.

2. Scalability

● Node.js is designed to handle a large number of simultaneous connections with minimal


overhead.
● It supports horizontal scaling (adding more servers) and vertical scaling (adding more
resources to the server).
3. Non-blocking I/O

● Node.js uses an event loop for handling I/O operations, which allows it to process
multiple requests without waiting for previous ones to complete. This is ideal for data-
intensive, real-time applications.

4. Single Programming Language

● Developers can use JavaScript for both the frontend and backend, creating a unified
development stack. This reduces the learning curve and improves productivity.
● Code can often be shared or reused between client-side and server-side applications.

5. Large Ecosystem (npm)

● Node.js has a vast library of packages and modules available through npm (Node
Package Manager), which simplifies development by offering pre-built tools for
common tasks.

6. Real-time Applications

● Node.js excels at building real-time applications such as chat applications, gaming


platforms, and collaborative tools due to its ability to handle WebSocket and other real-
time communication protocols.

7. Cross-platform Development

● With frameworks like Electron.js, Node.js can be used to create desktop applications
that work on Windows, macOS, and Linux, using the same codebase.

8. Community Support

● Node.js has a large, active community of developers. This ensures continuous updates,
shared knowledge, and third-party tools to extend its functionality.

9. Lightweight and Memory-efficient

● The event-driven architecture allows Node.js to handle many connections without


consuming significant resources, making it suitable for lightweight and memory-
constrained environments.

10. Asynchronous Programming

● Node.js's asynchronous nature (using callbacks, promises, and async/await) ensures


that applications remain responsive and do not freeze during heavy operations.

11. Streaming and Buffering


● Node.js can handle data streams efficiently, making it ideal for:
o Media streaming services (e.g., video/audio).
o File uploads and downloads in chunks rather than loading the entire file into
memory.

12. Easy to Learn

● Developers familiar with JavaScript on the client side can quickly learn Node.js and
begin building server-side applications.

13. Reduced Time to Market

● Its simplicity, unified language for frontend and backend, and reusable code result in
faster development cycles.

14. Extensibility

● Node.js is highly extensible, allowing developers to customize and extend its


functionality with built-in APIs and third-party libraries.

Use Case Advantages

● Best suited for applications like:


o RESTful APIs
o Real-time apps (e.g., chat, gaming)
o Microservices
o Data-intensive applications

Question 64: Explain Node.js web application architecture?


Answer:Node.js web application architecture refers to the design and structure of a web
application built using Node.js. It defines how the application components interact and how
data flows between the client, server, and database. The architecture leverages Node.js's event-
driven, non-blocking I/O model to create scalable and efficient web applications.
Here’s a breakdown of a typical Node.js web application architecture:

1. Components of Node.js Web Application Architecture

a. Client-Side

● The frontend of the application, usually built using HTML, CSS, and JavaScript
frameworks like React, Angular, or Vue.js.
● The client communicates with the server via HTTP/HTTPS or WebSocket protocols.

b. Server-Side

● The backend, powered by Node.js, handles requests from the client, processes business
logic, and interacts with the database.
● Node.js uses frameworks like Express.js, NestJS, or Koa.js to simplify routing,
middleware, and request handling.

c. Database

● The server communicates with a database to store or retrieve data. Common databases
include:
o SQL Databases: MySQL, PostgreSQL.
o NoSQL Databases: MongoDB, Cassandra.
o Node.js supports both relational and non-relational databases through libraries
like mongoose (for MongoDB) or sequelize (for SQL).

2. Layers in Node.js Web Application Architecture

A Node.js web application typically follows a layered architecture:


a. Presentation Layer

● Purpose: Handles interactions with the user interface (UI) and sends requests to the
server.
● Technologies: Frontend frameworks, RESTful API calls, WebSocket connections.

b. Application Layer

● Purpose: Implements business logic, processes client requests, and sends responses
back to the client.
● Technologies: Node.js frameworks (e.g., Express.js, NestJS).
● Common tasks:
o Routing requests.
o Validating inputs.
o Managing sessions/authentication.

c. Data Access Layer

● Purpose: Interfaces with the database for data storage and retrieval.
● Technologies: ORMs (e.g., Mongoose, Sequelize), direct database queries.

d. Database Layer

● Purpose: Stores and manages the application’s data.


● Technologies: SQL databases (structured) or NoSQL databases (unstructured or semi-
structured).

3. Architecture Styles

Depending on the use case, Node.js applications may adopt different architectural styles:
a. Monolithic Architecture

● All application components (frontend, backend, and database) are tightly integrated.
● Simpler to develop but harder to scale as the application grows.

b. Microservices Architecture

● The application is broken into small, independently deployable services.


● Each service handles a specific functionality (e.g., user management, order processing).
● Services communicate via RESTful APIs, gRPC, or message brokers (e.g., RabbitMQ,
Kafka).

c. Serverless Architecture

● Relies on cloud providers to manage server resources.


● Developers focus on writing functions (e.g., AWS Lambda, Azure Functions).
● Ideal for lightweight or event-driven applications.

d. Real-time Architecture

● Used for applications requiring real-time communication (e.g., chat apps, live games).
● Utilizes WebSockets or libraries like Socket.io for bi-directional communication.

4. Key Features in Node.js Architecture

Event Loop

● Node.js's core feature.


● Handles multiple concurrent requests without blocking threads, enabling efficient
processing.

Non-blocking I/O

● Ensures the application remains responsive while waiting for tasks like database queries
or file operations.

Middleware

● Functions that process requests before reaching the endpoint handler.


● Commonly used for:
o Authentication.
o Logging.
o Request parsing.

Example Node.js Architecture with Express.js


Example Code
A simple Node.js architecture using Express.js:
const express = require('express');
const app = express();

// Middleware
app.use(express.json());

// Routes
app.get('/api/users', (req, res) => {
res.send({ message: 'List of users' });
});

// Business Logic (Controller Layer)


app.post('/api/users', (req, res) => {
const user = req.body;
// Insert into database (Data Access Layer)
res.send({ message: 'User created', user });
});

// Start Server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

7. Benefits of Node.js Architecture

● Scalability: Handles concurrent requests efficiently.


● Real-time Capabilities: Perfect for chat apps, gaming, and live updates.
● Unified Development: JavaScript on both frontend and backend.
● Extensibility: Easily integrate middleware, plugins, or modules.

Question 65: Difference between JavaScript and Node.js

Answer:

Feature JavaScript Node.js


Definition A programming language A runtime environment that
primarily used for client- executes JavaScript outside the
side scripting. browser, mainly for server-side
development.
Primary Use Frontend development Backend development (server-side
(browser-side applications).
applications).
Execution Context Runs in the browser (e.g., Runs on the server or local machine
Chrome, Firefox). (outside the browser).
Libraries/Frameworks Libraries like React, Frameworks like Express.js,
Angular, Vue.js for UI NestJS, and Koa.js for server-side
development. development.
Runtime Environment Browser-based (restricted Server-based (with access to system
by browser sandbox). resources and APIs).
Modules Uses ES6 modules Uses CommonJS modules
(import/export). (require/export) or ES6 modules
(since newer versions).
Asynchronous Supports asynchronous Asynchronous programming is a
Programming programming with core feature, particularly for
callbacks, promises, and handling I/O operations (e.g.,
async/await (mainly for UI database, file system).
events).
File System Access Cannot access the file Can access the file system (fs
system or make network module), perform network requests
requests directly. (http module), etc.
Examples DOM manipulation, form Web servers, REST APIs, file
validation, event handling. handling, real-time applications.
Main Advantage Enables interactivity and Enables building scalable, high-
dynamic behavior on web performance backend applications.
pages.
Platform Runs on any modern web Runs on any operating system
browser. (Windows, macOS, Linux).

Question 66: Explain the working of Node.js?

Answer. Node.js is a powerful, event-driven, non-blocking I/O framework built on Chrome's


V8 JavaScript engine. It's designed to build scalable network applications and is widely used
for creating fast, scalable server-side applications in JavaScript. Here's a breakdown of how
Node.js works:

1. V8 Engine
Node.js is built on Google Chrome's V8 JavaScript engine, which compiles JavaScript directly
to machine code, making it highly efficient and fast.

2. Single-Threaded Event Loop

Node.js operates on a single-threaded event loop model, which is different from traditional
server-side languages (like PHP, Java, or Python), which create a new thread for each incoming
request. In Node.js, the event loop enables the server to handle many requests simultaneously
in a non-blocking, asynchronous manner.

How the Event Loop Works:

● Event Loop: The event loop continuously checks the event queue to see if there are any
I/O operations (e.g., file reading, database queries) that have been completed and need
to be processed.
● Non-Blocking I/O: Node.js performs I/O operations (such as file system access,
network requests, etc.) asynchronously, meaning the application doesn't need to wait
for one operation to complete before moving on to the next.
● Callback Functions: When an I/O task finishes, the event loop executes a callback
function associated with that task. This allows Node.js to keep processing other requests
in the meantime.

3. Asynchronous and Non-blocking

Node.js uses asynchronous programming to handle operations without waiting for one task to
finish before starting another. This is achieved through:

● Callbacks: Functions that are called after an operation completes.


● Promises: An improvement over callbacks, allowing more -NPM (Node Package
Manager) is a tool that is essential to the Node.js ecosystem. It serves two primary
purposes:
1. Package Management: NPM is used to manage libraries and packages that your project
depends on. It allows developers to install, update, and manage third-party packages
easily.
2. Command-Line Interface (CLI): NPM also provides a command-line interface to
interact with the package registry, run scripts, and perform other tasks like managing
dependencies and versioning.
● readable and manageable code for handling asynchronous operations.
● async/await: A syntactic sugar built on promises that allows for asynchronous code to
be written in a more synchronous style, making it easier to read and maintain.

For example, reading a file in Node.js won't block the server from handling other requests;
instead, Node.js will continue processing other requests while it waits for the file to be read.
When the reading is complete, the callback function is executed with the result.

4. Libuv and the Thread Pool

While Node.js itself is single-threaded, it uses the libuv library to handle asynchronous I/O
operations. Libuv provides a thread pool that allows certain types of blocking operations (e.g.,
file system access) to be offloaded to background threads, so the main thread is not blocked.
● The event loop handles non-blocking tasks like HTTP requests, while I/O-bound tasks
(like database queries, file reads, etc.) are passed to the thread pool.
● This architecture enables Node.js to handle many concurrent connections without the
performance issues caused by threading in traditional server models.

5. Module System

Node.js uses a module-based architecture, where code can be organized into reusable modules
(JavaScript files). The require function is used to import modules into an application.

● Core Modules: Node.js comes with a set of built-in modules like fs (file system), http,
path, events, and more.
● Third-party Modules: Node.js also supports a vast ecosystem of external modules
available through npm (Node Package Manager).

6. Network and HTTP Server

Node.js is often used to create HTTP servers that can handle requests. The http module allows
you to create a web server that listens for HTTP requests and sends responses.

7. Event-Driven Architecture

Node.js uses an event-driven architecture where the application can respond to various events
like HTTP requests, user interactions, or sensor data. The application listens for these events
and triggers the appropriate actions when they occur.

● The EventEmitter class allows you to create custom events and handle them
asynchronously.
● For example, you could create an event that fires when a user uploads a file, and the
application can process it without blocking other operations.

8. Concurrency with the Event Loop

Though Node.js is single-threaded, it can handle many concurrent requests effectively due to
its non-blocking nature. While the event loop is processing I/O operations asynchronously, it
can serve multiple requests in parallel. This makes it well-suited for real-time applications like
chat apps, live-streaming, and games.

9. Scalability

Node.js is designed to scale efficiently. Due to its asynchronous, non-blocking nature, it can
handle thousands of concurrent connections. Moreover, you can scale your Node.js application
horizontally by using Cluster Module or tools like PM2 to fork multiple instances of the
application across different CPU cores.

real-time chat, etc.).

Question 67: Explain NPM.


Answer: NPM (Node Package Manager) is a tool that is essential to the Node.js ecosystem. It
serves two primary purposes:

1. Package Management: NPM is used to manage libraries and packages that your project
depends on. It allows developers to install, update, and manage third-party packages
easily.
2. Command-Line Interface (CLI): NPM also provides a command-line interface to
interact with the package registry, run scripts, and perform other tasks like managing
dependencies and versioning.

Question 68:Write a short note on Restful API.

Answer:- RESTful API (Representational State Transfer API)

A RESTful API is an architectural style for designing networked applications, and it is based
on a set of principles that allow clients and servers to communicate over the HTTP protocol.
REST (Representational State Transfer) is a lightweight, stateless, and scalable approach to
building web services that interact with data and resources.

Key Principles of RESTful API:

Stateless: Each request from the client to the server must contain all the information necessary
to understand and process the request (e.g., authentication data, parameters). The server does
not store any client context between requests.

● Client-Server Architecture: The client and server are separate entities, allowing each to
evolve independently. The client makes requests to the server, which processes them
and sends back a response.
● Uniform Interface: A RESTful API has a consistent and predefined set of operations
for interacting with resources (such as GET, POST, PUT, DELETE). This uniformity
simplifies interaction between different components and platforms.
● Resource-Based: RESTful APIs treat data as resources that can be accessed,
manipulated, or represented in different formats (such as JSON or XML). Each resource
is identified by a URI (Uniform Resource Identifier), typically in the form of URLs
(e.g., /users, /products/{id}).

Use of HTTP Methods:

● GET: Retrieve data from the server.


● POST: Create a new resource on the server.
● PUT: Update an existing resource on the server.
● DELETE: Remove a resource from the server.
Representation: A resource can have multiple representations, typically in formats like JSON
or XML. When a client makes a request, the server responds with a representation of the
requested resource.

Example of a RESTful API:

Consider a RESTful API for managing user data:

GET /users: Retrieves a list of all users.

GET /users/{id}: Retrieves details of a specific user by their ID.

POST /users: Creates a new user with the data sent in the request body.

PUT /users/{id}: Updates the user details with the specified ID.

DELETE /users/{id}: Deletes the user with the specified ID.

Benefits of RESTful APIs:

Simplicity: REST is simple to use and understand, as it leverages standard HTTP methods.

Scalability: REST APIs are stateless, allowing easy scalability and distribution of requests.

Interoperability: REST APIs can be used across different platforms (web, mobile, desktop) and
programming languages.

Flexibility: REST allows different data formats, and the client and server can evolve
independently as long as the interface remains consistent.

Question 69: What is REPL terminal?

Answer: REPL terminal is an interactive programming environment that allows users to write
and execute code one command or expression at a time. REPL stands for:

Read: Reads the user input (a single command, expression, or line of code).

Evaluate: Executes the code or expression.

Print: Displays the result of the executed code.

Loop: Returns to the prompt to await the next input.

Key Features of a REPL Terminal:

● Immediate Feedback: You can test code snippets and see the results instantly without
needing to compile or build an entire program.
● Interactive Learning: REPLs are excellent for learning and experimenting with
programming languages.
● Language-Specific: Most modern programming languages provide their own REPL
environments (e.g., Python has the python command, Node.js has node, etc.).
● Error Debugging: REPLs can help you identify and fix errors by running code
incrementally.

Question 70:-What is MongoDB?

Answer:- MongoDB is a popular, open-source, document-oriented database designed to store


and manage data in a flexible, scalable, and performance-efficient way. It is classified as a
NoSQL database, meaning it is not based on the traditional relational database model. Instead,
MongoDB uses a document model, which stores data in JSON-like documents with dynamic
schemas.

Key Features of MongoDB:

● Document-Oriented Storage:

Data is stored in flexible, JSON-like structures called documents, which are organized into
collections.

Documents can contain nested structures and arrays, making them more expressive and
adaptable to real-world data models than traditional rows and columns.

● Schema Flexibility:

MongoDB is schema-less, meaning you don't need to define a rigid structure beforehand. Each
document in a collection can have its own unique structure.

● Scalability:

Supports horizontal scaling via sharding, distributing data across multiple servers or clusters.

Ideal for handling large-scale applications with high throughput and massive datasets.

● High Performance:

Optimized for read and write operations.

Offers in-memory processing and indexing for efficient query execution.

● Built-In Features:

Indexing: Supports a variety of index types for fast data access.

Aggregation Framework: Allows complex data analysis and transformation.


Replication: Provides high availability via replica sets.

Question 71:-How is MongoDB better than other SQL databases?

Answer:- MongoDB, a NoSQL database, differs fundamentally from traditional SQL


databases and offers several advantages depending on the use case. Here's how MongoDB
might be considered better than SQL databases in specific scenarios:

1. Schema Flexibility

MongoDB: Schema-less or schema-flexible. Documents in a collection can have different


structures.Great for applications where data structures evolve over time or vary between
records.

Example: Adding a new field doesn’t require modifying the entire database schema.SQL
Databases: Rigid schemas requiring predefined tables and columns.Schema changes can be
costly and time-consuming in large datasets.

2. Handling Unstructured or Semi-Structured Data

MongoDB: Handles JSON-like documents (BSON), allowing storage of nested data and arrays
directly.Ideal for data that doesn’t fit neatly into rows and columns, like social media profiles
or IoT data.SQL Databases: Require normalization or additional tables to represent complex
relationships, which can make queries more complex.

3. Horizontal Scalability

MongoDB: Supports horizontal scaling through sharding, where data is distributed across
multiple servers.Suitable for applications needing to handle massive amounts of data and high
user traffic.

Example: Large-scale e-commerce or streaming platforms.SQL Databases: Often scale


vertically, which means upgrading to more powerful hardware, a costly and less flexible
approach.

4. Faster Iteration and Development

MongoDB: Flexible data model enables rapid prototyping and faster development
cycles.Especially beneficial for startups or agile teams.SQL Databases: Development might be
slower due to the need to design and maintain rigid schemas upfront.

5. Performance for Write-Heavy Workloads

MongoDB: Optimized for high-volume insert and update operations due to its document model
and ability to process data in parallel.Example: IoT data logging or real-time analytics.

SQL Databases: Write performance can be hindered by complex transactions, constraints, and
normalization requirements.

6. Built for Modern Applications


MongoDB:

Stores geospatial data natively.

Built-in support for unstructured data like images or videos.

JSON-like documents align well with modern web and mobile development.

SQL Databases:

Relational model better suited for structured, predictable data.

7. Simplified Data Representation

MongoDB: Data often represents the application's objects directly, reducing the need for
Object-Relational Mapping (ORM).

Example: A single query retrieves deeply nested objects.

SQL Databases: Often require multiple table joins to reconstruct an object, which can be
computationally expensive.

8. Built-In High Availability

MongoDB: Supports automatic failover and data redundancy via replica sets.

Ensures availability and reliability even in distributed systems.

SQL Databases: High availability often requires additional setup or third-party solutions.

When SQL Databases Are Better:

Despite MongoDB's strengths, SQL databases like MySQL, PostgreSQL, or Oracle still excel
in scenarios requiring:

Complex Transactions: ACID compliance for highly consistent, multi-step operations (e.g.,
banking).

Structured Data: Well-defined and consistent schema requirements.

Reporting and Analytics: SQL’s robust querying and aggregation capabilities with JOINs and
complex relationships.

Question 72:-What are some of the advantages of MongoDB?

Answer:- MongoDB offers several advantages that make it a popular choice for modern
applications. Below are some key benefits:
1. Flexible Data Model

Dynamic Schemas: Unlike SQL databases, MongoDB doesn’t require a predefined schema.
Documents in the same collection can have different structures, making it highly adaptable to
evolving data requirements.

JSON-Like Documents: Data is stored in a BSON (Binary JSON) format, allowing for nested
structures, arrays, and more complex data representations.

2. Scalability

Horizontal Scaling: MongoDB supports sharding, enabling you to distribute data across
multiple servers to handle large-scale datasets and high traffic efficiently.

Elastic Growth: Easily scale up or down based on application needs without significant
architectural changes.

3. High Performance

Optimized Write Operations: MongoDB excels in write-heavy workloads, such as logging or


real-time data processing.

Efficient Reads: Indexing capabilities allow for fast query execution.

In-Memory Storage: Data can be processed in-memory for improved performance.

4. Built for Modern Applications

Real-Time Applications: Suitable for IoT, social media, and real-time analytics due to its
support for fast data ingestion and processing.

Geospatial Features: Native support for geospatial queries makes it ideal for location-based
applications like ride-sharing or delivery services.

5. Ease of Development

Rapid Prototyping: The flexible schema reduces the need for extensive setup, allowing
developers to iterate quickly.

Object-Oriented Data Representation: JSON-like documents closely align with object-oriented


programming paradigms, simplifying application development.

6. Rich Query Language

Powerful Querying: MongoDB supports a wide range of queries, including filtering,


aggregation, and text search.
Aggregation Framework: Enables advanced data processing and transformation directly within
the database.

7. High Availability

Replica Sets: Built-in replication ensures data redundancy and automatic failover in case of
node failure, enhancing reliability.

Distributed Architecture: Designed for cloud environments and high availability.

8. Cost-Effectiveness

Open Source: MongoDB Community Edition is free to use, making it accessible for startups
and small businesses.

Cloud Integration: Managed solutions like MongoDB Atlas reduce operational costs by
handling infrastructure, backups, and scaling.

9. Support for Big Data

MongoDB can handle massive amounts of unstructured or semi-structured data, making it


suitable for big data use cases like social media analytics or machine learning pipelines.

10. Ecosystem and Tools

MongoDB Atlas: A cloud-based managed database service with features like auto-scaling,
backups, and monitoring.

MongoDB Compass: A GUI tool for visualizing and analyzing data.

Driver Support: Offers robust drivers for multiple programming languages, making it easy to
integrate with various tech stacks.

11. Geared Towards Cloud-Native Applications

MongoDB integrates seamlessly with modern cloud platforms, enabling deployment across
distributed systems with minimal overhead.

Question 73:-What are the data types in MongoDB?How do you Delete a Document?

Answer:- Data Types in MongoDB

MongoDB supports a variety of data types, which are stored in BSON (Binary JSON). Below
are the most common MongoDB data types:

String:
Used to store text.

Example: "name": "John"

Integer:

Used for storing whole numbers (32-bit or 64-bit).

Example: "age": 25

Double:

Used for storing floating-point numbers.

Example: "price": 19.99

Boolean:

Used to store true or false.

Example: "isActive": true

Object:

Stores embedded documents (nested objects).

Example:

json

Copy code

"address": { "city": "New York", "zip": "10001" }

Array:

Stores a list of values.


Example:

json

Copy code

"tags": ["electronics", "sale"]

Null:

Used to store a null value.

Example: "description": null

Date:

Stores date and time in ISODate format.

Example: "createdAt": ISODate("2024-12-06T10:00:00Z")

ObjectId:

A unique identifier automatically created for each document.

Example: "_id": ObjectId("64c7f9e0f7894c8d7f7f8a7a")

Binary Data:

Used to store binary data, such as images or files.

Example: "file": BinData(0, "base64encodeddata")

Decimal128:

Used for storing high-precision decimal values.

Example: "balance": Decimal128("12345.67")

MinKey and MaxKey:


Special BSON types used to compare values against the lowest (MinKey) and highest
(MaxKey) values.

Regular Expression:

Used to store regex patterns for matching strings.

Example: "pattern": /abc/i

Timestamp:

Used for storing a timestamp, often for replication and internal MongoDB operations.

Example: "ts": Timestamp(1638390, 1)

How to Delete a Document in MongoDB:-

MongoDB provides methods to delete documents from a collection.

1. Using deleteOne()

Deletes a single document that matches a query.

Example:

db.collectionName.deleteOne({ name: "John" });

This deletes the first document where the name field is "John".

2. Using deleteMany()

Deletes multiple documents that match a query.

Example:

db.collectionName.deleteMany({ status: "inactive" });

This deletes all documents where status is "inactive".

3. Using remove() (Deprecated)


Deletes documents matching a query. Use deleteOne() or deleteMany() instead.

Example:

db.collectionName.remove({ name: "John" });

4. Deleting All Documents in a Collection

Pass an empty query to deleteMany() to remove all documents.

Example:

db.collectionName.deleteMany({});

Question74:-How to perform queries in MongoDB?

Answer:-Querying in MongoDB involves retrieving data from collections using various


criteria. MongoDB queries are executed using methods like find(), findOne(), and aggregation
pipelines. Here's how to perform queries in MongoDB:

Basic Query Methods

1. find():

Retrieves documents that match the specified query criteria. Returns all matching documents.

Example:

db.collectionName.find({ name: "John" });

Retrieves all documents where name is "John".

2. findOne():

Retrieves the first document that matches the query criteria.

Example:

db.collectionName.findOne({ age: 25 });


Retrieves one document where age is 25.

Query Syntax

Queries in MongoDB are JSON-like objects specifying field-value pairs and operators.

1. Match Exact Value:

Example:

db.collectionName.find({ status: "active" });

Retrieves documents where status is "active".

2. Match with Conditions:

Use comparison operators to filter data.

Operators:

$eq: Equal to.

$ne: Not equal to.

$gt: Greater than.

$gte: Greater than or equal to.

$lt: Less than.

$lte: Less than or equal to.

Example:-

db.collectionName.find({ age: { $gte: 18, $lte: 25 } });

Retrieves documents where age is between 18 and 25 (inclusive).

3. Logical Operators:

Combine query criteria with logical operators:


$and: Matches all conditions.

$or: Matches any condition.

$not: Negates a condition.

$nor: Matches documents that fail all conditions.

Example:-

db.collectionName.find({

$or: [{ status: "active" }, { age: { $gt: 30 } }]

});

Retrieves documents where status is "active" or age is greater than 30.

4. Array Queries:

MongoDB provides operators to query arrays.

Match Specific Element:

db.collectionName.find({ tags: "electronics" });

Retrieves documents where tags contains "electronics".

Match Array Length:

db.collectionName.find({ tags: { $size: 3 } });

Retrieves documents where the tags array has exactly 3 elements.

Match Elements in Range:

db.collectionName.find({ scores: { $elemMatch: { $gt: 90, $lt: 100 } } });

Retrieves documents where the scores array has an element between 90 and 100.

Projection

Control which fields to include or exclude in the query result using the second parameter of
find() or findOne().

Example:

db.collectionName.find({ age: { $gte: 18 } }, { name: 1, age: 1 });

Includes only the name and age fields in the result.


Exclude Fields:

db.collectionName.find({}, { password: 0 });

Excludes the password field from the result.

Sorting

Use the sort() method to order results.

Example:

db.collectionName.find().sort({ age: -1 });

Sorts documents in descending order of age.

Pagination

Use skip() and limit() to paginate results.

Example:

db.collectionName.find().skip(10).limit(5);

Skips the first 10 documents and retrieves the next 5.

Aggregation Framework

For complex queries and transformations, use the aggregation pipeline.

Example:

db.collectionName.aggregate([

{ $match: { status: "active" } },

{ $group: { _id: "$age", count: { $sum: 1 } } },

{ $sort: { count: -1 } }

]);
Filters documents with status: "active", groups them by age, counts the occurrences, and sorts
by count.

Text Search

Use text indexes for full-text search.

Example:

db.collectionName.find({ $text: { $search: "laptop" } });

Retrieves documents containing the word "laptop."

Regex Queries

Find documents matching a regular expression.

Example:

db.collectionName.find({ name: /John/i });

Retrieves documents where name contains "John" (case-insensitive).

Question 75:-What is the Mongo Shell?Explain $eq,$ne,$gt,$in and $lt .

Answer:-The Mongo Shell is an interactive command-line interface for MongoDB. It is used


to interact with a MongoDB database instance, allowing users to execute queries, manage
databases and collections, and perform administrative operations. The Mongo Shell is part of
the MongoDB package and is typically accessed using the mongo command.

Key Features of the Mongo Shell:

Interactive Environment:

Write and execute JavaScript code directly.

Test queries and database commands interactively.

Database Management:

Create, update, delete databases and collections.

Insert, update, delete, and query documents.


Built-in JavaScript Engine:

Allows you to use JavaScript for complex operations and scripting.

Administrative Commands:

Perform tasks like creating indexes, managing users, and monitoring database
performance.

Connection to MongoDB Instances:

Connect to standalone instances, replica sets, or sharded clusters.

MongoDB Query Operators Explained

1. $eq (Equal)

Matches documents where the specified field is equal to a given value.

Syntax:

{ field: { $eq: value } }

Example:

db.users.find({ age: { $eq: 25 } });

Retrieves all users with age equal to 25.

2. $ne (Not Equal)

Matches documents where the specified field is not equal to a given value.

Syntax:

{field: { $ne: value } }

Example:

db.users.find({ status: { $ne: "active" } });

Retrieves all documents where status is not "active".

3. $gt (Greater Than)

Matches documents where the specified field is greater than a given value.
Syntax:

{ field: { $gt: value } }

Example:

db.products.find({ price: { $gt: 100 } });

Retrieves all products with a price greater than 100.

4. $lt (Less Than)

Matches documents where the specified field is less than a given value.

Syntax:

{ field: { $lt: value } }

Example:

db.orders.find({ quantity: { $lt: 50 } });

Retrieves all orders with a quantity less than 50.

5. $in (In)

Matches documents where the specified field’s value is in a given array of values.

Syntax:

{ field: { $in: [value1, value2, ...] } }

Example:

db.users.find({ role: { $in: ["admin", "editor"] } });

Retrieves all users whose role is either "admin" or "editor".


Combining Operators

You can combine these operators in a single query using logical operators like $and, $or, etc.

Example:

db.products.find({

$and: [

{ price: { $gt: 50 } },

{ price: { $lt: 200 } }

});

Retrieves products with a price greater than 50 and less than 200.

Question 76:-What are Databases in MongoDB?

Answer:-In MongoDB, a database is a container for collections, which in turn store documents.
Databases in MongoDB are used to logically organize and manage data. Each database is
independent, allowing you to store and operate on different datasets separately.

Key Features of Databases in MongoDB

1. Namespace:
○ Each database has a unique name.
○ Collections within a database are identified by the database name and collection
name, forming a namespace.
2. Multiple Databases:
○ A single MongoDB instance can host multiple databases, enabling you to
segregate data for different applications or purposes.
3. Default Database:
○ MongoDB provides a default database called test. If no database is specified,
test is used.
4. Database Limit:
○ MongoDB doesn't impose a strict limit on the number of databases. Practical
limits depend on system resources.
5. Data Storage:
○ Each database is stored in its own set of files on disk.

Question 77:-What is a Document in MongoDB?Explain InsertOne and InsertMany


command in MongoDB with example.
Answer:-In MongoDB, a document is a basic unit of data that is stored in a collection.
Documents are represented in a JSON-like format called BSON (Binary JSON), which
supports richer data types than JSON, such as dates and binary data.

Key Characteristics of a Document:

1. Field-Value Pairs:
○ Documents consist of key-value pairs (fields and their corresponding data).

Example:
json

"name": "John Doe",

"age": 30,

"isActive": true


2. Dynamic Schema:
○ Documents within the same collection can have different fields or structures.

Example:
json

{ "name": "Alice", "age": 25 }

{ "name": "Bob", "skills": ["JavaScript", "MongoDB"] }


3. Nested Structures:
○ Documents can contain embedded documents and arrays.

Example:
json

"name": "John",

"address": { "city": "New York", "zip": "10001" },

"hobbies": ["reading", "coding"]


}


4. Unique Identifier:
○ Each document has a unique _id field automatically generated unless specified
manually.

Insert Commands in MongoDB

MongoDB provides commands to insert documents into a collection. These are insertOne and
insertMany.

1. insertOne Command

The insertOne method is used to insert a single document into a collection.

Syntax:
javascript

db.collectionName.insertOne(document)

Example:
javascript

db.users.insertOne({

name: "John Doe",

age: 30,

isActive: true

});


○ Inserts the document into the users collection.

Output:
json

"acknowledged": true,

"insertedId": ObjectId("64c7f9e0f7894c8d7f7f8a7a")

}

2. insertMany Command

The insertMany method is used to insert multiple documents into a collection at once.

Syntax:
javascript
db.collectionName.insertMany([document1, document2, ...])

Example:
javascript

db.users.insertMany([

{ name: "Alice", age: 25, isActive: true },

{ name: "Bob", age: 28, isActive: false },

{ name: "Charlie", age: 35, isActive: true }

]);


○ Inserts three documents into the users collection.

Output:
json
{

"acknowledged": true,

"insertedIds": {

"0": ObjectId("64c7f9e0f7894c8d7f7f8a7a"),

"1": ObjectId("64c7f9e0f7894c8d7f7f8a7b"),

"2": ObjectId("64c7f9e0f7894c8d7f7f8a7c")


Key Points for insertOne and insertMany

1. Atomicity:
○ insertOne: Operation is always atomic (affects only one document).
○ insertMany: The operation is atomic only if ordered is set to true (default
behavior). If one document insertion fails, the entire operation is aborted.
2. Ordered vs. Unordered Insertion:
○ By default, insertMany inserts documents in the order provided (ordered: true).
○ To allow the operation to continue even if some insertions fail, set ordered:
false.

Example:

db.users.insertMany([

{ name: "David", age: 40 },

{ _id: 1, name: "Emma", age: 30 }, // Explicit _id

{ _id: 1, name: "Lucas", age: 25 } // Duplicate _id

], { ordered: false });


■ In this case, the second document will succeed, but the third document
(duplicate _id) will fail without stopping the operation.

Question 78:-What is a Collection in MongoDB?Explain updateOne and updateMany


command in monodb.

Answer:-In MongoDB, a collection is a group of documents stored within a database.


Collections are similar to tables in relational databases, but unlike tables, collections do not
enforce a schema, meaning the documents within a collection can have different fields and data
types. A collection can contain documents of any structure, and MongoDB allows flexible,
schema-less storage.

Key Characteristics of a Collection:

1. No Schema:
○ Collections in MongoDB do not enforce a fixed schema, allowing you to store
documents with varying fields.
2. Named Group of Documents:
○ Each collection has a unique name within the database.
3. Dynamic Structure:
○ Documents within the same collection can have different fields and data types.
4. Automatic Creation:
○ Collections are created automatically when you insert the first document into
them.
5. Indexes:
○ Collections can have indexes to speed up queries, including primary indexes on
the _id field (which is automatically indexed by default).

Update Operations in MongoDB:

MongoDB provides two primary methods for updating documents: updateOne() and
updateMany(). These methods allow you to modify existing documents in a collection.

1. updateOne() Command

The updateOne() method is used to update a single document that matches the specified filter
criteria. If multiple documents match, only the first matching document will be updated.

Syntax:
javascript

db.collection.updateOne(

{ filter }, // The filter query to identify the document

{ update }, // The update operation to perform

{ options } // (Optional) Options for the update

Example: Update a single document where the name is "John" to set the age to 35.
javascript

db.users.updateOne(

{ name: "John" }, // Filter: find the document with name "John"

{ $set: { age: 35 } } // Update: set age to 35

);


○ The above command will update only the first document where name is "John".
● Options:
○ $set: Modifies the value of a field.
○ $inc: Increments the value of a field.
○ $unset: Removes a field.

Output:
json
{

"acknowledged": true,

"matchedCount": 1,

"modifiedCount": 1


○ matchedCount: Number of documents that matched the filter.
○ modifiedCount: Number of documents actually modified.

2. updateMany() Command

The updateMany() method is used to update all documents that match the specified filter
criteria. It is useful when you want to apply the same update to multiple documents at once.

Syntax:
javascript

db.collection.updateMany(

{ filter }, // The filter query to identify the documents

{ update }, // The update operation to perform

{ options } // (Optional) Options for the update

Example: Update all documents where the status is "inactive" to set the isActive field to true.
javascript

db.users.updateMany(

{ status: "inactive" }, // Filter: find all documents where status is "inactive"

{ $set: { isActive: true } } // Update: set isActive to true

);


○ This command will update all documents in the users collection where status is
"inactive", setting the isActive field to true.
● Options:
○ $set: Modifies the value of a field.
○ $inc: Increments the value of a field.
○ $mul: Multiplies the value of a field.
○ $push: Adds elements to an array.
○ $unset: Removes a field.

Output:
json

"acknowledged": true,

"matchedCount": 3,

"modifiedCount": 3


○ matchedCount: Number of documents that matched the filter.
○ modifiedCount: Number of documents actually modified.

Update Operations Example (Both updateOne and updateMany)

1. Using updateOne():
○ Scenario: You want to update a single user's age where the name is "Alice".

javascript

db.users.updateOne(

{ name: "Alice" },

{ $set: { age: 28 } }

);

2.
3. Using updateMany():
○ Scenario: You want to update the status of all users who are "inactive" to
"active".

javascript

db.users.updateMany(
{ status: "inactive" },

{ $set: { status: "active" } }

);

4.

Key Differences Between updateOne() and updateMany()

1. updateOne():
○ Updates only the first matching document.
○ Useful when you want to update a specific document or just the first match.
2. updateMany():
○ Updates all matching documents.
○ Useful when you want to apply the same update across multiple documents.

Additional Update Modifiers:

$set: Sets the value of a field. If the field doesn't exist, it will be created.
javascript

db.users.updateOne(

{ name: "John" },

{ $set: { age: 40 } }

);

$inc: Increments a field by a specified value.


javascript
db.users.updateOne(

{ name: "John" },

{ $inc: { age: 1 } }

);

$push: Adds an element to an array.


javascript
db.users.updateOne(

{ name: "Alice" },

{ $push: { hobbies: "swimming" } }

);

$unset: Removes a field from a document.


javascript

db.users.updateOne(

{ name: "Alice" },

{ $unset: { age: "" } }

);

Question 79:-Explain Logical operator with example in MongoDB.

Answer:-In MongoDB, logical operators are used to combine multiple conditions in a query,
allowing you to perform more complex searches. These operators are used with the $and, $or,
$not, and $nor conditions to combine multiple query expressions.

Key Logical Operators in MongoDB

1. $and:
○ The $and operator is used to match documents that satisfy all the conditions
provided in the query.
○ Multiple conditions must all be true for the document to be a match.

Syntax:
javascript
Copy code
{ $and: [{ condition1 }, { condition2 }] }

Example: Retrieve documents from the users collection where age is greater than 25 and status
is "active":
javascript
Copy code
db.users.find({
$and: [

{ age: { $gt: 25 } },

{ status: "active" }

});


■ This will match documents where both conditions are true: age > 25 and
status is "active".
2. $or:
○ The $or operator is used to match documents that satisfy at least one of the
conditions provided in the query.
○ Any one of the conditions must be true for the document to be a match.

Syntax:
javascript
Copy code
{ $or: [{ condition1 }, { condition2 }] }

Example: Retrieve documents from the users collection where age is less than 18 or status is
"inactive":
javascript
Copy code
db.users.find({

$or: [

{ age: { $lt: 18 } },

{ status: "inactive" }

});


■ This will match documents where either age < 18 or status is "inactive".
3. $not:
○ The $not operator is used to negate a condition. It matches documents that do
not satisfy the given condition.

Syntax:
javascript
Copy code
{ field: { $not: condition } }

Example: Retrieve documents from the users collection where the age is not equal to 30:
javascript
Copy code
db.users.find({

age: { $not: { $eq: 30 } }

});


■ This will match all documents where age is not equal to 30.
4. $nor:
○ The $nor operator is used to match documents where none of the specified
conditions are true.
○ It combines conditions similar to $or, but negates the result.

Syntax:
javascript
Copy code
{ $nor: [{ condition1 }, { condition2 }] }

Example: Retrieve documents from the users collection where age is not greater than 40 and
status is not "inactive":
javascript
Copy code
db.users.find({

$nor: [

{ age: { $gt: 40 } },

{ status: "inactive" }

});


■ This will match documents where neither age > 40 nor status is
"inactive".

Question:- 80 What are NoSQL databases? What are the different types of NoSQL
databases?
Answer:-NoSQL (Not Only SQL) databases are a type of database that provide a mechanism
for storing and retrieving data in ways other than the traditional relational database model
(SQL). Unlike relational databases, which use structured query language (SQL) and a fixed
schema, NoSQL databases are designed to be flexible, scalable, and suitable for large,
distributed data storage, especially in environments with big data and high-velocity,
unstructured data.

NoSQL databases are popular for applications that require high availability, horizontal scaling,
and the ability to handle a variety of data types like documents, key-value pairs, graphs, and
wide-column stores.

Key Features of NoSQL Databases:

1. Schema-less Design:
○ NoSQL databases do not require a predefined schema. This allows flexibility in
storing data with different structures.
2. Horizontal Scalability:
○ NoSQL databases are often designed to scale out by adding more servers
(nodes) to the system, enabling them to handle larger loads and data volumes
effectively.
3. High Availability and Fault Tolerance:
○ Many NoSQL databases are built to be distributed and replicated across multiple
servers or data centers, ensuring high availability and fault tolerance.
4. Flexible Data Models:
○ NoSQL databases support a variety of data models, such as key-value pairs,
documents, graphs, and column-family stores.
5. Unstructured or Semi-structured Data:
○ NoSQL databases can handle unstructured or semi-structured data, which is not
easily accommodated by traditional relational databases.

Different Types of NoSQL Databases

NoSQL databases are broadly categorized based on their data model. Here are the most
common types:

1. Key-Value Stores
○ Description: The simplest form of NoSQL databases. Data is stored as key-
value pairs, where the key is a unique identifier and the value can be a string,
number, or more complex data structure.
○ Use Case: Suitable for scenarios requiring high-speed data retrieval, such as
caching, session management, and user profile storage.
○ Examples:
■ Redis: An in-memory key-value store, often used for caching and real-
time applications.
■ Riak: A distributed key-value store designed for high availability and
fault tolerance.
Example:
json
Copy code
{

"user_id_123": { "name": "Alice", "age": 30, "city": "New York" }


2. Document Stores
○ Description: Data is stored as documents, typically in JSON or BSON format.
These documents can contain nested structures, arrays, and fields with different
data types. Document stores are highly flexible and allow for semi-structured
data.
○ Use Case: Ideal for content management systems, user data storage, and
applications with dynamic data structures.
○ Examples:
■ MongoDB: A popular document-based NoSQL database that uses
BSON (binary JSON) to store documents.
■ CouchDB: A document-based database that uses JSON for storing data
and supports HTTP-based APIs.

Example:
json
Copy code
{

"user_id": "123",

"name": "Alice",

"age": 30,

"address": { "city": "New York", "zip": "10001" }


3. Column-Family Stores
○ Description: Data is stored in columns rather than rows, which is the traditional
way in relational databases. Each column can store a large number of values,
and columns can be grouped into column families for better performance.
○ Use Case: Suitable for analytics applications, real-time data processing, and
applications that require fast read/write operations on large datasets.
○ Examples:
■ Apache Cassandra: A highly scalable, distributed column-family store
designed for handling large amounts of data across many commodity
servers.
■ HBase: A column-family store built on top of Hadoop, designed for
handling large amounts of sparse data.

Example:
vbnet
Copy code
Column Family: user_profile

Row Key: user_123

Column1: "name: Alice"

Column2: "age: 30"

Column3: "city: New York"


4. Graph Databases
○ Description: Data is represented as nodes (entities) and edges (relationships)
between them. Graph databases excel at handling relationships and are
commonly used in applications like social networks, recommendation engines,
and fraud detection.
○ Use Case: Suitable for applications that require complex queries about
relationships, such as social networking, fraud detection, and route
optimization.
○ Examples:
■ Neo4j: One of the most popular graph databases, known for its powerful
querying capabilities using the Cypher query language.
■ ArangoDB: A multi-model database that supports graph, document, and
key-value data models.
○ Example:

A graph of social connections:


scss
Copy code
(Alice) --[friend]--> (Bob)

(Bob) --[friend]--> (Charlie)


5. Search Engines
○ Description: Though not always considered a traditional NoSQL database,
search engines like Elasticsearch store and index large amounts of unstructured
text data and provide fast search capabilities.
○ Use Case: Commonly used for full-text search, log analysis, and analytics
applications.
○ Examples:
■ Elasticsearch: A distributed search and analytics engine based on
Apache Lucene.
■ Solr: Another search platform built on top of Apache Lucene.
○ Example:
■ Indexing documents with full-text search capabilities.
UNIT-5
Q.81 what is difference between Get and Post method?
In Java, when dealing with web applications, the GET and POST methods are used to send data
from the client (browser) to the server. Here's a breakdown of their differences:
GET method:

● Data transmission:
Data is appended to the URL as query parameters
(e.g., https://www.example.com/search?q=java).

● Visibility:
Data is visible in the URL, which can be problematic for sensitive information.

● Data limit:
Limited amount of data can be sent due to URL length restrictions.

● Caching:
GET requests can be cached by the browser, which can improve performance but can lead to
stale data.

● Use cases:
Retrieving data from the server, such as loading a webpage or performing a search.

POST method:

● Data transmission: Data is sent in the body of the request, hidden from the user.

● Security: More secure than GET as data is not visible in the URL.

● Data limit: No limit on the amount of data that can be sent.

● Caching: POST requests are not cached by default, ensuring that data is always fresh.

● Use cases: Submitting data to the server for processing, such as creating a new user account or
submitting a form.

Q.82 Difference between forward () method and sendRedirect () method?


As we learned in the previous topics, Servlets are the Java programs that run on the server-side
and generate dynamic responses to the client request. The execution of the Servlet involves the
following steps:

● The client sends the request through the browser to the Web server/Application Server.
● The server passes the client request to the respective servlet.
● Servlet processes the request generates the response and sends the response back to the server.
● The server passes the generated response to the browser/client.
● We can achieve this in 2 ways, servlet provides
● forward() method in RequestDispatcher.

RequestDispatcher Interface
● Servlets provide RequestDispatcher in javax.servlet package. It defines an object to
dispatch the client request from one servlet to another servlet on the same server. Basically,
this can be used to receive the client request object and send that object to any other
resource such as Servlet, JSP, HTML file, etc. We can get the RequestDispatcher object
using the below
Syntax:

RequestDispatcher r = req.getRequestDispatcher(String arg);


forward() method
This method forwards a request from a servlet to another servlet on the same server. It allows one
servlet to do the initial processing of a request, obtains the RequestDispatcher object, and forwards
the request to another servlet to generate the response.

Syntax of forward ():

r.forward(req, resp);

endRedirect() method
It sends a temporary redirect response to the client using the specified redirect location URL given
in the method and clears the buffer. Let’s consider a scenario, where we need to redirect the request
from a servlet to other servlets which is in another server, in this case, we can use the
sendRedirect() method so that the client/browser knows where the request is going and getting
processed.

Syntax to use sendRedirect():


resp.sendRedirect(java.lang.String location)
Q.83 What are the advantages of Servlet over CGI?

Java servlets have several advantages over CGI, including:

● Speed: Servlets are faster than CGI scripts because they use a different process model.

● Efficiency: Servlets use lightweight Java threads to handle requests, while CGI uses
heavyweight operating system processes.

● Ease of use: Servlets are more user-friendly than CGI.

● Portability: Servlets are portable because they use the Java language.

● Robustness: Servlets are managed by the JVM, so there's no need to worry about memory leaks
or garbage collection.

● Security: Servlets are secure because they use the Java language.

● Platform independence: Servlets are platform independent and easy to develop.

● Access to Java APIs: Servlets can access the large set of APIs available for the Java platform.

● Data sharing: Servlets can share data between requests.


Servlets are Java programs that run on web servers to extend their capabilities. They can respond
to any type of request, but are commonly used to extend web server applications

Q.84 Discuss the implicit objects available to JSP page.

The nine implicit objects available to a JavaServer Pages (JSP) page are:

request, response, pageContext, session, application, out, config, page, and exception.

S.No. Object & Description

request
1
This is the HttpServletRequest object associated with the request.
response
2 This is the HttpServletResponse object associated with the response to the
client.

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.

application
5
This is the ServletContext object associated with the application context.

config
6
This is the ServletConfig object associated with the page.

pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.

page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.

Exception
9 The Exception object allows the exception data to be accessed by designated
JSP.

Q.85 Explain the architecture and lifecycle of a JavaServer Page (JSP) within a web
application.
A JavaServer Page (JSP) is a collection of technologies that helps developers create dynamic web
pages using the Java programming language. The architecture and lifecycle of a JSP are as
follows:
A JavaServer Page (JSP) is a collection of technologies that helps developers create dynamic web
pages using the Java programming language. The architecture and lifecycle of a JSP are as
follows:
Lifecycle
The lifecycle of a JSP begins when a client requests the page. The steps in the lifecycle are:
1. The web container receives the request for a JSP

2. The JSP engine compiles the JSP page into a servlet

3. The web server executes the servlet

4. The servlet generates HTML output, which is sent back to the client

5. The page is cached for faster access the next time it is requested
JSP has several advantages, including:

● Less coding: Custom tags reduce the amount of code required, making coding more flexible

● Fast development: No need to recompile or redeploy the project when modifying a JSP page

● Easy integration: Supports Java APIs, which can be easily integrated with HTML code

Q.86 Write a short note on tomcat server.


Tomcat is an open-source web server and servlet. The Apache Software Foundation has developed
it. It is used widely for hosting Java-based applications on the web. It is built on Java technologies
and implements the Java Servlet and JavaServer Pages (JSP) specifications. Tomcat acts as a
bridge between web servers and Java-based applications, facilitating the execution of dynamic
content and processing client requests.

Tomcat offers a lightweight and efficient solution for hosting Java web applications. Tomcat is
popular for several reasons. Its scalability is admired by many. Tomcat's robustness is useful. It
has great community support which brings relief to the users. With its modular architecture and
adherence to industry standards, Tomcat enables developers to build and deploy web applications
with ease.
Q.87 Explain types of Cookies with example.

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

There are 2 types of cookies in servlets.

1. Non-persistent cookie

2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

Simple example of Servlet Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in another
servlet. As we know well that session corresponds to the particular user. So if you access it from
too many browsers with different values, you will get the different value.
Q.88 Discuss the different types of standard action tags used in JSP.
There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp
action tags are given below.

JSP Action Tags Description

forwards the request and response to


jsp:forward
another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty
prints the value of property of the bean.

embeds another components such as


jsp:plugin
applet.

sets the parameter value. It is used in


jsp:param
forward and include mostly.
can be used to print the message if plugin
jsp:fallback
is working. It is used in jsp:plugin.

Q.89 Define the advantages of servlet over CGI? Explain with an example
1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets can run on any
Servlet enabled web server. For example if you develop an web application in windows machine
running Java web server, you can easily run the same on apache web server (if Apache Serve is
installed) without modification or compilation of code. Platform independency of servlets provide
a great advantages over alternatives of servlets.

2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very
fast. These are due to the way servlets run on web server. For any program initialization takes
significant amount of time. But in case of servlets initialization takes place first time it receives a
request and remains in memory till times out or server shut downs. After servlet is loaded, to
handle a new request it simply creates a new thread and runs service method of servlet. In
comparison to traditional CGI scripts which creates a new process to serve the request.

3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented language
which can be extended or polymorphed into new objects. So the java servlets take all these
advantages and can be extended from existing class to provide the ideal solutions.

4. Safety

Java provides very good safety features like memory management, exception handling etc.
Servlets inherits all these features and emerged as a very powerful web server extension.

5. Secure
Servlets are server side components, so it inherits the security provided by the web server. Servlets
are also benefited with Java Security Manager.
Q.90 Illustrate why the session is required in web applications. Mention all the session
tracking techniques in servlet with their pros and cons. Also give example of each.

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to maintain
the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the figure
given below:

Session Tracking Techniques


There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Q.91 Describe Servlet. Explain types of Servlet. Give an example of


HttpServlet. Write steps to execute the servlet.

Here are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:


1. By implementing Servlet interface,

2. By inheriting GenericServlet class, (or)

3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure

2. Create a Servlet

3. Compile the Servlet

4. Create a deployment descriptor

5. Start the server and deploy the project

6. Access the servlet

1)Create a directory structures

The directory structure defines that where to put the different types of files so that web container
may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see
the directory structure that must be followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The web.xml file must be
under the WEB-INF folder.

2)Create a Servlet

There are three ways to create the servlet.

1. By implementing the Servlet interface

2. By inheriting the GenericServlet class

3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to
handle http requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this
example, we are inheriting the HttpServlet class and providing the implementation of the
doGet() method. Notice that get request is the default request.

3)Compile the servlet


For compiling the Servlet, jar file is required to be loaded. Different Servers provide
different jar files:

Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar
Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

Two ways to load the jar file


1. set classpath
2. paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.
4)Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information about
the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many
xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.
5)Start the Server and deploy the project
To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.
One Time Configuration for Apache Tomcat Server
You need to perform 2 tasks:
1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).
2. Change the port number of tomcat (optional). It is required if another server is running on
same port (8080).
6) How to access the servlet
Open browser and write http://hostname:portno/contextroot/urlpatternofservlet.
Q.92 what are Java Server Pages? Explain life cycle of a JSP page? How JSP
are better than Servlets?
A Java Server Page life cycle is defined as the process that started with its creation which later
translated to a servlet and afterward servlet lifecycle comes into play. This is how the process goes
on until its destruction.

Following steps are involved in the JSP life cycle:

1. Translation of JSP page to Servlet


2. Compilation of JSP page(Compilation of JSP into test.java)
3. Classloading (test.java to test.class)
4. Instantiation(Object of the generated Servlet is created)
5. Initialization(jspInit() method is invoked by the container)
6. Request processing(_jspService()is invoked by the container)
7. JSP Cleanup (jspDestroy() method is invoked by the container)
Translation of JSP page to Servlet:
This is the first step of the JSP life cycle. This translation phase deals with the Syntactic correctness
of JSP. Here test.jsp file is translated to test.java.

1. Compilation of JSP page: Here the generated java servlet file (test.java) is compiled to a class
file (test.class).
2. Classloading: The classloader loads the Java class file into the memory. The loaded Java class
can then be used to serve incoming requests for the JSP page.
3. Instantiation: Here an instance of the class is generated. The container manages one or more
instances by providing responses to requests.
4. Initialization: jspInit() method is called only once during the life cycle immediately after the
generation of the Servlet instance from JSP.
5. Request processing: _jspService() method is used to serve the raised requests by JSP. It takes
request and response objects as parameters. This method cannot be overridden.
6. JSP Cleanup: In order to remove the JSP from the use by the container or to destroy the
method for servlets jspDestroy()method is used. This method is called once, if you need to
perform any cleanup task like closing open files, or releasing database connections
jspDestroy() can be overridden.

Q.93 Explain implicit objects available in jsp with example?


These Objects are the Java objects that the JSP Container makes available to the developers in
each page and the developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.

S.No. Object & Description

request
1
This is the HttpServletRequest object associated with the request.

response
2 This is the HttpServletResponse object associated with the response
to the client.

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.

application
5 This is the ServletContext object associated with the application
context.

config
6
This is the ServletConfig object associated with the page.
pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.

page
8 This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.

Exception
9 The Exception object allows the exception data to be accessed by
designated JSP.

Example of session implicit object


index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>

Q.94 What are JSP directives? Explain various types of directives with
example?
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
● page directive
● include directive
● taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
Attributes of JSP page directive
● import
● contentType
● extends
● info
● buffer

1) Import
The import attribute is used to import class,interface or all the members of a package.It is similar
to import keyword in java class or interface.
Example of import attribute
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".
3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The
default size of the buffer is 8Kb.

Q.95 What are standard actions in JSP? Illustrate with example


There are many JSP action tags or elements. Each JSP action tag is used to perform some specific
tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below
Action elements are basically predefined functions. The following table lists out the available
JSP actions −

S.No. Syntax & Purpose

jsp:include
1
Includes a file at the time the page is requested.

jsp:useBean
2
Finds or instantiates a JavaBean.

jsp:setProperty
3
Sets the property of a JavaBean.

jsp:getProperty
4
Inserts the property of a JavaBean into the output.

jsp:forward
5
Forwards the requester to a new page.

jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin.

7 jsp:element
Defines XML elements dynamically.

jsp:attribute
8
Defines dynamically-defined XML element's attribute.

jsp:body
9
Defines dynamically-defined XML element's body.

jsp:text
10
Used to write template text in JSP pages and documents.

Q.96 Explain the Life cycle of servlet?


Servlet Life Cycle can be described as a series of steps that a servlet goes through during its life
span from loading to destruction.
The Servlet Life Cycle is as follows:
Servlet class is loaded first when the Web container receives a new request.
Then, the web container creates a servlet instance. This instance is created only once in the entire
Servlet Life Cycle.
The servlet is initialized using the init() method.
the servlet calls service() method to process the client's request.
The server is destroyed using the destroy() method.
Java Virtual Machine's(JVM) garbage collector clears the destroyed servlet's memory.
Let us see the signature for each of the methods mentioned above:

init()

Whenever a user invokes the URL associated with the particular servlet, the init() method is
called. It is called only once, not each time a request is made. An instance of a servlet is created
through the init() method. Each user request creates a new thread catering to GET and POST
requests.

public void init(ServletConfig config) throws ServletException{

//initialization code
}

service()

The web container calls the service() method each time there is a new request to the servlet. This
is done by spawning a new thread. This method checks the HTTP request type, i.e, whether it is a
GET, POST, DELETE, etc, and calls the doGet, doPost, doDelete, etc methods as per the
request.

public void service(ServletRequest request, ServletResponse response) throws ServletException,


IOException{

//doGet, doPost, doDelete etc as per request

destroy()

This method is called just once at the end of the Life Cycle of Servlet. It helps perform all the
clean-up activities, including closing database connections and halting background threads.
Then, the servlet is removed from the container.

public void destroy (){

//clean-up code

Architecture Diagram of the Servlet Life Cycle in Java

The following represents the Servlet Life Cycle. When a request is sent for a particular web page,
the corresponding servlet must be initialized. The servlet container/web container will load the
servlet and create an instance of it through init().

Subsequent requests to the same web page will invoke the service() method. This method will
typecast the ServletRequest and ServletResponse objects to HttpServletRequest and
HttpServletResponse objects, respectively. Servlets can handle multiple requests concurrently
since each request results in a new thread.
The destroy() method is only called once all threads within the servlet's service methods have
exited or after a timeout period.

Q.97 what are java Beans? Why they are used? Write a JSP page and use an
existing java bean in JSP page by using the standard action. Write the program
with describing the output?
A JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans API specifications.

Following are the unique characteristics that distinguish a JavaBean from other Java classes −

● It provides a default, no-argument constructor.

● It should be serializable and that which can implement the Serializable interface.

● It may have a number of properties which can be read or written.


● It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.

A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −

S.No. Method & Description

getPropertyName()
1 For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.

setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute
will have only a setPropertyName() method.
Example
Consider a student class with few properties –

public class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;

public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}

Q.98 Discuss the role of the HttpServletRequest and HttpServletResponse


interfaces in servlet programming.
The HttpServletRequest and HttpServletResponse interfaces are used in servlet programming to
read and write data from and to HTTP requests and responses, respectively:

HttpServletRequest

Allows servlets to read data from HTTP requests, including request headers and form data. The
servlet container creates an HttpServletRequest object and passes it to the servlet's service
methods.

HttpServletResponse

Allows servlets to write data to HTTP responses, including response headers and the response
message body.
Here are some methods available in the HttpServletRequest interface:

getDateHeader

Returns the value of a specified request header as a long value that represents a Date object

getCookies
Returns an array containing all of the Cookie objects the client sent with this request

getSession

Returns the current session associated with this request, or creates one if there isn't one
An HTTP servlet is a type of servlet that handles HTTP requests and provides HTTP responses,
usually as HTML page

Q.99 Discuss the compilation process of JSP files into servlets and how they
are executed by the servlet container.
A JSP container is an entity that translates, executes, and processes JSP pages and delivers requests
to them.

The exact make-up of a JSP container varies from implementation to implementation, but it will
consist of a servlet or collection of servlets. The JSP container, therefore, is executed by a servlet
container. (Servlet containers are summarized in "Servlet Containers".)

A JSP container may be incorporated into a Web server if the Web server is written in Java, or the
container may be otherwise associated with and used by the Web server.

JSP Pages and On-Demand Translation

Presuming the typical on-demand translation scenario, a JSP page is usually executed through the
following steps:

1. The user requests the JSP page through a URL ending with a .jsp file name.

2. Upon noting the .jsp file name extension in the URL, the servlet container of the Web
server invokes the JSP container.

3. The JSP container locates the JSP page and translates it if this is the first time it has been
requested. Translation includes producing servlet code in a .java file and then compiling
the .java file to produce a servlet .class file.

The servlet class generated by the JSP translator subclasses a class (provided by the JSP
container) that implements the javax.servlet.jsp.HttpJspPage interface (described
in "Standard JSP Interfaces and Methods"). The servlet class is referred to as the page
implementation class. This document will refer to instances of page implementation classes
as JSP page instances.
Translating a JSP page into a servlet automatically incorporates standard servlet
programming overhead into the generated servlet code, such as implementing
the javax.servlet.jsp.HttpJspPage interface and generating code for its service method.

4. The JSP container triggers instantiation and execution of the page implementation class.

The servlet (JSP page instance) will then process the HTTP request, generate an HTTP
response, and pass the response back to the client.

Q.100 Provide examples of how you can use these interfaces to retrieve
request parameters, set response headers, and send data back to the client.

ServletResponse allows Servlet

● To settle up the content length and mime type of the reply

● Provides an output stream and a Writer


Through ServletResponse, the Servlet can send the reply data. The Subclasses of ServletResponse
provide the Servlet with more protocol-based-specific capabilities. For example, up
ServletResponse can contain methods that allow the Servlet to Control the HTTP-specific header
information.

Example of ServletRequest to display the name of the user


We are displaying the name of the user in this servlet, And for this, we have used the getParameter
method that returns the value for the given request parameter name. We have the use of Servlet –
Request Interface in it And When we use it within this example and running will successfully
establish the method.
newindex.html

<form action="welcome User" method="get">

Enter your name<input type="text" name="Name"><br>

<input type="Submit" value="Login">


</form>

MockServer.java
import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class MockServ extends HttpServlet {

public void doGet(HttpServletRequest req,

HttpServletResponse resp)

// Uses throws exception

throws ServletException, IOException

resp.setContentType("text/html");

// sets Content Type

PrintWriter ab = resp.getWriter();

String Name = req.getParameter("Name");

// thiswill return value

ab.println(" Welcome User " + Name);

// this will print the Name Welcome User

ab.close();

}
}

You might also like