Wt Proctor Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 352

“Web Technologies Unveiled:

A Comprehensive Guide”

Shashank singh
Published By: Book Rivers
Website: www.bookrivers.com
Email: publish@bookrivers.com
Mobile: +91-9695375469

1ST Edition: -2023


MRP: /-INR
ISBN:

Copyright©: Shashank singh

All Rights Reserved


No part of this publication may be reproduced, transmitted or stored
in a retrieval system, in any form or by any means, electronic,
mechanical, photocopying recording or otherwise, without the prior
permission of the author.

[PRINTED IN INDIA]

ii
Preface

Welcome to "Web Technologies Unveiled: A Comprehensive


Guide." In the dynamic realm of technology, the web stands as the
cornerstone of innovation, connectivity, and endless possibilities.
As a professor deeply entrenched in the world of computer science
and engineering, it is my pleasure to present this comprehensive
guide, aimed at unraveling the intricacies of web technologies. The
web has evolved from a simple information-sharing platform to a
complex ecosystem that powers our daily lives, businesses, and
communication. This book is a result of years of experience,
research, and a passion for understanding and teaching the intricate
web technologies that shape our digital landscape.
In this book, we embark on a journey through the vast landscape of
web technologies, exploring everything from the fundamental
building blocks to the latest advancements. Whether you are a
student, a professional in the field, or someone simply curious about
the inner workings of the web, this guide is designed to be your
companion.
Key Features of This Book
• Comprehensive Coverage: We delve into the core
components of web technologies, providing a thorough
understanding of java, HTML, CSS, JavaScript, and more.
Explore the nuances of web development and gain insights
into the latest trends and frameworks.
• Practical Insights: This guide goes beyond theoretical
concepts, offering practical insights and examples that bridge
the gap between knowledge and application. Learn how to
build responsive and user-friendly web applications through
hands-on exercises.
• Emerging Trends: The web is ever-evolving, and staying
abreast of emerging trends is crucial. Discover the latest
developments in web technologies, including progressive web
iii
apps, web components, and the impact of artificial intelligence
on the web.
• Security Considerations: Security is paramount in the digital
age. We dedicate a section to the principles of web security,
helping you understand and implement measures to safeguard
web applications and user data.
Dr. Shashank Singh

iv
DEDICATION

To my beloved grandfather, whose unwavering support, wisdom,


and gentle encouragement have been a guiding light throughout my
academic journey? Your stories, shared under the starlit sky,
sparked my curiosity and passion for the world of technology. This
book is a tribute to the values you instilled in me and the enduring
love that continues to inspire every page.
Dr. Shashank Singh

v
CHAPTERS

Chapter 1. Introduction to Web Development


Strategies, Core Java
1. History of web and Internet, Protocols
Governing web.
2. Writing Web Projects, connecting to
Internet.
3. Introduction to Internet services and tools,
Introduction client–server computing.
4. Core Java: Introduction, Operator, Data
types, Variables, Arrays.
5. Core Java: Methods &classes, Inheritances,
Package and Interface.
6. Core Java: Exception Handling, Multithread
Programming, I/O.
7. Java Applet, String Handling, Event
Handling.
8. Introduction to AWT,AWT controls, Layout
Managers
Chapter 2.WebPage Designing
1. HTML: List, Table, Images, Frames, Forms.
2. CSS(Cascading Style Sheet)
3. XML: DTD, XML schemas, Object Models,
Presenting and Using XML.
4. Using XML Processors: DOM and
SAX,Dynamic HTML
Chapter 3.Java script and Networking
1. Java script: Introduction, Documents, forms,
statements, functions.

vi
2. Java script: objects, Introduction to AJAX
3. Networking: Internet Addressing,
Inetaddress, Factory Methods.
4. Networking: TCP/IP, Client sockets, URL,
URL Connection.
5. Networking: T CP/IP Server sockates,
Datagram.
Chapter 4. Enterprise Java Beans
1. Java Beans : Preparing a Class to be a Java
Beans, Creating a java Beans
2. Java Beans: Java Beans Properties, Types of
beans, Stateful Session beans, Stateless bean,
Entity bean.
3. Java Database Connectivity (JDBC):
Merging Data from Multiple Tables, Joining,
Manipulating.
4. Java Database Connectivity (JDBC):
Database with JDBC, Prepared Statements,
Transaction Processing, Stored Procedures.
Chapter 5. Servlets and Java Server Pages
1. Servlets: Overview and Architecture,
Interface Servlet and the Life Cycle.
Handling HTTP get Requests, Handling
HTTP post Requests.
2. Servlets: Redirecting Request to Other
Resources, Session Tracking, cookies,
Session Tracking with Http Session.
3. Java Server Pages(JSP): Introduction, Java
Server Pages Overview, A First Java Server
Page Example.

vii
4. 4. Java Server Pages (JSP): Implicit Objects,
Scripting Standard Actions, Directives,
Custom Tag Libraries.

viii
Chapter - 1
Introduction to Web Development Strategies,
Core Java

1.1 (a) Introduction to Web Technology:


Web technology encompasses a broad spectrum of tools,
languages, and protocols that facilitate communication, interaction,
and presentation of content on the World Wide Web. Since the
inception of the web in the late 1980s, it has seen monumental
growth, not just in terms of the number of websites and users but
also in the complexity and capabilities of web technologies.
At its core, the web operates on a simple client-server model.
A user, through a web browser (the client), requests information or
resources, which are fetched from a server and then displayed to the
user. This interaction, though simple in its description, is powered
by a suite of technologies working harmoniously behind the scenes.
1. HTML (HyperText Markup Language): This is the standard
markup language used to create web pages. It describes the
structure and content of a web page, defining elements such as
headings, paragraphs, links, and more.
2. CSS (Cascading Style Sheets): While HTML defines the
structure, CSS is used to present the content aesthetically. It
controls the layout, colors, fonts, and overall look of a web page.
3. JavaScript: A scripting language that allows for interactive web
pages. It operates on the client side and can interact with both
HTML and CSS.
4. Protocols: The web operates on several protocols, with the most
fundamental being HTTP (HyperText Transfer Protocol) and
HTTPS (the secure version). These protocols define how
messages are formatted and transmitted, and how servers and
browsers should respond to various commands.

1
5. Web Browsers: Software applications like Chrome, Firefox,
Safari, and Edge that retrieve, render, and display content from
the web.
6. Web Servers: These are specialized computers that store web
resources and use server-side scripting languages like PHP,
Python, or Ruby to process and serve them to clients upon
request.
7. Databases: Systems like MySQL, PostgreSQL, and MongoDB
store structured data, enabling websites to retrieve and display
dynamic content.
8. Frameworks & Libraries: Tools like React, Angular, and
Bootstrap allow developers to build web applications more
efficiently, relying on established code structures and patterns.
9. APIs (Application Programming Interfaces): Enable the
integration of different software tools and platforms, allowing
them to communicate and share data.
10. Web Security: Technologies like SSL/TLS certificates and
protocols ensure the privacy and security of data transmitted
over the web.
11. Web Standards: Established by organizations like the World
Wide Web Consortium (W3C), these standards ensure
consistent and accessible web experiences across various
devices and platforms
1.1(b)Web development strategies:
Web development strategies refer to the comprehensive
approaches and methodologies employed to create successful
websites and web applications. A well-devised web development
strategy ensures that a website or application is user-friendly,
functional, aesthetically pleasing, and meets the objectives of its
creators or stakeholders. Here are some key web development
strategies:

2
1. Requirement Analysis:
• Understand the goals and objectives of the website or
application.
• Identify target audiences and their preferences.
• Analyze competitors and identify unique selling points
(USPs).
2. Responsive Design:
• Ensure the website is accessible and usable across various
devices and screen sizes.
• Implement a mobile-first design, given the increasing
mobile web traffic.
3. Content Strategy:
• Plan and structure content to cater to the target audience.
• Ensure content is relevant, valuable, and optimized for
search engines (SEO-friendly).
4. User Experience (UX) and User Interface (UI) Design:
• Create intuitive navigation structures.
• Design user-friendly interfaces, focusing on aesthetics and
usability.
5. Performance Optimization:
• Minimize server requests.
• Optimize images and other media.
• Implement caching solutions to enhance loading speeds.
6. Search Engine Optimization (SEO):
• Optimize website structure, meta tags, and content for search
engines.
• Implement a strong backlink strategy and focus on organic
growth.
7. Web Accessibility:
• Ensure the website is accessible to users with disabilities.
3
• Comply with standards such as Web Content Accessibility
Guidelines (WCAG).
8. Security Measures:
• Use HTTPS to encrypt data.
• Implement regular backups, firewalls, and other security
measures to safeguard against cyber threats.
9. Feedback Loop:
• Incorporate user feedback systems or analytics tools to
gather insights.
• Regularly update the website or application based on user
feedback and evolving needs.
10. Modular and Scalable Development:
• Adopt a modular approach to code for easier maintenance
and scalability.
• Plan for potential growth or expansion of the website or
application.
• Continuous Integration and Continuous Deployment
(CI/CD):
• Implement CI/CD pipelines for automated testing and
deployment.
• Ensure updates or changes are seamlessly integrated without
disrupting user experience.
12. Social Media and Third-party Integration:
• Integrate with social media platforms for increased
engagement and outreach.
• Incorporate third-party tools or services, if necessary, to
enhance functionality.
13. Post-launch Strategy:
• Monitor website traffic and user behavior.
• Handle maintenance, updates, and troubleshoot any issues.

4
14. Backup and Recovery:
• Ensure regular backups of the website data.
• Establish a recovery plan in case of server failures or data
breaches.
15. Future-proofing:
• Stay updated with the latest web development trends and
technologies.
• Periodically reassess and adapt strategies to meet evolving
needs
1.1 (c) History of internet and web:
History of the Internet:
1. 1960s - The Genesis:
• ARPANET: The foundation of the internet began with
ARPANET (Advanced Research Projects Agency Network) in
1969, commissioned by the U.S. Department of Defense. It
was the first network to implement the packet-switching
method and had its first successful message transfer between
UCLA and Stanford Research Institute.
2. 1970s - Expansion and Protocols:
• TCP/IP: In the late '70s, Vint Cerf and Bob Kahn developed
the Transmission Control Protocol (TCP), which later became
TCP/IP (adding Internet Protocol). Adopted by ARPANET in
1983, TCP/IP became the standard for internet communication
and remains so today.
• The Birth of Email: Ray Tomlinson introduced the use of the
"@" symbol in email addresses in 1971, and electronic mail
took off as a new form of communication.
3. 1980s - Networks and Domains:
• DNS: The Domain Name System (DNS) was introduced in
1983, providing more user-friendly names for numerical IP
addresses.
5
• Expanding Networks: Other networks like BITNET and
USENET emerged, promoting academic and public
communication.
4. 1990s - The Web and Commercialization:
• World Wide Web: In 1991, British physicist Tim Berners-Lee
at CERN introduced the World Wide Web, defining HTML,
HTTP, and web browsers. The first website, "info.cern.ch,"
was launched.
• Browsers: The early '90s saw browsers like Mosaic (which
later influenced Netscape) coming to the fore, popularizing the
web.
• ISP Boom: Commercial Internet Service Providers (ISPs)
began to emerge, granting public access to the internet.
5. 2000s - Modern Internet:
• Broadband: Dial-up connections transitioned to faster
broadband connections, enhancing the internet experience.
• Web 2.0: The interactive web, emphasizing user-generated
content, collaboration, and social networking, became the
norm.
• Mobile Internet: The rise of smartphones and mobile data
revolutionized internet access and use.
6. 2010s - Ubiquity and Beyond:
• IoT: The Internet of Things connected everyday devices to the
internet.
• Cloud Computing: Data storage and processing increasingly
shifted to cloud platforms.
• Focus on Privacy: With data breaches and concerns over data
privacy, there was a heightened focus on cybersecurity and
regulations.

6
History of the Web:
1. 1990s - Birth and Boom:
• First Browser and Server: Tim Berners-Lee developed the first
web browser and server in 1990.
• Rise of Search Engines: Early search engines like AltaVista,
Yahoo!, and later Google, emerged, organizing the vast
information on the web.
• Dot-com Bubble: The late '90s saw a surge in internet-based
companies and startups, culminating in the dot-com bubble of
2000.
2. 2000s - Web 2.0 and Multimedia:
• Interactive Sites: Websites transitioned from static pages to
interactive platforms, with sites like YouTube, Facebook, and
Wikipedia becoming popular.
• Flash: Adobe Flash played a significant role in multimedia
web content, though it later faced decline due to performance
and security issues.
3. 2010s - Mobile Web and Progressive Web Apps:
• Responsive Design: With diverse devices accessing the web,
responsive web design became essential.
• Progressive Web Apps (PWAs): Websites started to emulate
app-like experiences in browsers, bridging the gap between
web and native apps.
4. 2020s and Beyond:
• WebAssembly: A new code format for the web that promises
faster performance for web applications.
• JAMstack: A modern architecture emphasizing decoupling the
frontend from the backend for better performance and security.
1.1(d) Types of Internet Protocols:
Internet Protocols are a set of rules that governs the
communication and exchange of data over the internet. Both the
7
sender and receiver should follow the same protocols in order to
communicate the data. In order to understand it better, let’s take an
example of a language. Any language has its own set of vocabulary
and grammar which we need to know if we want to communicate in
that language. Similarly, over the internet whenever we access a
website or exchange some data with another device then these
processes are governed by a set of rules called the internet protocols.
Working of Internet Protocol
The internet and many other data networks work by organizing
data into small pieces called packets. Each large data sent between
two network devices is divided into smaller packets by the
underlying hardware and software. Each network protocol defines
the rules for how its data packets must be organized in specific ways
according to the protocols the network supports.
Need of Protocols
It may be that the sender and receiver of data are parts of
different networks, located in different parts of the world having
different data transfer rates. So, we need protocols to manage the
flow control of data, and access control of the link being shared in
the communication channel. Suppose there is a sender X who has a
data transmission rate of 10 Mbps. And, there is a receiver Y who
has a data receiving rate of 5Mbps. Since the rate of receiving the
data is slow so some data will be lost during transmission. In order
to avoid this, receiver Y needs to inform sender X about the speed
mismatch so that sender X can adjust its transmission rate. Similarly,
the access control decides the node which will access the link shared
in the communication channel at a particular instant in time. If not
the transmitted data will collide if many computers send data
simultaneously through the same link resulting in the corruption or
loss of data.
1.1(e) IP Addressing:
An IP address represents an Internet Protocol address. A
unique address that identifies the device over the network. It is
8
almost like a set of rules governing the structure of data sent over
the Internet or through a local network. An IP address helps the
Internet to distinguish between different routers, computers, and
websites. It serves as a specific machine identifier in a specific
network and helps to improve visual communication between source
and destination.
Types of Internet Protocol
1. TCP/IP (Transmission Control Protocol/ Internet Protocol)
These are a set of standard rules that allows different types of
computers to communicate with each other. The IP protocol ensures
that each computer that is connected to the Internet is having a
specific serial number called the IP address. TCP specifies how data
is exchanged over the internet and how it should be broken into IP
packets. It also makes sure that the packets have information about
the source of the message data, the destination of the message data,
the sequence in which the message data should be re-assembled, and
checks if the message has been sent correctly to the specific
destination. The TCP is also known as a connection-oriented
protocol.
2. SMTP (Simple Mail Transfer Protocol)
These protocols are important for sending and distributing
outgoing emails. This protocol uses the header of the mail to get the
email id of the receiver and enters the mail into the queue of
outgoing mail. And as soon as it delivers the mail to the receiving
email id, it removes the email from the outgoing list. The message
or the electronic mail may consider the text, video, image, etc. It
helps in setting up some communication server rules.
3. PPP(Point-to-Point Protocol)
It is a communication protocol that is used to create a direct
connection between two communicating devices. This protocol
defines the rules using which two devices will authenticate with
each other and exchange information with each other. For example,
A user connects his PC to the server of an Internet Service Provider
9
and also uses PPP. Similarly, for connecting two routers for direct
communication it uses PPP.
4. FTP (File Transfer Protocol)
This protocol is used for transferring files from one system to
the other. This works on a client-server model. When a machine
requests for file transfer from another machine, the FTO sets up a
connection between the two and authenticates each other using their
ID and Password. And, the desired file transfer takes place between
the machines.
5. SFTP(Secure File Transfer Protocol)
SFTP which is also known as SSH FTP refers to File Transfer
Protocol (FTP) over Secure Shell (SSH) as it encrypts both
commands and data while in transmission. SFTP acts as an
extension to SSH and encrypts files and data then sends them over
a secure shell data stream. This protocol is used to remotely connect
to other systems while executing commands from the command line.
6. HTTP(Hyper Text Transfer Protocol)
This protocol is used to transfer hypertexts over the internet
and it is defined by the www(world wide web) for information
transfer. This protocol defines how the information needs to be
formatted and transmitted. And, it also defines the various actions
the web browsers should take in response to the calls made to access
a particular web page. Whenever a user opens their web browser,
the user will indirectly use HTTP as this is the protocol that is being
used to share text, images, and other multimedia files on the World
Wide Web.
Note: Hypertext refers to the special format of the text that can
contain links to other texts.
7. HTTPS(HyperText Transfer Protocol Secure)
HTTPS is an extension of the Hypertext Transfer Protocol
(HTTP). It is used for secure communication over a computer
network with the SSL/TLS protocol for encryption and
10
authentication. So, generally, a website has an HTTP protocol but if
the website is such that it receives some sensitive information such
as credit card details, debit card details, OTP, etc then it requires an
SSL certificate installed to make the website more secure. So, before
entering any sensitive information on a website, we should check if
the link is HTTPS or not. If it is not HTTPS then it may not be secure
enough to enter sensitive information.
8. TELNET(Terminal Network)
TELNET is a standard TCP/IP protocol used for virtual
terminal service given by ISO. This enables one local machine to
connect with another. The computer which is being connected is
called a remote computer and which is connecting is called the local
computer. TELNET operation lets us display anything being
performed on the remote computer in the local computer. This
operates on the client/server principle. The local computer uses the
telnet client program whereas the remote computer uses the telnet
server program.
9. POP3(Post Office Protocol 3)
POP3 stands for Post Office Protocol version 3. It has two
Message Access Agents (MAAs) where one is client MAA
(Message Access Agent) and another is server MAA(Message
Access Agent) for accessing the messages from the mailbox. This
protocol helps us to retrieve and manage emails from the mailbox
on the receiver mail server to the receiver’s computer. This is
implied between the receiver and the receiver mail server. It can also
be called a one-way client-server protocol. The POP3 WORKS ON
THE 2 PORTS I.E. PORT 110 AND PORT 995.
10. IPv4
The fourth and initially widely used version of the Internet
Protocol is called IPv4 (Internet Protocol version 4). It is the most
popular version of the Internet Protocol and is in charge of
distributing data packets throughout the network. Maximum unique
addresses for IPv4 are 4,294,967,296 (232), which are possible due
11
to the use of 32-bit addresses. The network address and the host
address are the two components of each address. The host address
identifies a particular device within the network, whereas the
network address identifies the network to which the host belongs. In
the “dotted decimal” notation, which is the standard for IPv4
addresses, each octet (8 bits) of the address is represented by its
decimal value and separated by a dot (e.g. 192.168.1.1).
11. IPv6
The most recent version of the Internet Protocol, IPv6, was
created to address the IPv4 protocol’s drawbacks. A maximum of
4.3 billion unique addresses are possible with IPv4’s 32-bit
addresses. Contrarily, IPv6 uses 128-bit addresses, which enable a
significantly greater number of unique addresses. This is significant
because IPv4 addresses were running out and there are an increasing
number of devices that require internet access. Additionally, IPv6
offers enhanced security features like integrated authentication and
encryption as well as better support for mobile devices. IPv6 support
has spread among websites and internet service providers, and it is
anticipated to gradually displace IPv4 as the main internet protocol.
12. ICMP
ICMP (Internet Control Message Protocol) is a network
protocol that is used to send error messages and operational
information about network conditions. It is an integral part of the
Internet Protocol (IP) suite and is used to help diagnose and
troubleshoot issues with network connectivity. ICMP messages are
typically generated by network devices, such as routers, in response
to errors or exceptional conditions encountered in forwarding a
datagram. Some examples of ICMP messages include:
• Echo Request and Echo Reply (ping)
• Destination Unreachable
• Time Exceeded
• Redirect

12
ICMP can also be used by network management tools to test
the reachability of a host and measure the round-trip time for packets
to travel from the source to the destination and back. It should be
noted that ICMP is not a secure protocol, it can be used in some
types of network attacks like DDoS amplification.
13. UDP
UDP (User Datagram Protocol) is a connectionless, unreliable
transport layer protocol. Unlike TCP, it does not establish a reliable
connection between devices before transmitting data, and it does not
guarantee that data packets will be received in the order they were
sent or that they will be received at all. Instead, UDP simply sends
packets of data to a destination without any error checking or flow
control. UDP is typically used for real-time applications such as
streaming video and audio, online gaming, and VoIP (Voice over
Internet Protocol) where a small amount of lost data is acceptable
and low latency is important. UDP is faster than TCP because it has
less overhead. It doesn’t need to establish a connection, so it can
send data packets immediately. It also doesn’t need to wait for
confirmation that the data was received before sending more, so it
can transmit data at a higher rate.
14. IMAP
IMAP (Internet Message Access Protocol) is a protocol used
for retrieving emails from a mail server. It allows users to access and
manage their emails on the server, rather than downloading them to
a local device. This means that the user can access their emails from
multiple devices and the emails will be synced across all devices.
IMAP is more flexible than POP3 (Post Office Protocol version 3)
as it allows users to access and organize their emails on the server,
and also allows multiple users to access the same mailbox.
15. SSH
SSH (Secure Shell) is a protocol used for secure remote login
and other secure network services. It provides a secure and
encrypted way to remotely access and manage servers, network
13
devices, and other computer systems. SSH uses public-key
cryptography to authenticate the user and encrypt the data being
transmitted, making it much more secure than traditional remote
login protocols such as Telnet. SSH also allows for secure file
transfers using the SCP (Secure Copy) and SFTP (Secure File
Transfer Protocol) protocols. It is widely used in Unix-based
operating systems and is also available for Windows. It is commonly
used by system administrators, developers, and other technical users
to remotely access and manage servers and other network devices.
16. Gopher
Gopher is a type of file retrieval protocol that provides
downloadable files with some description for easy management,
retrieving, and searching of files. All the files are arranged on a
remote computer in a stratified manner. It is an old protocol and it
is not much used nowadays.
1.2(a)Writing web projects:
Creating a web project involves several structured steps to ensure
it's successful, functional, and meets the needs of its intended users.
Here are the general steps to follow when developing a web project:
1. Define the Project:
• Objective: Understand the purpose of the website or
application. Is it an e-commerce site, informational blog,
portfolio, or something else?
• Target Audience: Identify and understand the demographics
and preferences of your potential users.
2. Plan and Strategize:
• Site Structure: Outline a sitemap detailing the primary
navigation and hierarchy of the pages.
• Features and Functionalities: List down essential features, such
as contact forms, login systems, or shopping carts.
• Resources: Determine the human, technological, and financial
resources required.
14
3. Design:
• Wireframing: Sketch the basic layout of the site, showing
where elements will be positioned.
• Mockups: Create more detailed designs showcasing colors,
typography, and images.
• Prototyping: Build interactive prototypes to simulate user flow
and interactions.
4. Content Development:
• Copywriting: Write the text content for each page, ensuring
clarity and relevance.
• Media: Source or create images, videos, icons, or any other
media required.
• Optimization: Ensure the content is optimized for search
engines (SEO).
5. Development:
• Frontend Development: Turn designs into functional web
pages using HTML, CSS, and JavaScript.
• Backend Development: Implement server-side functionalities,
database integrations, and set up CMS (if required).
• Integration: Combine frontend and backend elements, ensuring
they work seamlessly.
• Mobile Optimization: Ensure the website is responsive and
works flawlessly on mobile devices.
6. Testing:
• Functionality Testing: Ensure all features work as intended.
• Compatibility Testing: Check the website's performance
across different browsers and devices.
• User Testing: Gather feedback from potential users to identify
pain points or areas of improvement.
• Performance Testing: Test the site's speed and responsiveness,
optimizing where necessary.

15
7. Deployment:
• Hosting: Choose a reliable web hosting provider and set up the
server.
• Domain: Purchase and configure a domain name.
• Launch: Make the website live and accessible to users.
8. Maintenance and Updates:
• Regular Monitoring: Use analytics tools to monitor site
performance, user engagement, and other vital metrics.
• Updates: Keep the site updated with fresh content, security
patches, and technology upgrades.
• Feedback Loop: Continuously gather feedback and make
necessary improvements.
9. Promotion and SEO:
• SEO: Optimize the website for search engines to ensure it ranks
well in search results.
• Social Media: Use platforms like Facebook, Twitter, and
Instagram to promote the website.
• Email Marketing: Engage with users via newsletters and
updates.
10. Review and Iterate:
• Performance Review: Periodically review the site's goals and
performance metrics.
• Iterate: Based on reviews, make necessary adjustments to the
design, content, or functionalities.
1.2(b)Connecting to the internet :
It can be achieved in various ways, depending on the device and the
type of internet service available. Here are the general steps to
connect to the internet:
1. Choose an Internet Service Provider (ISP):
• Research and select an ISP that offers services in your area,
taking into account factors like speed, reliability, and price.
16
2. Get the Necessary Hardware:
• Modem: A device that modulates and demodulates digital
signals, allowing your device to communicate with the wider
internet.
• Router: A device that distributes the internet connection to
multiple devices in your home or office. Some modems come
with built-in routers.
• For mobile devices, you might require a SIM card with data
services.
3. Set Up the Modem:
• Connect the modem to the wall outlet using the appropriate cable
(like a DSL, cable, or fiber-optic line).
• Turn on the modem and let it synchronize with the ISP. This
might involve waiting for certain indicator lights to become
stable.
4. Set Up the Router (if separate from the modem):
• Connect the router to the modem using an Ethernet cable.
• Power on the router and wait for it to start up. Like the modem,
this might require waiting for certain indicator lights.
5. Configure the Network:
• Connect a computer or mobile device to the router. This can be
done wirelessly (via Wi-Fi) or through a wired connection
(using an Ethernet cable).
• Open a web browser and enter the router's IP address (often
"192.168.1.1" or "192.168.0.1", but refer to your router's
manual).
• Log in using the default username and password (usually
"admin" for both, but check the router's manual).
• Set up your Wi-Fi network by choosing a network name (SSID)
and a strong password. Also, ensure the network is secured using
WPA2 or higher encryption.

17
6. Connect Your Devices:
• On your computer, smartphone, or other devices, go to the Wi-
Fi settings.
• Select your network's name (SSID) from the list of available
networks.
• Enter the password you set up earlier.
7. Test the Connection:
• Open a web browser on your device.
• Try visiting a website, such as Google, to confirm the internet
connection is working.
8. Optional Steps:
• Update the router's firmware for improved performance and
security.
• Set up parental controls or guest networks if your router supports
these features.
• Configure additional security settings, like MAC address
filtering or a VPN.
9. Troubleshooting (if required):
• If you can't connect, restart the modem and router.
• Ensure all cables are properly connected.
• Check if there's a larger service outage with your ISP.
• Contact your ISP's customer service for assistance.
1.3(a) Introduction to Internet Services and Tools:
The internet, as we know it, is a vast interconnected network
that enables the exchange of information across the globe. Over the
years, a multitude of services and tools have emerged to harness the
power of this network, making our lives more connected, efficient,
and informed. This introduction will give an overview of some of
the fundamental internet services and tools.
1. World Wide Web (WWW): The WWW, commonly known as
the web, is a vast information system of interlinked hypertext
18
documents accessed via the internet. It uses browsers like
Chrome, Firefox, and Safari to navigate web pages, which are
typically designed using HTML.
2. Email (Electronic Mail): Email allows users to send and
receive electronic messages. With email clients like Gmail,
Outlook, and Yahoo Mail, users can exchange text, images,
attachments, and more with recipients anywhere in the world
instantly.
3. File Transfer Protocol (FTP): FTP is a standard network
protocol used to transfer files from one host to another over the
internet. FTP clients like FileZilla allow users to upload and
download files from web servers.
4. Internet Relay Chat (IRC): IRC is an application layer
protocol that enables communication via text. Through IRC
clients, users can enter chat rooms and have real-time
discussions.
5. Search Engines: Search engines like Google, Bing, and Yahoo
help users find specific information on the web by indexing
billions of web pages and returning relevant results based on
user queries.
6. Social Media Platforms: Websites and applications like
Facebook, Twitter, and Instagram allow users to connect, share,
and communicate in virtual communities and networks.
7. Cloud Services: Platforms like Dropbox, Google Drive, and
Microsoft OneDrive provide storage solutions, allowing users to
save and access their files from any device connected to the
internet.
8. Streaming Services: Platforms like YouTube, Netflix, and
Spotify allow users to stream video and audio content without
needing to download it, providing instant entertainment.
9. E-commerce: Websites like Amazon, eBay, and Alibaba offer
platforms for buying and selling goods and services online.
10. Virtual Private Network (VPN): VPNs are services that create
a secure and encrypted connection over a less secure network,

19
such as the internet. They ensure privacy and protection from
potential eavesdroppers.
11. Internet of Things (IoT): IoT refers to the interconnection of
everyday objects to the internet, enabling them to send and
receive data. Examples include smart thermostats, wearables,
and connected vehicles.
12. Collaboration Tools: Platforms like Zoom, Microsoft Teams,
and Slack have emerged as essential tools for communication
and collaboration, allowing teams to work together regardless of
their physical location.
1.3 (b) Introduction to Client-Server Computing:
Client-server computing is a distributed application structure
that partitions tasks or workloads between servers and clients. This
model has played a foundational role in the digital age, powering the
majority of web, enterprise, and personal applications we use daily.
Let’s delve deeper into the intricacies of client-server computing.
1. Basic Concept:
At its core, client-server computing involves a client (often a
user's device or software) making a request for resources or services,
and a server, which processes this request and returns the desired
data or action. This is analogous to a diner (client) ordering food in
a restaurant, and the kitchen (server) preparing and serving the food.
2. Clients:
• Types: Clients can be thin clients or thick/fat clients. Thin clients
rely heavily on the server for processing, while thick clients
perform substantial processing locally.
• Functions: Clients initiate requests, present data to the user, and
manage local resources like disk storage and peripheral devices.
For instance, a web browser acts as a client when it requests a
webpage from a server.

20
3. Servers:
• Types: There are various types of servers based on their roles,
including web servers, database servers, FTP servers, and mail
servers, among others.
• Functions: Servers wait for and fulfill requests from clients. This
can involve retrieving and sending data, performing
computations, directing network traffic, and more.
4. Communication:
Clients and servers communicate over a network using
protocols. For instance, web browsers and web servers communicate
using the Hypertext Transfer Protocol (HTTP). The data exchanged
between them often follows standard formats like XML or JSON.
5. Advantages of Client-Server Computing:
• Scalability: New resources and systems can be added without
disrupting the user experience or overall performance.
• Centralized Control: Servers can be centrally managed and
updated, ensuring uniformity, reducing redundancy, and
simplifying backup processes.
• Flexibility: Different clients can access a server from anywhere,
provided they can connect to the network. This has been
foundational for the development of web applications and
services.
• Efficiency: By segregating tasks based on where they're most
efficiently handled (client-side or server-side), the model often
results in faster performance and less waste of resources.
• Challenges:
• Single Point of Failure: If a server fails, clients relying on it can
be affected. This has led to strategies like load balancing and
redundant server architectures.
• Security Concerns: With data flow between clients and servers,
there's potential for breaches, especially if data is transmitted
unencrypted or if servers are not adequately protected.

21
• Network Dependency: The model inherently relies on a
network. If the network fails or becomes slow, it can impede the
client-server interaction.
7. Evolution and Future:
While the client-server model remains dominant, it has
evolved. Today's cloud computing often uses a client-server model
but with virtualized and scalable infrastructures. Similarly, peer-to-
peer (P2P) models, where devices act as both clients and servers,
have gained traction in specific applications like file sharing
1.4(a) Introduction of java:
Java is a programming language and a platform. Java is a high
level, robust, object-oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the
subsidiary of Oracle) in the year 1995. James Gosling is known as
the father of Java. Before Java, its name was Oak. Since Oak was
already a registered company, so James Gosling and his team
changed the name from Oak to Java.
Platform: Any hardware or software environment in which a
program runs, is known as a platform. Since Java has a runtime
environment (JRE) and API, it is called a platform.
Java Example
Let's have a quick look at Java programming example. A detailed
description of Hello Java example is available in next page.
Simple.java
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

22
Application
According to Sun, 3 billion devices run Java. There are many
devices where Java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player,
antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java
programming APIs such as java.lang, java.io, java.net, java.util,
java.sql, java.math etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web
and enterprise applications. It is built on top of the Java SE platform.
It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight
user interface API.

23
History of Java
The history of Java is very interesting. Java was originally
designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The
history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language
for digital devices such as set-top boxes, televisions, etc. However,
it was best suited for internet programming. Later, Java technology
was incorporated by Netscape.
The principles for creating Java programming were "Simple,
Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling
and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile
devices, games, e-business solutions, etc. Following are given
significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated
the Java language project in June 1991. The small team of sun
engineers called Green Team.
2) Initially it was designed for small, embedded systems in
electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file
extension was .gt.
4) After that, it was called Oak and was developed as a part of the
Green project.
Why Java was named as "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as a national
tree of many countries like the U.S.A., France, Germany,
Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies.
24
Why Java Programming named "Java"?
7) Why had they chose the name Java for Java language? The team
gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell,
and fun to say.
According to James Gosling, "Java was one of the top choices along
with Silk". Since Java was so unique, most of the team members
preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced
(called Java coffee). It is a kind of espresso bean. Java name was
chosen by James Gosling while having a cup of coffee nearby his
office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems
(which is now a subsidiary of Oracle Corporation) and released
in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products
of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release
of Java, there have been many additional features added to the
language. Now Java is being used in Windows applications, Web
applications, enterprise applications, mobile applications, cards,
etc. Each new version adds new features in Java.
1.4(b)Features of Java:
The primary objective of Java programming language creation
was to make it portable, simple and secure programming language.
Apart from this, there are also some excellent features which play
an important role in the popularity of this language. The features of
Java are also known as Java buzzwords.
A list of the most important features of the Java language is given
below.
25
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a
simple programming language because:
26
o Java syntax is based on C++ (so easier for programmers to learn
it after C++).
o Java has removed many complicated and rarely-used features,
for example, explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there
is an Automatic Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything
in Java is an object. Object-oriented means we organize our software
as a combination of different types of objects that incorporate both
data and behavior.
Object-oriented programming (OOPs) is a methodology that
simplifies software development and maintenance by providing
some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in
which a program runs.
There are two types of platforms software-based and
hardware-based. Java provides a software-based platform.
The Java platform differs from most other platforms in the sense that
it is a software-based platform that runs on top of other hardware-
based platforms. It has two components:
27
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled
by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple
platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-
free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime
Environment (JRE) which is used to load Java classes into the
Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system
from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code
that can violate access rights to objects.
o Security Manager: It determines what resources a class can
access such as reading and writing to the local disk.
o Java language provides these securities by default. Some
security can also be provided by an application developer
explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the
Java Virtual Machine to get rid of objects which are not being
used by a Java application anymore.
o There are exception handling and the type checking mechanism
in Java. All these points make Java robust.
28
Architecture-neutral
Java is architecture neutral because there are no
implementation dependent features, for example, the size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory
for 32-bit architecture and 4 bytes of memory for 64-bit architecture.
However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java
bytecode to any platform. It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code. It is still
a little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create
distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently.
We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is
that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web
applications, etc.
1.4(c) C++ vs Java:

29
There are many differences and similarities between the C++
programming language and Java. A list of top differences between
C++ and Java are given below:

Comparison Index C++ java

Platform- C++ is platform-dependent. Java is platform-


independent independent.

Mainly used C++ is mainly used for system Java is mainly used for
for programming. application programming.
It is widely used in
Windows-based, web-
based, enterprise, and
mobile applications.

Design Goal C++ was designed for systems and Java was designed and
applications programming. It was an created as an interpreter
extension of the C programming for printing systems but
language. later extended as a support
network computing. It was
designed to be easy to use
and accessible to a broader
audience.

Goto C++ supports the goto statement. Java doesn't support the
goto statement.

Multiple C++ supports multiple inheritance. Java doesn't support


inheritance multiple inheritance
through class. It can be
achieved by
using interfaces in java.

Operator C++ supports operator overloading. Java doesn't support


Overloading operator overloading.

30
Pointers C++ supports pointers. You can write a Java supports pointer
pointer program in C++. internally. However, you
can't write the pointer
program in java. It means
java has restricted pointer
support in java.

Compiler and C++ uses compiler only. C++ is Java uses both compiler
Interpreter compiled and run using the compiler and interpreter. Java
which converts source code into source code is converted
machine code so, C++ is platform into bytecode at
dependent. compilation time. The
interpreter executes this
bytecode at runtime and
produces output. Java is
interpreted that is why it is
platform-independent.

Call by Value C++ supports both call by value and call Java supports call by value
and Call by by reference. only. There is no call by
reference reference in java.

Structure and C++ supports structures and unions. Java doesn't support
Union structures and unions.

Thread C++ doesn't have built-in support for Java has built-
Support threads. It relies on third-party libraries in thread support.
for thread support.

Documentatio C++ doesn't support documentation Java supports


n comment comments. documentation comment
(/** ... */) to create
documentation for java
source code.

Virtual C++ supports virtual keyword so that we Java has no virtual


Keyword can decide whether or not to override a keyword. We can override
function. all non-static methods by
default. In other words,

31
non-static methods are
virtual by default.

unsigned C++ doesn't support >>> operator. Java supports unsigned


right shift >>> right shift >>> operator
that fills zero at the top for
the negative numbers. For
positive numbers, it works
same like >> operator.

Inheritance C++ always creates a new inheritance Java always uses a single
Tree tree. inheritance tree because all
classes are the child of the
Object class in Java. The
Object class is the root of
the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive


with hardware.

Object- C++ is an object-oriented language. Java is also an object-


oriented However, in the C language, a single oriented language.
root hierarchy is not possible. However, everything
(except fundamental
types) is an object in Java.
It is a single root hierarchy
as everything gets derived
from java.lang.Object.

First Java Program | Hello World Example


1. Software Requirements
2. Creating Hello Java Example
3. Resolving javac is not recognized
In this section, we will learn how to write the simple program of
Java. We can write a simple hello Java program easily after
installing the JDK.

32
To create a simple Java program, you need to create a class that
contains the main method. Let's understand the requirement first.
The requirement for Java Hello World Example
For executing any Java program, the following software or
application must be properly installed.
o Install the JDK if you don't have installed it, download the JDK
and install it.
o Set path of the jdk/bin directory.
http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program
Creating Hello World Example:
Let's create the hello java program:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To compile: javac Simple.java
To execute: java Simple
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler
converts the source code into byte code.

33
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main,
String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility.
It means it is visible to all.
o static is a keyword. If we declare any method as static, it is
known as the static method. The core advantage of the static
method is that there is no need to create an object to invoke the
static method. The main() method is executed by the JVM, so it
doesn't require creating an object to invoke the main() method.
So, it saves memory.
o void is the return type of the method. It means it doesn't return
any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
We will discuss it in coming section.
o System.out.println() is used to print statement. Here, System is
a class, out is an object of the PrintStream class, println() is a
method of the PrintStream class. We will discuss the internal
working of System.out.println() statement in the coming section.
1.4(d) Difference between JDK, JRE, and JVM:
1. A summary of JVM
2. Java Runtime Environment (JRE)
3. Java Development Kit (JDK)

34
We must understand the differences between JDK, JRE, and
JVM before proceeding further to Java. See the brief overview of
JVM here.
If you want to get the detailed knowledge of Java Virtual
Machine, move to the next page. Firstly, let's see the differences
between the JDK, JRE, and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called
a virtual machine because it doesn't physically exist. It is a
specification that provides a runtime environment in which Java
bytecode can be executed. It can also run those programs which are
written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software
platforms. JVM, JRE, and JDK are platform dependent because the
configuration of each OS is different from each other. However,
Java is platform independent. There are three notions of the JVM:
specification, implementation, and instance.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also
written as Java RTE. The Java Runtime Environment is a set of
software tools which are used for developing Java applications. It is
used to provide the runtime environment. It is the implementation
of JVM. It physically exists. It contains a set of libraries + other files
that JVM uses at runtime.
The implementation of JVM is also actively released by other
companies besides Sun Micro Systems.

35
JDK
JDK is an acronym for Java Development Kit. The Java
Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java
Platforms released by Oracle Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and
a few other resources such as an interpreter/loader (java), a compiler
(javac), an archiver (jar), a documentation generator (Javadoc), etc.
to complete the development of a Java Application.

36
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which java
bytecode can be executed.
JVMs are available for many hardware and software platforms
(i.e. JVM is platform dependent).
What is JVM
It is:
1. A specification where working of Java Virtual Machine is
specified. But implementation provider is independent to choose
the algorithm. Its implementation has been provided by Oracle
and other companies.
2. An implementation its implementation is known as JRE (Java
Runtime Environment).
3. Runtime Instance Whenever you write java command on the
command prompt to run the java class, an instance of JVM is
created.
1.4(e) Java Variables:
A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.

37
Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
There are two types of data types in Java: primitive and non-
primitive.
Variable
A variable is the name of a reserved area allocated in memory. In
other words, it is a name of the memory location. It is a combination
of "vary + able" which means its value can be changed.

1. int data=50;//Here data is variable


Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local
variable. You can use this variable only within that method and the
other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.

38
2) Instance Variable
A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific
and is not shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It
cannot be local. You can create a single copy of the static variable
and share it among all the instances of the class. Memory allocation
for static variables happens only once when the class is loaded in the
memory.
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{ int data=50;//instance variable
}
}//end of class
1.4(f) Data Types in Java:
Data types specify the different sizes and values that can be stored
in the variable. There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
39
2. Non-primitive data types: The non-primitive data types include
Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.
Java is a statically-typed programming language. It means, all
variables must be declared before its use. That is why we need to
declare variable's type and name.
There are 8 types of primitive data types:
o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

40
Data Default Value Default size
Type

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

1. Boolean Data Type


The Boolean data type is used to store only two possible values: true
and false. This data type is used for simple flags that track true/false
conditions.
The Boolean data type specifies one bit of information, but its "size"
can't be defined precisely.
Example:
1. Boolean one = false

41
2.Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit
signed two's complement integer. Its value-range lies between -128
to 127 (inclusive). Its minimum value is -128 and maximum value
is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4
times smaller than an integer. It can also be used in place of "int"
data type.
Example:
1. byte a = 10, byte b = -20
3.Short Data Type
The short data type is a 16-bit signed two's complement integer. Its
value-range lies between -32,768 to 32,767 (inclusive). Its minimum
value is -32,768 and maximum value is 32,767. Its default value is
0.
The short data type can also be used to save memory just like byte
data type. A short data type is 2 times smaller than an integer.
Example:
1. short s = 10000, short r = -5000
4.Int Data Type
The int data type is a 32-bit signed two's complement integer. Its
value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647
(2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.
Example:
1. int a = 100000, int b = -200000

42
5. Long Data Type
The long data type is a 64-bit two's complement integer. Its value-
range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value
is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data
type is used when you need a range of values more than those
provided by int.
Example:
1. long a = 100000L, long b = -200000L
6.Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating
point.Its value range is unlimited. It is recommended to use a float
(instead of double) if you need to save memory in large arrays of
floating point numbers. The float data type should never be used for
precise values, such as currency. Its default value is 0.0F.
Example:
1. float f1 = 234.5f
7. Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating
point. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also
should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
1. double d1 = 12.3
8. Char Data Type
The char data type is a single 16-bit Unicode character. Its value-
range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The
char data type is used to store characters.
43
Example:
1. char letterA = 'A'
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. The
\u0000 is the lowest range of Unicode system. To get detail
explanation about Unicode visit next page.
1.4(g) Operators in Java:
Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
1. Java Unary Operator
The Java unary operators require only one operand. Unary
operators are used to perform various operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample
{
public static void main(String args[]){
int x=10;
44
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
2.Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical
operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

45
Output:
15
5
50
2
0
3.Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a
value to the left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Output:
40
80
80
240
4.Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
Java Right Shift Operator Example
46
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
4. Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the
first condition is false. It checks the second condition only if the first
one is true.
The bitwise & operator always checks both conditions whether first
condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}

47
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not
checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}
Output:
false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first
condition is true. It checks the second condition only if the first one
is false.
The bitwise | operator always checks both conditions whether first
condition is true or false.
public class OperatorExample{
48
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11
5.Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-
else statement and used a lot in Java programming. It is the only
conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample{
public static void main(String args[]){
49
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
2
6.Java Assignment Operator
Java assignment operator is one of the most common operators. It is
used to assign the value on its right to the operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16

50
1.5 (a): Objects and Classes in Java:
An object in Java is the physical as well as a logical entity, whereas,
a class in Java is a logical entity only.
What is an object in Java

An entity that has state and behavior is known as an object e.g.,


chair, bike, marker, pen, table, car, etc. It can be physical or logical
(tangible and intangible). The example of an intangible object is the
banking system.
An object has three characteristics:
o State: represents the data (value) of an object.
o Behavior: represents the behavior (functionality) of an object
such as deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external user.
However, it is used internally by the JVM to identify each object
uniquely.

51
For Example, Pen is an object. Its name is Reynolds; color is white,
known as its state. It is used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint
from which objects are created. So, an object is the instance(result)
of a class.
Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
1.5 (b) Class in Java:
A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical
entity. It can't be physical.
A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

52
Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
A variable which is created inside the class but outside the method
is known as an instance variable. Instance variable doesn't get
memory at compile time. It gets memory at runtime when an object
or instance is created. That is why it is known as an instance
variable.
Method in Java
In Java, a method is like a function which is used to expose the
behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
New keyword in Java
The new keyword is used to allocate memory at runtime. All objects
get memory in Heap memory area.
Object and Class Example: main within the class
In this example, we have created a Student class which has two data
members id and name. We are creating the object of the Student
class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: Student.java
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
53
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference
variable
System.out.println(s1.name);
}
}
Output:
0
null
Object and Class Example: main outside the class
In real time development, we create classes and use it from another
class. It is a better approach than previous one. Let's see a simple
example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java
file. If you define multiple classes in a single Java source file, it is a
good idea to save the file name with the class name which has main()
method.
File: TestStudent1.java
//Java Program to demonstrate having the main method in

54
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main
method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
3 Ways to initialize object :
There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor

55
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a
simple example where we are going to initialize the object through
a reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a
white space
}
}
Output:
101 Sonoo
We can also create multiple objects and store information in it
through reference variable.
File: TestStudent3.java
class Student{
int id;
String name;
}
56
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonoo
102 Amit
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord
method. Here, we are displaying the state (data) of the objects by
invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;

57
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan

58
As you can see in the above figure, object gets the memory in
heap memory area. The reference variable refers to the object
allocated in the heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory.
3) Object and Class Example: Initialization through a
constructor
We will learn about constructors in Java later.
Object and Class Example: Employee
Let's see an example where we are maintaining records of
employees.
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
59
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
Object and Class Example: Rectangle
There is given another example that maintains the records of
Rectangle class.
File: TestRectangle1.java
class Rectangle{
int length;
int width;
60
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
Anonymous object
61
Anonymous simply means nameless. An object which has no
reference is known as an anonymous object. It can be used at the
time of object creation only.
If you have to use an object only once, an anonymous object is a
good approach. For example:
new Calculation();//anonymous object
Calling method through a reference:
Calculation c=new Calculation();
c.fact(5);
Calling method through an anonymous object
new Calculation().fact(5);
Let's see the full example of an anonymous object in Java.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
Output:
Factorial is 120

62
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of
primitives.
Initialization of primitive variables:
int a=10, b=20;
Initialization of refernce variables:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two
objects
Let's see the example:
int width;
voi//Java Program to illustrate the use of Rectangle class which
//has length and width data members
class Rectangle{
int length d insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two
objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();

63
r2.calculateArea();
}
}
Output:
55
45
Real World Example: Account
File: TestAccount.java
//Java Program to demonstrate the working of a banking-system
//where we deposit and withdraw amount from our account.
//Creating an Account class which has deposit() and withdraw()
methods
class Account{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
64
}
//withdraw method
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+"
"+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
65
a1.checkBalance();
}}

Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0
1.5 (c) Inheritance in java:
Inheritance in Java is a fundamental concept of object-oriented
programming (OOP) that allows one class to inherit properties and
behaviors (fields and methods) from another class. Java supports
single inheritance, meaning a class can inherit from only one
superclass. However, a class can implement multiple interfaces,
allowing for a form of multiple inheritance through interface
implementation.
Here are some key aspects of inheritance in Java:
1. Superclass and Subclass: Inheritance involves two main
classes: the superclass (or parent class) and the subclass (or
child class). The subclass inherits the properties and behaviors
of the superclass.
2. "Is-A" Relationship: Inheritance establishes an "is-a"
relationship between the superclass and the subclass. This
means that a subclass is a specialized version of the superclass.
For example, if you have a Vehicle superclass, a Car subclass
is a type of vehicle.
3. Keyword extends: In Java, you use the extends keyword to
declare that a class is a subclass of another class. For example:
66
javaCopy code
class Subclass extends Superclass
{ // ...
}
4. Access to Superclass Members: Subclasses inherit the fields
and methods of the superclass. They can access and use these
inherited members as if they were defined in the subclass
itself. However, access modifiers (e.g., public, protected,
private) control the visibility and accessibility of inherited
members.
5. Overriding: Subclasses can override (provide a new
implementation for) methods inherited from the superclass.
This allows a subclass to customize or extend the behavior of
inherited methods. To override a method, you use the
@Override annotation to indicate that you intend to override a
method, and the method signature in the subclass must match
that of the superclass.
6. Super Keyword: The super keyword is used in a subclass to
refer to the members (fields and methods) of the superclass. It
can be used to call superclass constructors, access superclass
methods, and distinguish between superclass and subclass
members with the same name.
Here's a simple example of inheritance in Java:
javaCopy code
// Superclass
class Animal
{ void eat()
{ System.out.println("Animal is eating."); } }
// Subclass
class Dog extends Animal

67
{
void bark()
{
System.out.println("Dog is barking.");
}
}
public class Main
{
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.eat();
// Inherited from Animal
myDog.bark();
// Defined in Dog
} } In this example, Dog is a subclass of Animal, and it inherits the
eat method from Animal. It also adds its own method, bark. This
demonstrates the basic concept of inheritance in Java.
Single level inheritance
Multilevel inheritance in Java is a type of inheritance where a class
inherits from a superclass, and then another class inherits from that
subclass. In multilevel inheritance, there is a chain of inheritance
with multiple levels of classes. Each class in the chain becomes a
superclass for the class that inherits from it. This creates a
hierarchical relationship among the classes.

class Animal {

68
void eat() {
System.out.println("The animal is eating.");
}
}
// Child class inheriting from the parent class
class Dog extends Animal {
void bark() {
System.out.println("The dog is barking.");
}
}
public class Main {
public static void main(String[] args) {
// Create an instance of the child class
Dog myDog = new Dog();

// Call methods from both the parent and child class


myDog.eat(); // This calls the eat method from the Animal
class
myDog.bark(); // This calls the bark method from the Dog class
}
}
In this example, we have a parent class called Animal with a method
eat. The child class Dog extends Animal and adds its own method
called bark. When you create an instance of Dog, you can access
both the eat method inherited from Animal and the bark method
defined in the Dog class.

69
This is an example of single-level inheritance because there is one
level of inheritance between the parent class and the child class.
Multilevel inheritance
Multilevel inheritance in Java is a type of inheritance where a class
inherits from a superclass, and then another class inherits from that
subclass. In multilevel inheritance, there is a chain of inheritance
with multiple levels of classes. Each class in the chain becomes a
superclass for the class that inherits from it. This creates a
hierarchical relationship among the classes.
// Grandparent class
class Animal {
void eat() {
System.out.println("The animal is eating.");
}
}

// Parent class inheriting from the grandparent class


class Dog extends Animal {
void bark() {
System.out.println("The dog is barking.");
}
}
// Child class inheriting from the parent class
class Labrador extends Dog {
void swim() {
System.out.println("The Labrador is swimming.");
}
70
}
public class Main {
public static void main(String[] args) {
// Create an instance of the child class
Labrador myLabrador = new Labrador();
// Call methods from all three levels of the inheritance chain
myLabrador.eat(); // Calls eat method from Animal class
myLabrador.bark(); // Calls bark method from Dog class
myLabrador.swim(); // Calls swim method from Labrador
class
}
}
in this example:
• Animal is the grandparent class with an eat method.
• Dog is the parent class that inherits from Animal and adds a bark
method.
• Labrador is the child class that inherits from Dog and adds a
swim method.
Heirachical inheritance
Hierarchical inheritance, sometimes referred to as "tree
inheritance," is a type of inheritance in object-oriented programming
where multiple classes inherit properties and behaviors from a
common superclass or base class. In hierarchical inheritance, there
is a single superclass, and multiple subclasses derive from it. Each
subclass represents a specialized version of the common superclass.
Key features of hierarchical inheritance:
1. Single Superclass: In hierarchical inheritance, there is one
central superclass (base class) from which multiple subclasses

71
inherit. All these subclasses share common characteristics
defined in the superclass.
2. "Is-A" Relationship: Hierarchical inheritance establishes an
"is-a" relationship between the subclasses and the superclass.
This means that each subclass is a specific type of the common
superclass.
3. Code Reusability: The common properties and behaviors
defined in the superclass are reused by all the subclasses. This
promotes code reuse and maintains a consistent structure
across related classes.
4. Customization: Subclasses can add their specific properties
and behaviors in addition to the inherited ones. This
customization allows each subclass to have its own unique
functionality while retaining the shared attributes from the
superclass.
5. Polymorphism: Hierarchical inheritance enables
polymorphism, where objects of different subclasses can be
treated as instances of the common superclass. This facilitates
writing generic code that can work with various specialized
classes.

// Parent class
class Animal {
void eat() {
System.out.println("The animal is eating.");
}
}
// Child class 1 inheriting from the parent class
class Dog extends Animal {
void bark() {
System.out.println("The dog is barking.");
72
}
}
// Child class 2 inheriting from the parent class
class Cat extends Animal {
void meow() {
System.out.println("The cat is meowing.");
}
}
public class Main {
public static void main(String[] args) {
// Create instances of the child classes
Dog myDog = new Dog();
Cat myCat = new Cat();
// Call methods from both child classes
myDog.eat(); // Calls eat method from Animal class
myDog.bark(); // Calls bark method from Dog class

myCat.eat(); // Calls eat method from Animal class


myCat.meow(); // Calls meow method from Cat class
}
}
You can create instances of both Dog and Cat classes and access
methods specific to each class while sharing the common
functionality from the Animal class. This is an example of
hierarchical inheritance in Java.
Method overwriding
73
Method overriding in Java is a feature that allows a subclass
to provide a specific implementation of a method that is already
defined in its superclass. When a subclass overrides a method, it
provides its own version of the method with the same name, return
type, and parameters as the method in the superclass. This allows
the subclass to customize or extend the behavior of the inherited
method.
Key points about method overriding in Java:
1. Inheritance Required: Method overriding is only possible in
a subclass that inherits from a superclass. You cannot override
a method in the same class where it is defined.
2. Method Signature: The overriding method in the subclass
must have the same method signature as the method in the
superclass. This includes the method name, return type, and
parameter types (if any).
3. @Override Annotation: It's a good practice to use the
@Override annotation before the method in the subclass that
is intended to override a superclass method. This annotation
helps ensure that you are correctly overriding a method, and it
helps catch errors at compile-time if the method signatures
don't match.
4. Superclass Method: The method in the superclass that is
being overridden should be marked as public, protected, or
package-private (default) to allow access to subclasses. It
should not be marked as final, static, or private because these
methods cannot be overridden.
5. Polymorphism: Method overriding is a form of
polymorphism, where the actual method called depends on the
type of the object at runtime. This allows you to write code
that works with objects of different subclasses in a generic
way.
// Parent class
class Animal {

74
void makeSound() {
System.out.println("Animal makes a generic sound.");
}
}
// Child class inheriting from the parent class
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks.");
}
}
// Another child class inheriting from the parent class
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows.");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.makeSound(); // Calls the makeSound method of
the Animal class
75
myDog.makeSound(); // Calls the overridden makeSound
method in the Dog class
myCat.makeSound(); // Calls the overridden makeSound
method in the Cat class
}
}
In this example:
• The Animal class has a method makeSound.
• The Dog and Cat classes are child classes of Animal and both
override the makeSound method to provide their specific
implementations.
Use of super
In Java, the super keyword is used in various contexts to refer to the
members (fields, methods, and constructors) of the superclass
(parent class) when you're working in the context of a subclass
(child class). It allows you to access and call superclass members
and constructors.
// Parent class
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void makeSound() {
System.out.println("Animal makes a generic sound.");
}
}
// Child class inheriting from the parent class
76
class Dog extends Animal {
Dog(String name) {
super(name); // Call the constructor of the parent class
}
@Override
void makeSound() {
System.out.println(name + " the dog barks.");
}
void playFetch() {
System.out.println(name + " the dog is playing fetch.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog("Buddy");

// Call the overridden method in the Dog class


myDog.makeSound(); // Calls the overridden makeSound
method

// Call a method specific to the Dog class


myDog.playFetch();

// Call a method from the superclass using the super keyword


super.makeSound();
77
}
}
In this example:
• The Animal class has a constructor that sets the name attribute
and a method makeSound.
• The Dog class is a child class of Animal and calls the
super(name) constructor to initialize the name attribute of the
parent class.
• The Dog class overrides the makeSound method to provide its
specific implementation and adds a method playFetch.
Inside the main method, we create an instance of Dog called myDog
and demonstrate the use of the super keyword to call the makeSound
method from the parent class Animal.
Abstract class
In Java, an abstract class is a class that cannot be instantiated on its
own but serves as a blueprint for other classes. It allows you to
define methods that must be implemented by any concrete (non-
abstract) subclasses. Abstract classes are created using the abstract
keyword.
Here are some key points about abstract classes in Java:
1. Cannot Be Instantiated: You cannot create objects (instances)
of an abstract class directly. Attempting to do so will result in
a compilation error.
2. May Contain Abstract Methods: Abstract classes can have
abstract methods, which are declared without an
implementation. These methods are meant to be implemented
by concrete subclasses.
3. May Contain Concrete Methods: Abstract classes can also
have concrete (fully implemented) methods. Concrete
methods provide common functionality that can be inherited
by subclasses.

78
4. Can Have Fields: Abstract classes can have instance variables
(fields) just like any other class.
5. Subclassing: To use an abstract class, you need to create a
subclass that extends the abstract class. The subclass must
provide implementations for all abstract methods of the parent
abstract class.
Here's an example of an abstract class in Java:
// Abstract class
abstract class Shape {
String color;
Shape(String color) {
this.color = color;
}
// Abstract method - to be implemented by subclasses
abstract double getArea();

// Concrete method
void displayColor() {
System.out.println("The color of this shape is " + color);
}
}
// Concrete subclass 1
class Circle extends Shape {
double radius;

Circle(String color, double radius) {


super(color);
79
this.radius = radius;
}
@Override
double getArea() {
return Math.PI * radius * radius;
}
}
// Concrete subclass 2
class Rectangle extends Shape {
double width;
double height;
Rectangle(String color, double width, double height) {
super(color);
this.width = width;
this.height = height;
}

@Override
double getArea() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle("Red", 5.0);

80
Rectangle rectangle = new Rectangle("Blue", 4.0, 6.0);

circle.displayColor();
System.out.println("Circle Area: " + circle.getArea());

rectangle.displayColor();
System.out.println("Rectangle Area: " + rectangle.getArea());
}
}
In this example:
• Shape is an abstract class with an abstract method getArea and a
concrete method displayColor.
• Circle and Rectangle are concrete subclasses of Shape that
provide implementations for the getArea method.
You cannot create an instance of the Shape class directly
because it's abstract, but you can create instances of its concrete
subclasses Circle and Rectangle. Abstract classes like Shape are
useful for defining a common interface or behavior that multiple
related classes should share while allowing each subclass to
provide its own specific implementation.

81
1.5 (d) Interface in Java:
An interface in Java is a blueprint of a class. It has static constants
and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There
can be only abstract methods in the Java interface, not method body.
It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
Why use Java interface?
There are mainly three reasons to use interface. They are given
below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple
inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides
total abstraction; means all the methods in an interface are declared
with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
82
The Java compiler adds public and abstract keywords before the
interface method. Moreover, it adds public, static and final
keywords before data members.
In other words, Interface fields are public, static and final by default,
and the methods are public and abstract.

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class,
an interface extends another interface, but a class implements an
interface.

Java Interface Example


In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
83
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
84
obj.print();
obj.show();
}}
Output:Hello
Welcome
Multiple inheritance is not supported through class in java, but
it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple
inheritance is not supported in the case of class because of
ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided
by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
} }
Output:
Hello

85
As you can see in the above example, Printable and Showable
interface have same methods but its implementation is provided by
class TestTnterface1, so there is no ambiguity.
1.5(e)Java Package:
A java package is a group of similar types of classes, interfaces and
sub-packages.
Package in java can be categorized in two form, built-in package and
user-defined package.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-
defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.


//save as Simple.java
86
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
There are three ways to access the package from outside the
package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Access Modifiers in Java
There are two types of modifiers in Java: access modifiers and non-
access modifiers.
The access modifiers in Java specifies the accessibility or scope of
a field, method, constructor, or class. We can change the access level
of fields, constructors, methods, and class by applying the access
modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within
the package. It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within
the package and outside the package through child class. If you
do not make the child class, it cannot be accessed from outside
the package.

87
4. Public: The access level of a public modifier is everywhere. It can
be accessed from within the class, outside the class, within the
package and outside the package.
1.6(a) Exception Handling in Java:
The Exception Handling in Java is one of the powerful mechanism
to handle the runtime errors so that the normal flow of the
application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and
the difference between checked and unchecked exceptions.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal
flow of the application. An exception normally disrupts the normal
flow of the application
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception
hierarchy inherited by two subclasses: Exception and Error. The
hierarchy of Java Exception classes is given below:

88
Types of Java Exceptions
There are mainly two types of exceptions: checked and
unchecked. An error is considered as the unchecked exception.
However, according to Oracle, there are three types of exceptions
namely:
1. Checked Exception
2. Unchecked Exception
1) Checked Exception
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as
unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
89
Java Exception Keywords
Java provides five keywords that are used to handle the exception.
The following table describes each.

Keyword

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block
must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.

finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are
using a try-catch statement to handle the exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
90
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is
handled by a try-catch block.
Java try block:
Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
If an exception occurs at the particular statement in the try block, the
rest of the block code will not execute. So, it is recommended not to
keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Example:
public class TryCatchExample2 {
public static void main(String[] args) {
try
91
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Output:
java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed,
i.e., the rest of the code statement is printed.
Java finally block
is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is
handled or not. Therefore, it contains all the necessary statements
that need to be printed regardless of the exception occurs or not.
The finally block follows the try-catch block.
class TestFinallyBlock {
public static void main(String args[]){
92
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
Output:

Java throw Exception


In Java, exceptions allows us to write good quality codes
where the errors are checked at the compile time instead of runtime
and we can create custom exceptions making the code recovery and
debugging easier.
Java throw keyword

93
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The
Exception has some message with it that provides the error
description
In this example, we have created the validate method that takes
integer value as a parameter. If the age is less than 18, we are
throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to
vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

94
Output:

Throwing User-defined Exception


exception is everything else under the Throwable class.
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined
exception");
}
catch (UserDefinedException ude)
{
95
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
Output:

0 Java throws keyword


The Java throws keyword is used to declare an exception. It gives
an information to the programmer that there may occur an
exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can
be maintained.
Exception Handling is mainly used to handle the checked
exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
Java throws Example
Let's see the example of Java throws clause which describes that
checked exceptions can be propagated by throws keyword.

96
Testthrows1.java
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow..
1.6(b) Multithreading in java:
Multithreading in Java is a process of executing multiple threads
simultaneously.
97
A thread is a lightweight sub-process, the smallest unit of
processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
However, we use multithreading than multiprocessing because
threads use a shared memory area. They don't allocate separate
memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each
process allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for
saving and loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
98
What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing.
It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it
doesn't affect other threads. It uses a shared memory area.
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states.
These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
Explanation of Different Thread States
New: Whenever a new thread is created, it is always in the new state.
For a thread in the new state, the code has not been run yet and thus
has not begun its execution.
Active: When a thread invokes the start() method, it moves from the
new state to the active state. The active state contains two states
within it: one is runnable, and the other is running.
o Runnable: A thread, that is ready to run is then moved to the
runnable state. In the runnable state, the thread may be running
or may be ready to run at any given instant of time. It is the duty
of the thread scheduler to provide the thread time to run, i.e.,
moving the thread the running state.
A program implementing multithreading acquires a fixed slice
of time to each individual thread. Each and every thread runs for a
short span of time and when that allocated time slice is over, the
thread voluntarily gives up the CPU to the other thread, so that the
other threads can also run for their slice of time. Whenever such a
scenario occurs, all those threads that are willing to run, waiting for

99
their turn to run, lie in the runnable state. In the runnable state, there
is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the
runnable to the running state. Generally, the most common
change in the state of a thread is from runnable to running and
again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of
time (not permanently) then, either the thread is in the blocked state
or is in the waiting state.
For example, a thread (let's say its name is A) may want to
print some data from the printer. However, at the same time, the
other thread (let's say its name is B) is using the printer to print some
data. Therefore, thread A has to wait for thread B to use the printer.
Thus, thread A is in the blocked state. A thread in the blocked state
is unable to perform any execution and thus never consume any
cycle of the Central Processing Unit (CPU). Hence, we can say that
thread A remains idle until the thread scheduler reactivates thread
A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said
that the main thread is in the waiting state. The main thread then
waits for the child threads to complete their tasks. When the child
threads complete their job, a notification is sent to the main thread,
which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then
it is the duty of the thread scheduler to determine which thread to
choose and which one to reject, and the chosen thread is then given
the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation.
For example, a thread (its name is A) has entered the critical section
of a code and is not willing to leave that critical section. In such a
scenario, another thread (its name is B) has to wait forever, which
leads to starvation. To avoid such scenario, a timed waiting state is
given to thread B. Thus, thread lies in the waiting state for a specific
100
span of time, and not forever. A real example of timed waiting is
when we invoke the sleep() method on a specific thread. The sleep()
method puts the thread in the timed wait state. After the time runs
out, the thread wakes up and start its execution from when it has left
earlier.
Terminated: A thread reaches the termination state because of the
following reasons:
o When a thread has finished its job, then it exists or terminates
normally.
o Abnormal termination: It occurs when some unusual events
such as an unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In
other words, the thread is dead, and there is no way one can respawn
(active after kill) the dead thread

Java Threads | How to create a thread in Java


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface

101
1) Java Thread Example by extending Thread class
FileName: Multi.java
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:
thread is running..

2) Java Thread Example by implementing Runnable interface


FileName: Multi3.java
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor
Thread(Runnable r)
t1.start();
}
102
}
Output:
thread is running...
Java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
To do so, we were using free() function in C language and delete()
in C++. But, in java it is performed automatically. So, java provides
better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM)
so we don't need to make extra efforts.
Priority of a Thread (Thread Priority)
Each thread has a priority. Priorities are represented by a
number between 1 and 10. In most cases, the thread scheduler
schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends
on JVM specification that which scheduling it chooses. Note that
not only JVM a Java programmer can also assign the priorities of a
thread explicitly in a Java program.
Setter & Getter Method of Thread Priority
Let's discuss the setter and getter method of the thread priority.
public final int getPriority():The java.lang.Thread.getPriority()
method returns the priority of the given thread.
public final void setPriority(int newPriority): The
java.lang.Thread.setPriority() method updates or assign the priority
103
of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the
range, which is 1 (minimum) to 10 (maximum).
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
1.7(a) Java String:
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For
example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and
CharSequence interfaces.
Backward Skip 10sPlay VideoForward Skip 10s
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is
an object that represents a sequence of characters. The
java.lang.String class is used to create a string object.
How to create a string object?

104
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a
reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool.
For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly,


JVM will not find any string object with the value "Welcome" in
string constant pool that is why it will create a new object. After that
it will find the string with the value "Welcome" in the pool, it will
not create a new object but will return the reference to the same
instance.

105
Note: String objects are stored in a special memory area
known as the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are
created if it exists already in the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one
reference variable
In such case, JVM will create a new string object in normal (non-
pool) heap memory, and the literal "Welcome" will be placed in the
string constant pool. The variable s will refer to the object in a heap
(non-pool).
Java String Example
StringExample.java
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new
keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java

106
strings
example
1.7(b) Java i/o:
Java I/O (Input and Output) is used to process the input and produce
the output.
Java uses the concept of a stream to make I/O operation fast. The
java.io package contains all the classes required for input and output
operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data. In Java, a stream is composed of
bytes. It's called a stream because it is like a stream of water that
continues to flow.
In Java, 3 streams are created for us automatically. All these streams
are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given
below:

107
OutputStream
Java application uses an output stream to write data to a destination;
it may be a file, an array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it
may be a file, an array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream
by the figure given below.

OutputStream class
OutputStream class is an abstract class. It is the superclass of all
classes representing an output stream of bytes. An output stream
accepts output bytes and sends them to some sink.
Useful methods of OutputStream

Method Description

1) public void write(int)throws is used to write a byte to the current output


IOException stream.

2) public void is used to write an array of byte to the


write(byte[])throws current output stream.
IOException

3) public void flush()throws flushes the current output stream.


IOException
108
4) public void close()throws is used to close the current output stream.
IOException

OutputStream Hierarchy

InputStream class
InputStream class is an abstract class. It is the superclass of all
classes representing an input stream of bytes.

Method Description

1) public abstract reads the next byte of data from the input
int read()throws stream. It returns -1 at the end of the file.
IOException

2) public int returns an estimate of the number of bytes


available()throws that can be read from the current input
IOException stream.

3) public void is used to close the current input stream.


close()throws
IOException

109
InputStream Hierarchy

User Input from Keyboard


Accepting keyboard input in Java is done using a Scanner object.
Consider the following statement
Scanner console = new Scanner(System.in)
This statement declares a reference variable named console. The
Scanner object is associated with standard input device (System.in).
To get input from keyboard, you can call methods of Scanner class.
For example in following statment nextInt() method of Scanner
takes an integer and returns to variable x :
int x = console.nextInt();
Example :
import java.util.Scanner; // Needed for Scanner class
/**
* This program demonstrates keyboard input.
*/
public class RectangleArea
{
public static void main(String[] args)

110
{
int length; // To hold rectangle's length.
int width; // To hold rectangle's width.
int area; // To hold rectangle's area

// Create a Scanner object to read input.


Scanner console = new Scanner(System.in);
// Get length from the user.
System.out.print("Enter length ");
length = console.nextInt();
// Get width from the user.
System.out.print("Enter width ");
width = console.nextInt();
// Calculate area.
area = length * width;

// Display area.
System.out.println("The area of rectangle is " + area);
}
}
Output :
Enter length 5
Enter width 8
The area of rectangle is 40
1.7(c) Java applet:

111
Applet is a special type of program that is embedded in the webpage
to generate the dynamic content. It runs inside the browser and
works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms,
including Linux, Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel.


Panel class extends Container which is the subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
112
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods for an
applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited.
It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked
only once.
2. public void start(): is invoked after the init() method or browser
is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is
invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.

113
1. public void paint(Graphics g): is used to paint the Applet. It
provides Graphics class object that can be used for drawing oval,
rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it.
After that create an html file and place the applet code in html file.
Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}

}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
114
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that
contains applet tag in comment and compile it. After that run it by:
appletviewer First.java. Now Html file is not required but it is for
testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command
prompt:
c:\>javac First.java
c:\>appletviewer First.java
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics
programming.
115
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to
draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is
used to fill rectangle with the default color and specified width
and height.
4. public abstract void drawOval(int x, int y, int width, int height):
is used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is
used to fill oval with the default color and specified width and
height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is
used to draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle): is used draw a circular or elliptical
arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical
arc.
10. public abstract void setColor(Color c): is used to set the graphics
current color to the specified color.
11. public abstract void setFont(Font font): is used to set the
graphics current font to the specified font.
Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
116
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
1.8(a) Java AWT:
Java AWT (Abstract Window Toolkit) is an API to develop
Graphical User Interface (GUI) or windows-based applications in
Java.Java AWT components are platform-dependent i.e.
components are displayed according to the view of operating
system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).The java.awt
package provides classes for AWT API such as TextField, Label,
117
TextArea, RadioButton, CheckBox, Choice, List etc.The AWT
tutorial will help the user to understand Java GUI programming in
simple and easy steps.
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform
(operating systems) subroutine for creating API components like
TextField, ChechBox, button, etc.For example, an AWT GUI with
components like TextField, label and button will have different look
and feel for the different platforms like Windows, MAC OS, and
Unix. The reason for this is the platforms have different view for
their native components and AWT directly calls the native
subroutine that creates those components.In simple words, an AWT
application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.

Components
118
All the elements like the button, text fields, scroll bars, etc. are
called components. In Java AWT, there are classes for each
component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them
to a container.
Container
The Container is a component in AWT that can contain
another components like buttons, textfields, labels etc. The classes
that extends Container class are known as container such as Frame,
Dialog and Panel.
It is basically a screen where the where the components are
placed at their specific locations. Thus it contains and controls the
layout of components.
Note: A container itself is a component (see the above diagram),
therefore we can add a container inside container.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu
bars. You must use frame, dialog or another window for creating a
window. We need to create an instance of Window class to create
this container.
Panel
The Panel is the container that doesn't contain title bar, border
or menu bar. It is generic container for holding the components. It
can have other components like button, text field etc. An instance of
Panel class creates a container, in which we can add components.
119
Frame
The Frame is the container that contain title bar and border and
can have menu bars. It can have other components like button, text
field, scrollbar etc. Frame is most widely used container while
developing an AWT application.

Useful Methods of Component Class

Method Description

public void Inserts a component on this component.


add(Component c)

public void setSize(int Sets the size (width and height) of the
width,int height) component.

public void Defines the layout manager for the


setLayout(LayoutManager component.
m)

public void Changes the visibility of the component,


setVisible(boolean status) by default false.

Java AWT Example


To create simple AWT example, you need a frame. There are two
ways to create a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame
class. Here, we are showing Button component on the Frame.

120
AWTExample1.java
// importing Java AWT class
import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

121
// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();

}
The setBounds(int x-axis, int y-axis, int width, int height) method is
used in the above example that sets the position of the awt button.
Output:

122
AWT Example by Association
Let's see a simple example of AWT where we are creating instance
of Frame class. Here, we are creating a TextField, Label and Button
component on the Frame.
AWTExample2.java
// importing Java AWT class
import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

123
// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

124
// setting the title of frame
f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}
// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

}
Output:

125
JAVA AWT CONTROLS
• Java AWT Label
• Java AWT Button
• Java AWT TextField
• Java AWT Checkbox
• Java AWT CheckboxGroup
• Java AWT Choice
• Java AWT List
• Java AWT Canvas
• AWT Scrollbar
• Java AWT MenuItem & Menu
• Java AWT PopupMenu
• Java AWT Panel
• Java AWT Toolkit
1. Java AWT Label
AWT Label Class Constructors
There are three types of Java AWT Label Class
126
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified
alignment
2. Java AWT Button
AWT Button is a control component with a label that generates an
event when clicked on. Button Class is used for creating a labeled
button that is platform-independent.
Syntax of AWT Button
public class Button extends Component implements Accessible
Java AWT Button Class Constructors
There are two types of Button class constructors as mentioned
below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click
Here” button with show click here as the value.
3. Java AWT TextField
Syntax of AWT TextField:
public class TextField extends TextComponent
TextField Class constructors
There are TextField class constructors are mentioned below:
1. TextField():
127
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be
displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns
(col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given
number of columns (col).
4. Java AWT Checkbox
Syntax of AWT Checkbox:
public class Checkbox extends Component implements
ItemSelectable, Accessible
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as
mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the
mentioned group.
5. Java AWT CheckboxGroup
CheckboxGroup Class is used to group together a set of Checkbox.
Syntax of AWT CheckboxGroup:

128
public class CheckboxGroup extends Object implements
Serializable
Note: CheckboxGroup enables the use of radio buttons in AWT.
6. Java AWT Choice
The object of the Choice class is used to show a popup menu of
choices.
Syntax of AWT Choice:
public class Choice extends Component implements ItemSelectable,
Accessible
AWT Choice Class constructor
Choice(): It creates a new choice menu.
7.Java AWT List
The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable,
Accessible
AWT List Class Constructors
The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.

129
1.8(b) Event handling in java:
An event can be defined as changing the state of an object or
behavior by performing actions. Actions can be a button click,
cursor movement, keypress through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event
classes.
Classification of Events
• Foreground Events
• Background Events

Types of Events
1. Foreground Events
Foreground events are the events that require user interaction
to generate, i.e., foreground events are generated due to interaction
by the user on components in Graphic User Interface (GUI).
Interactions are nothing but clicking on a button, scrolling the scroll
bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are
known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.

130
EVENT HANDLING
It is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows the
Delegation Event model.
Delegation Event model
• It has Sources and Listeners.

Delegation Event Model


• Source: Events are generated from the source. There are various
sources like buttons, checkboxes, list, menu-item, choice,
scrollbar, text components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated
from the source. Each of these listeners represents interfaces that
are responsible for handling events.
• To perform Event Handling, we need to register the source with
the listener.

131
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to
register.
Event Classes in Java

Event Class Listener Interface Description

An event that indicates


that a component-defined
action occurred like a
ActionEvent ActionListener
button click or selecting
an item from the menu-
item list.

The adjustment event is


AdjustmentEvent AdjustmentListener emitted by an Adjustable
object like Scrollbar.

An event that indicates


that a component moved,
ComponentEvent ComponentListener
the size changed or
changed its visibility.

When a component is
added to a container (or)
ContainerEvent ContainerListener removed from it, then
this event is generated by
a container object.

132
Event Class Listener Interface Description

These are focus-related


events, which include
FocusEvent FocusListener
focus, focusin, focusout,
and blur.

An event that indicates


ItemEvent ItemListener whether an item was
selected or not.

An event that occurs due


to a sequence of
KeyEvent KeyListener
keypresses on the
keyboard.

The events that occur due


MouseListener & to the user interaction
MouseEvent
MouseMotionListener with the mouse (Pointing
Device).

An event that specifies


MouseWheelEvent MouseWheelListener that the mouse wheel was
rotated in a component.

An event that occurs


TextEvent TextListener when an object’s text
changes.

An event which indicates


WindowEvent WindowListener whether a window has
changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the


registered class to handle events.

133
Different interfaces consists of different methods which are
specified below.

Listener Interface Methods

ActionListener  actionPerformed()

AdjustmentListener  adjustmentValueChanged()

 componentResized()
 componentShown()
ComponentListener
 componentMoved()
 componentHidden()

 componentAdded()
ContainerListener
 componentRemoved()

 focusGained()
FocusListener
 focusLost()

ItemListener  itemStateChanged()

 keyTyped()
KeyListener  keyPressed()
 keyReleased()

 mousePressed()
 mouseClicked()
MouseListener
 mouseEntered()
 mouseExited()

134
Listener Interface Methods

 mouseReleased()

 mouseMoved()
MouseMotionListener
 mouseDragged()

MouseWheelListener  mouseWheelMoved()

TextListener  textChanged()

 windowActivated()
 windowDeactivated()
 windowOpened()
WindowListener  windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()

Flow of Event Handling


1. User Interaction with a component is required to generate an
event.
2. The object of the respective event class is created automatically
after event generation, and it holds all information of the event
source.
3. The newly created object is passed to the methods of the
registered listener.
4. The method executes and returns the result.

135
Code-Approaches
The three approaches for performing event handling are by placing
the event handling code in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler
may throw errors due to the unavailability of some packages.
Event Handling Within Class

// Java progam to demonstrate the


// event handling within the class

import java.awt.*;
import java.awt.event.*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of the component
136
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
button.addActionListener(this);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("GFG!");
}

public static void main(String[] args)


{

137
new GFGTop();
}
}
Output

After Clicking, the text field value is set to GFG!

Explanation
1. Firstly extend the class with the applet and implement the
respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event. i.e.
ActionEvent by addActionListener().
4. In the end, implement the abstract method.

138
1.8(c) LayoutManager:
The Layout managers enable us to control the way in which visual
components are arranged in the GUI forms by determining the size
and position of components within the containers.
Types of LayoutManager
There are 6 layout managers in Java
• FlowLayout: It arranges the components in a container like the
words on a page. It fills the top line from left to right and top to
bottom. The components are arranged in the order as they are
added i.e. first components appears at top left, if the container is
not wide enough to display all the components, it is wrapped
around the line. Vertical and horizontal gap between
components can be controlled. The components can be left,
center or right aligned.
• BorderLayout: It arranges all the components along the edges
or the middle of the container i.e. top, bottom, right and left
edges of the area. The components added to the top or bottom
gets its preferred height, but its width will be the width of the
container and also the components added to the left or right gets
its preferred width, but its height will be the remaining height of
the container. The components added to the center gets neither
its preferred height or width. It covers the remaining area of the
container.
• GridLayout: It arranges all the components in a grid of equally
sized cells, adding them from the left to right and top to bottom.
Only one component can be placed in a cell and each region of
the grid will have the same size. When the container is resized,
all cells are automatically resized. The order of placing the
components in a cell is determined as they were added.
• GridBagLayout: It is a powerful layout which arranges all the
components in a grid of cells and maintains the aspect ration of
the object whenever the container is resized. In this layout, cells
may be different in size. It assigns a consistent horizontal and

139
vertical gap among components. It allows us to specify a default
alignment for components within the columns or rows.
• BoxLayout: It arranges multiple components in either vertically
or horizontally, but not both. The components are arranged from
left to right or top to bottom. If the components are aligned
horizontally, the height of all components will be the same and
equal to the largest sized components. If the components are
aligned vertically, the width of all components will be the same
and equal to the largest width components.
• CardLayout: It arranges two or more components having the
same size. The components are arranged in a deck, where all the
cards of the same size and the only top card are visible at any
time. The first component added in the container will be kept at
the top of the deck. The default gap at the left, right, top and
bottom edges are zero and the card components are displayed
either horizontally or vertically.
Example
import java.awt.*;
import javax.swing.*;
public class LayoutManagerTest extends JFrame {
JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1,
gridLayoutPanel2, gridLayoutPanel3;
JButton one, two, three, four, five, six;
JLabel bottom, lbl1, lbl2, lbl3;
public LayoutManagerTest() {
setTitle("LayoutManager Test");
setLayout(new BorderLayout()); // Set BorderLayout for
JFrame
flowLayoutPanel1 = new JPanel();
one = new JButton("One");

140
two = new JButton("Two");
three = new JButton("Three");
flowLayoutPanel1.setLayout(new
FlowLayout(FlowLayout.CENTER)); // Set FlowLayout Manager
flowLayoutPanel1.add(one);
flowLayoutPanel1.add(two);
flowLayoutPanel1.add(three);
flowLayoutPanel2 = new JPanel();
bottom = new JLabel("This is South");
flowLayoutPanel2.setLayout (new
FlowLayout(FlowLayout.CENTER)); // Set FlowLayout Manager
flowLayoutPanel2.add(bottom);
gridLayoutPanel1 = new JPanel();
gridLayoutPanel2 = new JPanel();
gridLayoutPanel3 = new JPanel();
lbl1 = new JLabel("One");
lbl2 = new JLabel("Two");
lbl3 = new JLabel("Three");
four = new JButton("Four");
five = new JButton("Five");
six = new JButton("Six");
gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5)); // Set
GridLayout Manager
gridLayoutPanel2.add(lbl1);
gridLayoutPanel2.add(lbl2);
gridLayoutPanel2.add(lbl3);

141
gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5, 5)); // Set
GridLayout Manager
gridLayoutPanel3.add(four);
gridLayoutPanel3.add(five);
gridLayoutPanel3.add(six);
gridLayoutPanel1.setLayout(new GridLayout(2, 1)); // Set
GridLayout Manager
gridLayoutPanel1.add(gridLayoutPanel2);
gridLayoutPanel1.add(gridLayoutPanel3);
add(flowLayoutPanel1, BorderLayout.NORTH);
add(flowLayoutPanel2, BorderLayout.SOUTH);
add(gridLayoutPanel1, BorderLayout.CENTER);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new LayoutManagerTest();
}
}

142
Output

***

143
Chapter - 2
Web Page Designing

2.1 (a) HTML COMMON TAGS:


• HTML stands for Hyper Text Markup Language
• An HTML file is a text file containing small markup tags
• The markup tags tell the Web browser how to display the
page
• An HTML file must have an htm or html file extension
• An HTML file can be created using a simple text editor

Type in the following text in “NOTEPAD”:


<html>
<head>
<title>Title of page</title>
</head>
<body>
Hello World! This is my first homepage. <b>This text is bold</b>
</body>
</html>
Save the file as "mypage.html".
Start your Internet browser. Select "Open" (or "Open Page") in
the File menu of your browser. A dialog box will appear. Select
"Browse" (or "Choose File") and locate the HTML file you just
created - "mypage.html" - select it and click "Open". Now you
should see an address in the dialog box, for example
"C:\MyDocuments\webdesign\mypage.html". Click OK, and the
browser will display the page.
Example Explained
The first tag in your HTML document is <html>. This tag tells your
browser that this is the start of an HTML document. The last tag in
144
your document is </html>. This tag tells your browser that this is the
end of the HTML document.

The text between the <head> tag and the </head> tag is header
information. Header information is not displayed in the browser
window. The text between the <title> tags is the title of your
document. The title is displayed in your browser's caption. The text
between the <body> tags is the text that will be displayed in your
browser. The text between the <b> and </b> tags will be displayed
in a bold font.
2.1(b)HTML ELEMENTS:
HTML documents are text files made up of HTML elements. HTML
elements are defined using HTML tags.
HTML Tags
• HTML tags are used to mark-up HTML elements
• HTML tags are surrounded by the two characters < and >
• The surrounding characters are called angle brackets
• HTML tags normally come in pairs like <b> and </b>
• The first tag in a pair is the start tag, the second tag is the end
tag
• The text between the start and end tags is the element content
• HTML tags are not case sensitive, <b> means the same as <B>
The purpose of the <b> tag is to define an HTML element that
should be displayed as bold.
Tag Attributes
Tags can have attributes. Attributes can provide additional
information about the HTML elements on your page.
This tag defines the body element of your HTML page: <body>.
With an added bgcolor attribute, you can tell the browser that the
background color of your page should be red, like this:
<body bgcolor="red">
145
This tag defines an HTML table: <table>. With an added border
attribute, you can tell the browser that the table should have no
borders: <table border="0">. Attributes always come in name/value
pairs like this: name="value". Attributes are always added to the
start tag of an HTML element.
1. HEADINGS
Headings are defined with the <h1> to <h6> tags. <h1> defines the
largest heading. <h6> defines the smallest heading.
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>

HTML automatically adds an extra blank line before and after a


heading.
2. PARAGRAPHS
Paragraphs are defined with the <p> tag.
<p>This is a paragraph</p>
<p>This is another paragraph</p>

HTML automatically adds an extra blank line before and after a


paragraph.
3. LINE BREAKS
The <br> tag is used when you want to end a line, but don't want to
start a new paragraph. The
<br> tag forces a line break wherever you place it.
The <br> tag is an empty tag. It has no closing tag.
146
4. Comments in HTML
The comment tag is used to insert a comment in the HTML source
code. A comment will be ignored by the browser. You can use
comments to explain your code, which can help you when you edit
the source code at a later date.
Note that you need an exclamation point after the opening bracket,
but not before the closing bracket.
2.1(c)HTML TEXT FORMATTING:
HTML defines a lot of elements for formatting output, like bold or
italic text. How to View HTML Source? To find out, click the VIEW
option in your browser's toolbar and select SOURCE or PAGE
SOURCE. This will open a window that shows you the HTML code
of the page.
1. Text Formatting Tags
Tag Description
<i> Defines italic text. Recommend using <em>
<b> Defines bold text. Recommend using <strong>
<em> Defines emphasized text. Renders as italic text.
<strong> Defines strong text. Renders as bold text.

Example
Source Output
<i>Italic text</i><br /> Italic text
<b>Bold text</b><br /> Bold text
<em>Emphasized text</em><br> Emphasized text
<strong>Strong text</strong><br> Strong text

What is the difference between <i> & <em> and <b> &
<strong>, <b> and <i> will both become deprecated tags. Using
<strong> and <em> are the tags that will be cross-browser

147
compatible as browsers move forward to embrace the new standards
in HTML (e.g., XHTML)
2. HTML Links
HTML uses a hyperlink to link to another document on the Web.
HTML uses the <a> (anchor) tag to create a link to another
document. An anchor can point to any resource on the Web: an
HTML page, an image, a sound file, a movie, etc.
The syntax of creating an anchor:
The <a> tag is used to create an anchor to link from, the href attribute
is used to address the document to link to, and the words between
the open and close of the anchor tag will be displayed as a hyperlink.
This anchor defines a link to W3Schools:
The line above will look like this in a browser:
Google
The Target Attribute
With the target attribute, you can define where the linked document
will be opened. The line below will open the document in a new
browser window:
The Anchor Tag and the Name Attribute
The name attribute is used to create a named anchor. When using
named anchors we can create links that can jump directly into a
specific section on a page, instead of letting the user scroll around
to find what he/she is looking for.
Below is the syntax of a named anchor:
<a name="label">Text to be displayed</a>
The name attribute is used to create a named anchor. The name of
the anchor can be any text you
care to use.
The line below defines a named anchor:
148
You should notice that a named anchor is not displayed in a special
way. To link directly to the "tips" section, add a # sign and the name
of the anchor to the end of a URL, like this:
2.1(d) HTML LISTS:
HTML supports ordered, unordered and definition lists.
1. Unordered Lists
An unordered list is a list of items. The list items are marked with
bullets (typically small black circles).
An unordered list starts with the <ul> tag. Each list item starts with
the <li> tag.
Here is how it looks in a browser:
• Coffee
• Milk
Inside a list item you can put paragraphs, line breaks, images, links,
other lists, etc.
2. Ordered Lists

with numbers.

the <li> tag.


Here is how it looks in a browser:
1. Coffee
2. Milk
Inside a list item you can put paragraphs, line breaks, images, links,
other lists, etc.
2.1(e) HTML TABLE:
Tables are defined with the <table> tag.
149
A table is divided into rows (with the <tr> tag), and each row is
divided into data cells (with the
<td> tag). td stands for "table data," and holds the content of a data
cell. A <td> tag can contain text, links, images, lists, forms, other
tables, etc.
Table Example
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
How the HTML code above looks in a browser:

row 1, cell 1 row 1, cell 2

row 2, cell 1 row 2, cell 2

HTML Tables and the Border Attribute


If you do not specify a border attribute, the table will be
displayed without borders. Sometimes this can be useful, but most
of the time, we want the borders to show.
To display a table with borders, specify the border attribute:
<table border="1">

150
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
HTML Table Headers
Header information in a table are defined with the <th> tag. All
major browsers display the text in the <th> element as bold and
centered.
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

151
How the HTML code above looks in your browser:

Header 1 Header 2

row 1, cell 1 row 1, cell 2

row 2, cell 1 row 2, cell 2

HTML Table Tags

Tag Description
<table> Defines a table
<th> Defines a header cell in a table
<tr> Defines a row in a table
<td> Defines a cell in a table
<caption> Defines a table caption
<colgroup> Specifies a group of one or more columns in a table for
formatting
<col> Specifies column properties for each column within a
<colgroup> element
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table
HTML <table> Tag
Definition and Usage
The <table> tag defines an HTML table. An HTML table consists
of the <table> element and one or more <tr>, <th>, and <td>
elements. The <tr> element defines a table row, the <th> element
defines a table header, and the <td> element defines a table cell. A
152
more complex HTML table may also include <caption>, <col>,
<colgroup>, <thead>, <tfoot>, and <tbody> elements.
Attributes
Attribute Value Description
align left Not supported in HTML5.
center Deprecated in HTML
right 4.01.Specifies the
alignment of a table
according tosurrounding
text
bgcolor rgb(x,x,x) Not supported in HTML5.
#xxxxxx Deprecated in HTML 4.01.Specifies
colorname the background color for a table
border “1” Specifies whether the table cells
should have borders ornot
Cellpadding pixels Not supported in HTML5. Specifies
the space between thecell wall and
the cell content
Cellspacing pixels Not supported in HTML5. Specifies
the space between cells
frame void Not supported in HTML5. Specifies
above which parts of theoutside borders
below that should be visible
hside
slhs
rhs
vside
sbox
borde
r
rules none Not supported in HTML5. Specifies
group which parts of the insideborders that
srows should be visible
cols
all

summary text Not supported in HTML5. Specifies a


summary of thecontent of a table
width pixels Not supported in HTML5. Specifies
% the width of a table

153
Example
<table border="1">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
HTML IMAGES
With HTML you can display images in a document.
The Image Tag and the src Attribute
In HTML, images are defined with the <img> tag. To display an
image on a page, you need to use the src attribute. Src stands for
"source". The value of the src attribute is the URL of the image you
want to display on your page.
The URL points to the location where the image is stored. An image
named "boat.gif" located in the directory "images" on
"www.w3schools.com" has the URL:
http://www.w3schools.com/images/boat.gif. The browser puts the
image where the image tag occurs in the document. If you put an
image tag between two paragraphs, the browser shows the first
paragraph, then the image, and then the second paragraph.
The Alt Attribute
The alt attribute is used to define an "alternate text" for an image.
The value of the alt attribute is an author-defined text:

154
The "alt" attribute tells the reader what he or she is missing on a
page if the browser can't load images. The browser will then display
the alternate text instead of the image. It is a good practice to include
the "alt" attribute for each image on a page, to improve the display
and usefulness of your document for people who have text-only
browsers.
HTML BACKGROUNDS
A good background can make a Web site look really great.
Backgrounds
The <body> tag has two attributes where you can specify
backgrounds. The background can be a color or an image.
1. Bgcolor
The bgcolor attribute specifies a background-color for an HTML
page. The value of this attribute can be a hexadecimal number, an
RGB value, or a color name:
The lines above all set the background-color to black.
2. Background
The background attribute specifies a background-image for an
HTML page. The value of this attribute is the URL of the image you
want to use. If the image is smaller than the browser window, the
image will repeat itself until it fills the entire browser window.
2.1(e) FORMS:
Forms can be used to collect information. Sophisticated forms may
be linked to a database to store the information, but this is beyond
the scope of the article. This article will show you how to create a
form that emails you the information.
Here is a very basic email form:
<form action="mailto:support@pixelmill.com" method="post">
Name:<br>
<input type="text" name="name" size="20"><br> Email:<br>
155
<input type="text" name="email" size="20"><br> Comment:<br>
<textarea cols="20" rows="5"></textarea><br>
<input type="submit" value="Submit"> <input type="reset"
value="Reset">
</form>
And here's what it looks like:
Name:
Email:
Comment:
Notice that the "input" tag was used for the text fields as well as the
buttons! The "input" tag is the tag you will use most often in forms.
Here are different forms of the input tag:
• type="text"
• type="password" (asterisks when you type)
• type="checkbox"
• type="radio"
• type="submit" (You can change the text on the button.)
• type="reset" (You can change the text on the button.)
• type="hidden" (You can't see this because it's hidden! This
allows you to send additional variables that your user can't see.)
• type="button" (You can change the text on the button.
Below you will find a table of the various form elements and how
you can use them.
FORM – attributes
action This attribute usually has a link to a web page that
="[url]" contains code which processes the form. In our
example above, we use "mailto" to tell the form to
send the information as an email.
method This attribute specifies how the information is sent.
With the "get" method, all the information is sent in
="get"
156
="post" one long URL string. With the "post" method, all the
information is sent but is "invisible" to the user.
name When creating complex forms and using scripting, you
="[name may need to specify the name of the form. The name
should be unique - that is, you shouldn't have other
forms on the page with the same form name.
of
form]"
INPUT – attributes
type The "type" attribute allows you to specify what
type of form element you want to use. As you
="text"
can see, the "input" element can have many
="password" different forms - see above for examples
="checkbox"
="radio"
="submit"
="reset"
="hidden"
="button"

checked This attribute does not have any values. When


you put this attribute into the tag for "radio" or
"checkbox," they will be selected.

src Use this attribute when you have an "image" to


specify the location of the image.
="[url]"
TEXTAREA - attributes
This form element is the multi-line text box that you often seen for
"comments." The opening and closing tag surround the text that will
be initially displayed.

157
name This attribute must be set to a unique name so you
know how to refer to the form element.
="[referring
name]"
Rows This attribute allows you to set the number of
rows for the text area.
="[number]"

cols This attribute allows you to set the number of


columns for the text area.
="[number]"
SELECT - attributes
The SELECT tag allows you to create "select boxes" or "drop down
menus." It is the "outer" element, used with the OPTION tag. (See
the example link below)
name This attribute must be set to a unique name so
you know how to refer to the form element.
="[referring
name]"
size This attribute allows you to set how many rows
are visible.
="[number]"
Multiple This attribute does not have any
"values." When you set this attribute, it allows
the user to select more than one option.

OPTION - attributes
The OPTION tag is used with the SELECT tag to define the
different options in the select box or dropdown menu. The opening
and closing tag surround the text that will be displayed.
value This attribute must be set to a unique name so you
know how to refer to the form element. It will
="[value]"
probably be an abbreviated version of the text that
is displayed.
158
Selected This attribute does not have any "values." When
you set this attribute, it marks this option as being
"preselected."
Putting it all together...
Here's a sample page using this code below:
<form>
Enter your Name: <input type="text" width="20" size="20">
<p>Favorite Color:<br>
<input type="checkbox" checked value="red" name="colors">
Red<br>
<input type="checkbox" value="blue" name="colors"> Blue</p>
<p>Gender:<br>
<input type="radio" checked value="male"
name="gender">Male<br>
<input type="radio" value="female" name="gender">Female</p>
<p>Address:<br>
<textarea rows="5" cols="20">Please enter
your permanent addresshere.</textarea></p>
Country:<br>
<select name="country">
<option value="usa" selected>USA</option>
<option value="uk">United Kingdom</option>
<option value="canada">Canada</option>
</select>

2.2(a)Introduction to CSS:
CSS stands for Cascading Style Sheets. CSS describes how
HTML elements are to be displayed on screen, paper, or in other
media. CSS saves a lot of work. It can control the layout of multiple
web pages all at once. External style sheets are stored in “.css” files.
CSS is used to define styles for your web pages, including the
design, layout and variations in display for different devices and
screen sizes.
159
Types of CSS:
There are three types of CSS available. They are:
1. Inline CSS
2. Internal CSS
3. External CSS
1. Inline CSS:
If the styles are mentioned along with the tag then this type of CSS
is known as inline CSS.
Example:
<p style=”text-align: justify; background-color: red”>Hi this is the
Inline CSS. </p>
2. Internal CSS:
For internal CSS, we write all the desired “styles” for the “selectors”
along with the properties and values in the “head” section. And in
the body section then newly defied selector tags are used with the
actual contents.

<html>
<head>
<style type= “text/css”>p
{
text-align: justify; background-color: red;
}
</style>
</head>
<body>
<p>This is Internal CSS.</p>
</body>
</html>

Example:
3. External CSS:
160
Sometimes we need to apply particular style to more than one web
page; in such cases external CSS can be used. The main idea in this
type of CSS is that the desired styles can be written in one “.css”
file. And this file can be called in our web pages to apply the styles.
Example:
CSS Selectors:
CSS selectors are used to "find" (or select) HTML elements
based on their element name, id, class, attribute, and more.
The element Selector:
The element selector selects elements based on the element
name. You can select all <p> elements on a page like this (in this
case, all <p> elements will be center-aligned, with a red text color):
Example:
p{
text-align: center; color: red;
}
The id Selector:
The id selector uses the id attribute of an HTML element to
select a specific element. The id of an element should be 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. The style rule below will be
applied to the HTML element with id="para1": Example:
#para1 {
text-align: center; color: red;
}
The class Selector:
The class selector selects elements with a specific class
attribute. To select elements with a specific class, write a period (.)
161
character, followed by the name of the class. In the example below,
all HTML elements with class="center" will be red and center-
aligned:
Example:
.center {
text-align: center; color: red;
}
You can also specify that only specific HTML elements should be
affected by a class. In the example below, only <p> elements with
class="center" will be center-aligned:
Example:
p.center {
text-align: center; color: red;
}
HTML elements can also refer to more than one class. In the
example below, the <p> element will be styled according to
class="center" and to class="large":
Example:
<p class="center large">This paragraph refers to two classes.</p>
Controlling Page Layout:
By default, HTML <div> sections will fill 100% of the web
page width, and stack up one on top of the other. It is highly unlikely
that this is how we want our page elements to be arranged; chances
are we want some sections arranged side by side, and using various
widths. For example we might want to have a main content area with
a menu down the left-hand side. Thankfully CSS makes this a simple
task. The first step is to understand the float property.

162
The CSS float Property:
The float property tells HTML elements how to arrange
themselves in relation to the other divs around them. We can specify
one of two values for the float property - left or right. If we tell a
<div> to float to the left, then it will shift itself as far left on the line
as it can go before bumping into another <div> section. If we tell an
element to float to the right it will shift as far right as it can? Let's
take a look at a working example; this will give us a good
visualization of how floating works. We'll begin by defining three
areas for our web page:
<div id="header">This is the page header</div>
<div id="menu">Menu links goes in here</div>
<div id="content">And finally the page content in here</div>
Now, what we want to do is to have the header take up the
whole of the top row, with the menu and content underneath,
arranged side by side. To do this we would use the following CSS
(the header section doesn't require any CSS):

#menu {
float: left;
}
#content {
float: left;
}
Using CSS to set HTML element widths:
One problem with arranging our HTML in this way is that the
<div> sections will size themselves automatically to fit the text
contained within them. This means that for a standard menu bar,
where we have lots of text that we want to contain in a narrow area,
we will end up with a very wide bar which will either squeeze the
163
content section into a small space, or ever push it onto another line.
We can fix this by specifying widths for our sections:
Example:
#menu {
float: left; width: 10em;
}
Widths can be specified in pixels, ems or as a percentage of the total
page width.
The CSS clear property
We have seen how we can position HTML elements next to
each other using CSS, but sometimes we might want an element to
appear beneath other elements. We can easily force an element to sit
below another using the clear property. When using clear, we can
tell an element to either clear those elements which are floated left,
those which are floated right, or both: Example:
#divname {
clear: left / right / both;
}
Changing Background:
The CSS background properties are used to define the background
effects for elements.
CSS background properties:
 background-color
 background-image
 background-repeat
 background-attachment
 background-position

164
Background Color
The background-color property specifies the background color of an
element. The background color of a page is set like this:
Example body {
background-color: lightblue;
}
With CSS, a color is most often specified by:
• A valid color name - like "red"
• A HEX value - like "#ff0000"
• An RGB value - like "rgb(255,0,0)"
Background Image:
The background-image property specifies an image to use as
the background of an element. By default, the image is repeated so
it covers the entire element. The background image for a page can
be set like this:
Example:
body {
background-image: url("paper.gif");
}
Background Image - Repeat Horizontally or Vertically:
By default, the background-image property repeats an image both
horizontally and vertically. Some images should be repeated only
horizontally or vertically, or they will look strange, like this:
Example:
body {
background-image: url("gradient_bg.png");
}

165
If the image above is repeated only horizontally (background-repeat:
repeat-x;), the
background will look better:
body {
background-image: url("gradient_bg.png"); background-repeat:
repeat-x;
}
Tip: To repeat an image vertically, set background-repeat: repeat-y;
Background Image - Set position and no-repeat:
Showing the background image only once is also specified by the
background-repeat property:
Example:
body {
background-image: url("img_tree.png"); background-repeat: no-
repeat;
}
In the example above, the background image is shown in the
same place as the text. We
want to change the position of the image, so that it does not disturb
the text too much. The position of the image is specified by the
background-position property:
Example:
body {
background-image: url("img_tree.png"); background-repeat: no-
repeat; background-position: right top;
}

166
Background Image - Fixed position
To specify that the background image should be fixed (will not scroll
with the rest of the page), use the background-attachment property:
Example:
body {
background-image: url("img_tree.png"); background-repeat: no-
repeat; background-position: right top; background-attachment:
fixed;
}
Controlling borders of the HTML elements using CSS:
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).

167
Example:
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;}
The border-width property specifies the width of the four borders.
The width can be set as a specific size (in px, pt, cm, em, etc) or by
using one of the three pre-defined values: thin, medium, or thick.
The border-width property can have from one to four values (for the
top border, right border, bottom border, and the left border).
Example
p.one {
border-style: solid; border-width: 5px;
}

p.two {
border-style: solid; border-width: medium;
}

p.three {
border-style: solid;
border-width: 2px 10px 4px 20px;
}
The border-color property is used to set the color of the four borders.
The color can be set by:
 name - specify a color name, like "red"
168
 Hex - specify a hex value, like "#ff0000"
 RGB - specify a RGB value, like "rgb(255,0,0)"
 transparent
The border-color property can have from one to four values (for the
top border, right border, bottom border, and the left border). If
border-color is not set, it inherits the color of the element.
Example
p.one {
border-style: solid; border-color: red;
}
p.two {
border-style: solid; border-color: green;
}
p.three {
border-style: solid;
border-color: red green blue yellow;
}
2.3(a) XML
XML stands for extensible markup language. XML is a
markup language much like HTML. XML was designed to carry
data, not to display data. XML tags are not predefined. You must
define your own tags. XML is designed to be self-descriptive. XML
is a w3c recommendation.
THE DIFFERENCE BETWEEN XML AND HTML:
XML is not a replacement for HTML. XML and HTML were
designed with different goals. XML was designed to transport and
store data, with focus on what data is. HTML was designed to
display data, with focus on how data looks. HTML is about
displaying information, while XML is about carrying information.
169
XML does not do anything: May be it is a little hard to understand,
but XML does not do anything. XML was created to structure, store,
and transport information. The following example is a note to
chythu, from ravi, stored as XML:
<note>
<to> chythu </to>
<from> ravi </from>
<heading>reminder</heading>
<body>don't forget me this weekend!</body>
</note>
The note above is quite self-descriptive. It has sender and
receiver information, it also has a heading and a message body. But
still, this XML document does not do anything. It is just information
wrapped in tags. Someone must write a piece of software to send,
receive or display it.
With XML you invent your own tags: The tags in the
example above (like <to> and <from>) are not defined in any XML
standard. These tags are "invented" by the author of the XML
document. That is because the XML language has no predefined
tags. The tags used in HTML are predefined. HTML documents can
only use tags defined in the HTML standard (like <p>, <h1>, etc.).
XML allows the author to define his/her own tags and his/her own
document structure. XML is not a replacement for HTML; XML is
a complement to HTML. It is important to understand that XML is
not a replacement for HTML. In most web applications, XML is
used to transport data, while HTML is used to format and display
the data.
My best description of XML is this: XML is a software- and
hardware-independent tool for carrying information. XML is a W3C
recommendation. XML became a W3C recommendation February
10, 1998. XML is everywhere. XML is now as important for the
web as HTML was to the foundation of the web. XML is the most
170
common tool for data transmissions between all sorts of
applications.
XML separates data from HTML: If you need to display
dynamic data in your HTML document, it will take a lot of work to
edit the HTML each time the data changes. With XML, data can be
stored in separate XML files. This way you can concentrate on using
HTML for layout and display, and be sure that changes in the
underlying data will not require any changes to the HTML. With a
few lines of JavaScript code, you can read an external XML file and
update the data content of your web page.
2.3(b) Unique Features of XML:
a) Sharing of data: In the real world, computer systems and
databases contain data in incompatible formats. XML data is
stored in plain text format. This provides a software-and
hardware-independent way of storing data. This makes it much
easier to create data that can be shared by different applications.
b) Transporting data: One of the most time-consuming challenges
for developers is to exchange data between incompatible
systems over the internet. Exchanging data as XML greatly
reduces this complexity, since the data can be read by different
incompatible applications.
c) Change of platform: Upgrading to new systems (hardware or
software platforms), is always time consuming. Large amounts
of data must be converted and incompatible data is often lost.
XML data is stored in text format. This makes it easier to expand
or upgrade to new operating systems, new applications, or new
browsers, without losing data.
d) Availability of data: Different applications can access your data,
not only in HTML pages, but also from XML data sources. With
XML, your data can be available to all kinds of "reading
machines" (handheld computers, voice machines, news feeds,
etc), and make it more available for blind people, or people with
other disabilities.
2.3(c)Structure of XML:
171
XML documents form a tree structure that starts at "the root" and
branches to "the leaves". An example of XML document is shown
below. XML documents use a self-describing and simple syntax:
<?XML version="1.0" encoding="iso-8859-1"?>
<note>
<to> Chythu </to>
<from> Ravi </from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The first line is the XML declaration. It defines the XML version
(1.0) and the encoding used (ISO-8859-1 = latin-1/west European
character set). The next line describes the root element of the
document (like saying: "This document is a note"):
<note>
The next 4 lines describe 4 child elements of the root (to, from,
heading, and body):
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
And finally the last line defines the end of the root element:
</note>
You can assume, from this example, that the XML document
contains a note to Tove from Jani. Don't you agree that XML is
pretty self-descriptive? XML documents form a tree structure XML
documents must contain a root element. This element is "the parent"
of all other elements. The elements in an XML document form a
document tree. The tree starts at the root and branches to the lowest
172
level of the tree. All elements can have sub elements (child
elements):
<root>
<child>
<subchild> </subchild>
</child>
</root>
The terms parent, child, and sibling are used to describe the
relationships between elements. Parent elements have children.
Children on the same level are called siblings (brothers or sisters).
All elements can have text content and attributes (just like in html).
Example:
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>giada de laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">harry potter</title>
<author>j k. rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">learning XML</title>
173
<author>erik t. ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The root element in the example is <bookstore>. All <book>
elements in the document are contained within <bookstore>. The
<book> element has 4 children: <title>, <author>,
<year>, and <price>.
XML syntax rules:
The syntax rules of XML are very simple and logical. The rules are
easy to learn, and easy to use. All XML elements must have a
closing tag. In HTML, Elements do not have to have a closing tag:
<p>this is a paragraph
<p>this is another paragraph
In XML, it is illegal to omit the closing tag. All elements must have
a closing tag:
<p>this is a paragraph</p>
<p>this is another paragraph</p>
Note: You might have noticed from the previous example that the
XML declaration did not have a closing tag. This is not an error. The
declaration is not a part of the XML document itself, and it has no
closing tag.
XML tags are case sensitive: The tag <letter> is different from the
tag <LETTER>. Opening and closing tags must be written with the
same case:
<Message>This is incorrect</MESSAGE>
<Message>This is correct</Message>

174
Note: "Opening and closing tags" are often referred to as "start and
end tags". Use whatever you prefer. It is exactly the same thing.
XML elements must be properly nested: In html, you might see
improperly nested elements:
<b><i>this text is bold and italic</b></i> <!--This is wrong--> In
XML, all elements must be properly nested within each other:
<b><i>this text is bold and italic</i></b>
In the example above, "properly nested" simply means that since the
<i> element is opened inside the <b> element, it must be closed
inside the <b> element.
XML documents must have a root element: XML documents must
contain one element that is the parent of all other elements. This
element is called the root element.
<root>
<child>
<subchild> </subchild>
</child>
</root>
XML attribute values must be quoted: XML elements can have
attributes in name/value pairs just like in html. In XML, the attribute
values must always be quoted. Study the two XML documents
below. The first one is incorrect, the second is correct:
• <note date=12/11/2007>
<to>tove</to>
<from>jani</from>
</note>
• <note date="12/11/2007">
<to>tove</to>

175
<from>jani</from>
</note>
The error in the first document is that the date attribute in the note
element is not quoted.
Entity References: Some characters have a special meaning in
XML. If you place a character like "<" inside an XML element, it
will generate an error because the parser interprets it as the start of
a new element. This will generate an XML error:
<message>if salary < 1000 then</message>
To avoid this error, replace the "<" character with an entity
reference:
<message>if salary &lt; 1000 then</message> There are 5
predefined entity references in XML:
&lt; < less than
&gt; > greater than
&amp; & ampersand
&apos; ' apostrophe
&quot; " quotation mark
Note: only the characters "<" and "&" are strictly illegal in XML.
the greater than character is legal, but it is a good habit to replace it.
Comments in XML: The syntax for writing comments in XML is
similar to that of html.
<!-- this is a comment -->
white-space is preserved in XML
HTML truncates multiple white-space characters to one single
white-space:
HTML: hello tove
Output: hello tove
176
With XML, the white-space in a document is not truncated.
XML stores new line as lf in windows applications, a new line is
normally stored as a pair of characters: carriage return (cr) and line
feed (lf). In UNIX applications, a new line is normally stored as an
lf character. Macintosh applications also use an lf to store a new line.
XML stores a new line as lf.
Basic Building Blocks of XML Documents:
All XML documents are made up the following four building
blocks:
i. Elements/Tags
ii. Attributes
iii. Entities
iv. Character Data
a. Parsed Character Data (PCDATA)
b. Unparsed Character Data (CDATA)
i) XML Elements/Tags:
An XML element is everything from (including) the element's start
tag to (including) the element's end tag. An element can contain:
other elements text, attributes or a mix of all of the above.
<bookstore>
<book category="children">
<title>harry potter</title>
<author>j k. rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>learning XML</title>
177
<author>erik t. ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
In the example above, <bookstore> and <book> have element
contents, because they contain other elements. <book> also has an
attribute (category="children"). <title>, <author>,
<year>, and <price> have text content because they contain text.
XML Naming Rules:
XML elements must follow these naming rules:
• Names can contain letters, numbers, and other characters
• Names cannot start with a number or punctuation character
• Names cannot start with the letters XML (or XML, or XML, etc)
• Names cannot contain spaces
• Any name can be used, no words are reserved.
Best Naming Practices:
Make names descriptive. Names with an underscore separator
are nice: <first_name>,
<last_name>.
• Names should be short and simple, like this:
<book_title> not like this:
• <the_title_of_the_book>.
• Avoid "-" characters. If you name something "first-name," some
software may think you want to subtract name from first.
• Avoid "." characters. If you name something "first.name," some
software may think that "name" is a property of the object "first."
• Avoid ":" characters. Colons are reserved to be used for
something called namespaces (more later).

178
• XML documents often have a corresponding database. a good
practice is to use the naming rules of your database for the
elements in the XML documents.
• Non-english letters like éòá are perfectly legal in XML, but
watch out for problems if your software vendor doesn't support
them.
XML Elements are Extensible:
XML elements can be extended to carry more information. look at
the following XML example:
<note>
<to>Chythu</to>
<from>Ravi</from>
<body>Don't forget me this weekend!</body>
</note>
Let‟s imagine that we created an application that extracted the <to>,
<from>, and <body> elements from the XML document to produce
this output:
Message to: Chythu from: Ravi
Don't forget me this weekend!
Imagine that the author of the XML document added some extra
information to it:
<note>
<date>2008-01-10</date>
<to>Chythu</to>
<from>Ravi</from>
<heading>reminder</heading>
<body>don't forget me this weekend!</body>
</note>
179
Should the application break or crash?
No, the application should still be able to find the <to>, <from>, and
<body> elements in the XML document and produce the same
output. One of the beauties of XML is that it can be extended
without breaking applications.
ii) XML Attributes:
XML elements can have attributes, just like html. Attributes provide
additional information about an element. In html, attributes provide
additional information about elements:
<img src="computer.gif">
<a href="demo.asp">
Attributes often provide information that is not a part of the data. In
the example below, the file type is irrelevant to the data, but can be
important to the software that wants to manipulate the element:
<file type="gif">computer.gif</file>
XML attributes must be quoted: Attribute values must always be
quoted. Either single or double quotes can be used. For a person's
sex, the person element can be written like this:
<person sex="female">
or like this:
<person sex='female'>
If the attribute value itself contains double quotes you can use single
quotes, like in this example:
<gangster name='george "shotgun" ziegler'> or you can use
character entities:
<gangster name="george &quot;shotgun&quot; ziegler">
XML Elements v/s Attributes:
Take a look at these examples:
• <person gender="male">
180
<firstname>Ravi</firstname>
<lastname>Chythanya</lastname>
</person>
• <person>
<gender>male</gender>
<firstname>Ravi</firstname>
<lastname>Chythanya</lastname>
</person>
In the first example gender is an attribute. In the next, gender
is an element. Both examples provide the same information. There
are no rules about when to use attributes or when to use elements.
Attributes are handy in html. In XML my advice is to avoid them.
Use elements instead.
My favorite way:
The following three XML documents contain exactly the same
information:
1) A date attribute is used in the first example:
<note date="10/01/2008">
<to>tove</to>
<from>jani</from>
<heading>reminder</heading>
<body>don't forget me this weekend!</body>
</note>
2) A date element is used in the second example:
<note>
<date>10/01/2008</date>
<to>tove</to>
181
<from>jani</from>
<heading>reminder</heading>
<body>don't forget me this weekend!</body>
</note>
3) An expanded date element is used in the third: (this is my
favorite):
<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>tove</to>
<from>jani</from>
<heading>reminder</heading>
<body>don't forget me this weekend!</body>
</note>
Avoid XML attributes?
Some of the problems with using attributes are:
• Attributes cannot contain multiple values (elements can)
• Attributes cannot contain tree structures (elements can)
• Attributes are not easily expandable (for future changes)
• Attributes are difficult to read and maintain. use elements for
data. use attributes for information that is not relevant to the data.
• Don't end up like this:
<note day="10" month="01" year="2008" to="tove" from="jani"
heading="reminder" body="don't forget me this weekend!">
</note>
182
XML attributes for metadata:
Sometimes ID references are assigned to elements. These IDs can
be used to identify XML elements in much the same way as the id
attribute in html. This example demonstrates this:
<messages>
<note id="501">
<to>tove</to>
<from>jani</from>
<heading>reminder</heading>
<body>don't forget me this weekend!</body>
</note>
<note id="502">
<to>jani</to>
<from>tove</from>
<heading>re: reminder</heading>
<body>i will not</body>
</note>
</messages>
The ID attributes above are for identifying the different notes.
It is not a part of the note itself. What I'm trying to say here is that
metadata (data about data) should be stored as attributes, and the
data itself should be stored as elements.
iii) XML Entities:
An entity is the symbolic representation of some information.
It references the data that look like an abbreviation or can be found
at an external location. Entities reduce the redundant information
and also allow for easier editing. The entities can be internal or

183
external. For example, the entity „&amp;‟ will replace as „&‟,
where ever it is found in the XML document.
iv) PCDATA:
PCDATA stands for Parsed Character Data. The text enclosed
between starting and ending tag is known as Character Data. The
parser parses the PCDATA and identifies the entities as well as
markup. Markups include the tags inside the text and entities are
expanded. In the case of Parsed Character Data, the symbols „&‟,
„<‟, „>‟ are represented using entities.
v) CDATA:
CDATA stands for Character Data and it is not parsed by the
parser. The tags inside the text are not considered as markup and the
entities are not expanded.
Validation of XML:
There are two levels of correctness of an XML document:
1) XML with correct syntax is Well Formed XML.
2) XML validated against a DTD is Valid XML.
A Well Formed XML document is a document that conforms to the
XML syntax rules like:
• XML documents must have a root element.
• XML elements must have a closing tag.
• XML tags are case sensitive.
• XML elements must be properly nested.
• XML attribute values must be quoted
Example:
<?XML version="1.0" encoding="iso-8859-1"?>
<note>
<to>tove</to>
<from>jani</from>

184
<heading>reminder</heading>
<body>don't forget me this weekend!</body>
</note>
A Valid XML document is a “well formed” XML document, which
conforms to the rules of a document type definition (DTD).
2.3(d) Document Type Definition (DTD):
The purpose of a DTD is to define the structure of an XML
document. It defines the structure with a list of legal elements:
DTD Syntax:
<!DOCTYPE DOCUMENT [
<!ELEMENT ELEMENT_NAME1 (Attribute Names) Appearance
of attributes>
<!ELEMENT ELEMENT_NAME2>
<!ELEMENT ELEMENT_NAME3>
.
.
.
<!ELEMENT ELEMENT_NAMEn>
<!ATTLIST Element_name Attribute_name Attribute_type
Default_value>
]>
A DTD can be declared inline inside an XML document, or as an
external reference.
Internal DTD Declaration:
If the DTD is declared inside the XML file, it should be wrapped in
DOCTYPE definition as in the following example:
<!DOCTYPE note[
185
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#CDATA)>
]>
<note>
<to>Ravi</to>
<from>Chythanya</from>
<heading>Message</heading>
<body>Welcome to the XML with DTD</body>
</note>
The DTD above is interpreted like this:
• !DOCTYPE note defines that the root element of this document
is note.
• !ELEMENT note defines that the note element contains four
elements “to, from, heading, body”.
• !ELEMENT to defines that to element to be of the type
#PCDATA.
• !ELEMENT from defines that from element to be of the type
#PCDATA.
• !ELEMENT heading defines that heading element to be of the
type #PCDATA.
• !ELEMENT body defines that body element to be of the type
#CDATA.
External DTD Declaration:
If the DTD is declared in an external file, it should be wrapped in a
DOCTYPE definition with the following syntax:
<!DOCTYPE DOCUMENT SYSTEM “File_Name.dtd”>
186
Example: emailDTD.xml:
<?xml version=”1.0”?>
<!DOCTYPE note SYSTEM “emailDTD.dtd”>
<note>
<to>Ravi</to>
<from>Chythanya</from>
<heading>Message</heading>
<body>Welcome to the XML with DTD</body>
</note>
emailDTD.dtd:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#CDATA)>
2.3(e) XML Schema:
W3C supports an XML-based alternative to DTD, called XML
schema:
1) The XML schema is used to represent the structure of XML
document. The goal or purpose of XML schema is to define the
building blocks of an XML document. These can be used as an
alternative to XML DTD. The XML schema language is called
as XML Schema Definition (XSD) language. The XML schema
became the World Wide Web Consortium (W3C)
recommendation in 2001.
2) XML schema defines elements, attributes, elements having child
elements, order of child elements. It also defines fixed and
default values of elements and attributes.

187
3) XML schema also allows the developers to use data types.
4) File extension of XML schema is “.xsd” i.e., Filename.xsd
Ex:
StudentSchema.xsd:
<?XML version=”1.0”?>
<xs:schema XMLns:xs=“http://www.w3.org/2001/XMLschema”>
<xs:element name="student">
<xs:complextype>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="std" type="xs:string"/>
<xs:element name="marks" type="xs:string"/>
</xs:sequence>
</xs:complextype>
</xs:element>
</xs:schema>

188
XML Document (myschema.XML):
<?xml version="1.0" encoding="iso-8859-1" ?>
<student XMLns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "studentschema.xsd">
<name>anand</name>
<address>knr</address>
<std>second</std>
<marks>70percent</marks>
</student>
Data Types in XML:
Various data types are that can be used to specify the data types of
an elements are:
• String
• Date
• Time
• Numeric
• Boolean
1. String Data Type:
The string data type can be used to define the elements containing
the characters lines, tabs, white spaces, or special characters.
Example:
XML Schema [stringType.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “StudentName” type=“xs:string”>
</xs:schema>

189
XML Document[stringTypeDemo.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<StudentName XMLns:xsi =
"http://www.w3.org/2001/XMLschema-instance"
xsi:nonamespaceschemalocation = "stringType.xsd">
Ravi Chythanya
</StudentName>
2. Date Data Type:
For specifying the date we use date data type. The format of date is
yyyy-mm-dd, where yyyy denotes the Year, mm denotes the month
and dd specifies the day.
Example:
XML Schema [dateType.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “DOB” type=“xs:date”>
</xs:schema>
XML Document[dateTypeDemo.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<DOB XMLns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "dateType.xsd">
1988-03-01
</DOB>
3. Time Data Type:
For specifying the time we use time data type. The format of date is
hh:mm:ss, where hh denotes the Hour, mm denote the minutes and
ss specify the seconds.

190
Example:
XML Schema [timeType.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “MyTime” type=“xs:time”>
</xs:schema>
XML Document[timeTypeDemo.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<MyTime XMLns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "timeType.xsd">
01:57:03
</MyTime>
4. Numeric Data Type:
If we want to use numeric value for some element then we can use
the data types as either
“decimal” or “integer”. Example:
XML Schema [decimalType.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “Percentage” type=“xs:decimal”>
</xs:schema>
XML Document[decimalTypeDemo.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<Percentage XMLns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "decimalType.xsd">
99.99

191
</Percentage>
XML Schema [integerType.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “Age” type=“xs:integer”>
</xs:schema>
XML Document[integerTypeDemo.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<Age XMLns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "integerType.xsd">
30
</Age>
5. Boolean Data Type:
For specifying either true or false values we must use the Boolean
data type.
Example:
XML Schema [booleanType.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “Flag” type=“xs:boolean”>
</xs:schema>
XML Document[booleanTypeDemo.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<Flag XMLns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "booleanType.xsd">
true

192
</Flag>
Simple Types:
XML defines the simple type which contains only text and does not
contain any other element or attributes. But the text appears for
element comes along with some type. The syntax is:
<xs:element name= “element_name” type= “data_type”> Here the
type can be any built in data type:
• xs:string
• xs:date
• xs:time
• xs:integer
• xs:decimal
• xs:Boolean
Restrictions on Simple Types:
For an XML document, it is possible to put certain restrictions on its
contents. These restrictions are called as facets.
XML Schema [Month.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “Month”>
<xs:simpleType>
<xs:restriction base= “xs:integer”>
<xs:minInclusive value= “1”>
<xs:maxInclusive value= “12”>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:schema>
193
XML Document[MonthDemo.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<Age xmlns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "Month.xsd">
12
</Month>
Various facets that can be applied are:
• length – Specifies exact number of characters.
• minLength – Specifies the minimum number of characters
allowed.
• maxLength – Specifies the minimum number of characters
allowed.
• minInclusive – Specifies lower bound for numeric values.
• minExclusive – Specifies lower bound for numeric values.
• maxInclusive – Specifies upper bound for numeric values.
• maxExclusive – Specifies upper bound for numeric values.
• enumeration – A list of acceptable values can be defined.
• pattern – specifies exact sequence of characters that are
acceptable.
• totalDigits – Specifies the exact number of digits.
• fractionDigits – Specifies maximum number of decimal places
allowed.
• whiteSpace – Specifies how to handle white spaces. The white
spaces can be spaces, tags, line feed, or carriage return.
Complex Types:
1) Elements:
Complex elements are the elements that contain some other
elements or attributes. The complex types of elements are:
i) Empty Elements
ii) Elements that contain text
iii) Elements that contain other elements

194
iv) Elements that contain other text as well other elements
Restrictions that can be applied on the data types are:
string date numeric boolean
enumeratio enumeration enumeration enumeration
n
Length maxExclusiv fractionDigits length
e
minLength maxInclusive maxExclusive maxLength
maxLength minExclusive maxInclusive minLength
Pattern minInclusive minExclusive pattern
whiteSpace pattern minInclusive whiteSpaces
s
whiteSpaces totalDigits
whiteSpaces

i) Empty Elements:
Let us define the empty elements by the complexType.
Example [Student.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “Student”>
<xs:complexType>
<xs:attribute name= “HTNo” type= “xs:integer”>
</xs:complexType>
</xs:element>
</xs:schema>
XML Document[Student.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>

195
<Student xmlns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "Student.xsd"
HTNo="1343">
</Student>
ii) Elements that contain text only:
We have the elements that contain simple contents such as text
and attributes. Hence we must add the type as simpleContent in the
schema definition. This simpleContent element must have either
extension or restriction.
Example [Student.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “Student”>
<xs:complexType>
<xs:simpleContent>
<xs:extension base= “xs:integer”>
<xs:attribute name= “HTNo” type= “xs:integer”>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
XML Document[Student.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<Student xmlns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "Student.xsd"
HTNo="1343">

196
100
</Student>
iii) Elements that contain other elements only: Example
[Student.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>
<xs:element name= “Student”>
<xs:complexType>
<xs:sequence>
<xs:element name= “firstName” type= “xs:string”>
<xs:element name= “lastName” type= “xs:string”>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML Document[Student.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<Student xmlns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "Student.xsd">
<firstName>Ravi</firstName>
<lastName>Chythanya</lastName>
</Student>
iv) Elements that contain text as well as other elements:
Example [Student.xsd]:
<?xml version= “1.0” ?>
<xs:schema xmlns:xs=“ http://www.w3.org/2001/XMLschema”>

197
<xs:element name= “Student”>
<xs:complexType mixed= “true”>
<xs:sequence>
<xs:element name= “Name” type= “xs:string”>
<xs:element name= “HTNo” type= “xs:integer”>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML Document[Student.xml]:
<?xml version="1.0" encoding="iso-8859-1" ?>
<Student xmlns:xsi = "http://www.w3.org/2001/XMLschema-
instance" xsi:nonamespaceschemalocation = "Student.xsd">
My Dear Student <Name>Ravi</Name>
With Hall Ticket Number <HTNo>0536</HTNo>
</Student>
2) Indicators:
Indicators allow us to define the elements in the manner we want.
Following are some indicators that are available in XML Schema.
a. all
b. choice
c. sequence
d. maxOccurs
e. minOccurs

198
2.4(a)DHTML :
DHTML stands for Dynamic Hypertext Markup language i.e.,
Dynamic HTML.
Dynamic HTML is not a markup or programming language but it is
a term that combines the features of various web development
technologies for creating the web pages dynamic and interactive.
The DHTML application was introduced by Microsoft with the
release of the 4th version of IE (Internet Explorer) in 1997.
Components of Dynamic HTML
DHTML consists of the following four components or languages:
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
HTML is a client-side markup language, which is a core
component of the DHTML. It defines the structure of a web page
with various defined basic elements or tags.
CSS
CSS stands for Cascading Style Sheet, which allows the web
users or developers for controlling the style and layout of the HTML
elements on the web pages.
JavaScript
JavaScript is a scripting language which is done on a client-
side. The various browser supports JavaScript technology. DHTML
uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are
the commands which tell the browser for performing an action.

199
DOM
DOM is the document object model. It is a w3c standard,
which is a standard interface of programming for HTML. It is
mainly used for defining the objects and properties of all elements
in HTML.
Uses of DHTML
Following are the uses of DHTML (Dynamic HTML):
o It is used for designing the animated and interactive web pages
that are developed in real-time.
o DHTML helps users by animating the text and images in their
documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down
menus or rollover buttons.
o This term is also used to create various browser-based action
games.
o It is also used to add the ticker on various websites, which needs
to refresh their content automatically.
Features of DHTML
Following are the various characteristics or features of DHTML
(Dynamic HTML):
o Its simplest and main feature is that we can create the web page
dynamically.
o Dynamic Style is a feature, that allows the users to alter the font,
size, color, and content of a web page.
o It provides the facility for using the events, methods, and
properties. And, also provides the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their
web sites or web pages.
o With the help of DHTML, users can easily change the tags and
their properties.

200
o The web page functionality is enhanced because the DHTML
uses low-bandwidth effect.
Difference between HTML and DHTML
Following table describes the differences between HTML and
DHTML:

HTML (Hypertext DHTML (Dynamic


Markup language) Hypertext Markup
language)

1. HTML is simply a 1. DHTML is not a


markup language. language, but it is a set of
technologies of web
development.

2. It is used for developing 2. It is used for creating


and creating web pages. and designing the
animated and interactive
web sites or pages.

3. This markup language 3. This concept creates


creates static web pages. dynamic web pages.

4. It does not contain any 4. It may contain the code


server-side scripting code. of server-side scripting.

5. The files of HTML are 5. The files of DHTML


stored with the .html or .htm are stored with the .dhtm
extension in a system. extension in a system.

6. A simple page which is 6. A page which is


created by a user without created by a user using
using the scripts or styles the HTML, CSS, DOM,
called as an HTML page. and JavaScript
technologies called a
DHTML page.

7. This markup language 7. This concept needs


does not need database database connectivity
201
connectivity. because it interacts with
users.

DHTML JavaScript
JavaScript can be included in HTML pages, which creates the
content of the page as dynamic. We can easily type the JavaScript
code within the <head> or <body> tag of a HTML page. If we want
to add the external source file of JavaScript, we can easily add using
the <src> attribute.
Following are the various examples, which describes how to
use the JavaScript technology with the DHTML:
Document.write() Method
The document.write() method of JavaScript, writes the output to a
web page.
Example 1: The following example simply uses the
document.write() method of JavaScript in the DHTML. In this
example, we type the JavaScript code in the <body> tag.
<HTML>
<head>
<title>
Method of a JavaScript
</title>
</head>
<body>
<script type="text/javascript">
document.write("JavaTpoint");
</script>
</body>
202
</html>
Output:

JavaScript and HTML event


A JavaScript code can also be executed when some event
occurs. Suppose, a user clicks an HTML element on a webpage, and
after clicking, the JavaScript function associated with that HTML
element is automatically invoked. And, then the statements in the
function are performed.
Example 1: The following example shows the current date and time
with the JavaScript and HTML event (Onclick). In this example, we
type the JavaScript code in the <head> tag.
<html>
<head>
<title>
DHTML with JavaScript
</title>
<script type="text/javascript">

203
function dateandtime()
{
alert(Date());
}
</script>
</head>
<body bgcolor="orange">
<font size="4" color="blue">
<center> <p>
Click here # <a href="#" onClick="dateandtime();"> Date and Time
</a>
# to check the today's date and time.
</p> </center>
</font>
</body>
</html>
Output:

204
Explanation:
In the above code, we displayed the current date and time with
the help of JavaScript in DHTML. In the body tag, we used the
anchor tag, which refers to the page itself. When you click on the
link, then the function of JavaScript is called.
In the JavaScript function, we use the alert() method in which we
type the date() function. The date function shows the date and time
in the alert dialog box on the web page.
JavaScript and HTML DOM
With version 4 of HTML, JavaScript code can also change the inner
content and attributes of the HTML event.
Example 1: This example checks the Grade of a student according
to the percentage criteria with the JavaScript and HTML DOM. In
this example, we type the code of a JavaScript in the <body> tag.
<html>
<head>
<title> Check Student Grade
</title>
</head>

<body>
<p>Enter the percentage of a Student:</p>
<input type="text" id="percentage">
<button type="button" onclick="checkGrade()">
Find Grade
</button>
<p id="demo"></p>
<script type="text/javascript">
205
function checkGrade() {
var x,p, text;
p = document.getElementById("percentage").value;

x=parseInt(p);

if (x>90 && x <= 100) {


document.getElementById("demo").innerHTML = "A1";
} else if (x>80 && x <= 90) {
document.getElementById("demo").innerHTML = "A2";
} else if (x>70 && x <= 80) {
document.getElementById("demo").innerHTML = "A3";
}
}
</script>
</body>
</html>
Output:

206
Explanation:
In the above code, we check the student’s Grade with the help
of JavaScript in DHTML. In the JavaScript code, we used the
checkGrade() method, which is invoked when we click on the
button. In this function, we stored the value in variable p. The value
is taken in the input field. When the value is stored, then we convert
the value of p into integer and store the conversion value in x,
because the value in p is text.
After that, we used the if-else-if statement for finding the grade
according to the percentage.
CSS with JavaScript in DHTML
With version 4 of HTML, JavaScript code can also change the style
such as size, color, and face of an HTML element.
Example 1: The following example changes the color of a text.
<html>
<head>
<title>
getElementById.style.property example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the
following different buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">
function change_Color(newColor) {

207
var element = document.getElementById('demo').style.color =
newColor;
}
</script>
</body>
</html>
Output:

Explanation:
In the above code, we changed the color of a text by using the
following syntax:
1. document.getElementById('demo').style.property=new_value;.
The above syntax is used in the JavaScript function, which is
performed or called when we clicked on the HTML buttons. The
different HTML buttons specify the color of a text.

208
DHTML CSS
We can easily use the CSS with the DHTML page with the help of
JavaScript and HTML DOM. With the help of
this.style.property=new style statement, we can change the style of
the currently used HTML element. Or, we can also update the style
of any particular HTML element by
document.getElementById(id).style.property = new_style
statement.
Example 1: The following example uses the DHTML CSS for
changing the style of current element:
<html>
<head>
<title>
Changes current HTML element
</title>
</head>
<body>
<center>
<h1 onclick="this.style.color='blue'"> This is a JavaTpoint Site
</h1>
<center>
</body>
</html>
Output:

209
Explanation:
In the above code, we used the this.style.color='blue' statement,
which shows the color of a text as blue.
Example 2: The following example uses the DHTML CSS for
changing the style of the HTML element:
<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the
following different buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
210
<script type="text/javascript">
function change_Color(newColor) {
var element = document.getElementById('demo').style.color =
newColor;
}
</script>
</body>
</html>
Output:

Explanation:
In the above code, we used the var element =
document.getElementById('demo').style.color = newColor;
statement, which changes the color of a text as green and blue
according to the buttons.
DHTML Events
An event is defined as changing the occurrence of an object.
211
It is compulsory to add the events in the DHTML page. Without
events, there will be no dynamic content on the HTML page. The
event is a term in the HTML, which triggers the actions in the web
browsers.
Suppose, any user clicks an HTML element, then the JavaScript
code associated with that element is executed. Actually, the event
handlers catch the events performed by the user and then execute the
code.
Example of events:

S.No. Event When it occurs

1. onabort It occurs when the user aborts


the page or media file loading.

2. onblur It occurs when the user leaves


an HTML object.

3. onchange It occurs when the user changes


or updates the value of an
object.

4. onclick It occurs or triggers when any


user clicks on an HTML
element.

5. ondblclic It occurs when the user clicks


k on an HTML element two times
together.

6. onfocus It occurs when the user focuses


on an HTML element. This
event handler works opposite to
onblur.

7. onkeydo It triggers when a user is


wn pressing a key on a keyboard
device. This event handler
works for all the keys.

212
8. onkeypre It triggers when the users press
ss a key on a keyboard. This event
handler is not triggered for all
the keys.

9. onkeyup It occurs when a user released a


key from a keyboard after
pressing on an object or
element.

10. onload It occurs when an object is


completely loaded.

11. onmouse It occurs when a user presses


down the button of a mouse over an
HTML element.

12. onmouse It occurs when a user moves the


move cursor on an HTML object.

13. onmouse It occurs when a user moves the


over cursor over an HTML object.

14. onmouse It occurs or triggers when the


out mouse pointer is moved out of
an HTML element.

15. onmouse It occurs or triggers when the


up mouse button is released over
an HTML element.

16. onreset It is used by the user to reset the


form.

17. onselect It occurs after selecting the


content or text on a web page.

18. onsubmit It is triggered when the user


clicks a button after the
submission of a form.

19. onunload It is triggered when the user


closes a web page.

213
Following are the different examples using the different event
handlers, which helps us to understand the concept of DHTML
events:
Example 1: This example uses the onclick event handler, which is
used to change the text after clicking.
<html>
<head>
<title>
Example of onclick event
</title>
<script type="text/javascript">
function ChangeText(ctext)
{
ctext.innerHTML=" Hi JavaTpoint! ";
}
</script>
</head>
<body>
<font color="red"> Click on the Given text for changing it: <br>
</font>
<font color="blue">
<h1 onclick="ChangeText(this)"> Hello World! </h1>
</font>
</body>
</html>

214
Output:

Example 2: This example uses the onsubmit event handler, which


gives an alert after clicking on a submit button.
<html>
<head>
<title>
Example of onsubmit event
</title>
</head>
<body>
<form onsubmit="Submit_Form()">
<label> Enter your name: </label>
<input type="text">
<label> Enter your Roll no: </label>
<input type="Number">
<input type="submit" value="submit">
215
</form>
<script type="text/javascript">
function Submit_Form()
{
alert(" Your form is submitted");
}
</script>
</body>
</html>
Output:

DHTML DOM
DHTML DOM stands for Dynamic HTML Document Object
Model.
It is a w3c standard, which is a standard interface of programming
for HTML. It is mainly used for defining the objects and properties
of all elements in HTML. It also defines the methods for accessing
the HTML elements.

216
Example: The following program helps in understanding the
concept of DHTML DOM. This example changes the color of text
and displays the text in red colour automatically.
<html>
<head>
<title>
Example of DHTML DOM
</title>
</head>
<body>
<font color = "blue">
<p id="demo"> This text changes color when the page loaded.
</p>
</font>
<script type="text/javascript">
document.getElementById('demo').style.color = "red";
</script>
</body>
</html>

Output:

217
Advantages of DHTML
Following are the various benefits or the advantages of DHTML
(Dynamic HTML):
o Those web sites and web pages which are created using this
concept are fast.
o There is no plug-in required for creating the web page
dynamically.
o Due to the low-bandwidth effect by the dynamic HTML, the
web page functionality is enhanced.
o This concept provides advanced functionalities than the static
HTML.
o It is highly flexible, and the user can make changes easily in the
web pages.
Disadvantages of DHTML
Following are the various disadvantages or limitations of DHTML
(Dynamic HTML):
o The scripts of DHTML does not run properly in various web
browsers. Or in simple words, we can say that various web
218
browsers do not support the DHTML. It is only supported by
the latest browsers.
o The coding of those websites that are created using DHTML is
long and complex.
o For understanding the DHTML, users must know about HTML,
CSS, and JavaScript. If any user does not know these
languages, then it is a time-consuming and long process in
itself.
***

219
Chapter - 3
Java script and Networking

3.1(a) Javascript:
JavaScript is an object-based scripting language which is
lightweight and cross-platform.JavaScript is not a compiled
language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the
JavaScript code for the web browser.
Intruduction
JavaScript (js) is a light-weight object-oriented programming
language which is used by several websites for scripting the
webpages. It is an interpreted, full-fledged programming language
that enables dynamic interactivity on websites when applied to an
HTML document. It was introduced in the year 1995 for adding
programs to the webpages in the Netscape Navigator browser. Since
then, it has been adopted by all other graphical web browsers. With
JavaScript, users can build modern web applications to interact
directly without reloading the page every time. The traditional
website uses js to provide several forms of interactivity and
simplicity.Although, JavaScript has no connectivity with Java
programming language. The name was suggested and provided in
the times when Java was gaining popularity in the market. In
addition to web browsers, databases such as CouchDB and
MongoDB uses JavaScript as their scripting and query language.
Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide
built-in execution environments.

220
2. JavaScript follows the syntax and structure of the C
programming language. Thus, it is a structured programming
language.
3. JavaScript is a weakly typed language, where certain types are
implicitly cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses
prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including,
Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into
existence. In the year 1994, Netscape was founded by Marc
Andreessen. He realized that the web needed to become more
dynamic. Thus, a 'glue language' was believed to be provided to
HTML to make web designing easy for designers and part-time
programmers. Consequently, in 1995, the company recruited
Brendan Eich intending to implement and embed Scheme
programming language to the browser. But, before Brendan could
start, the company merged with Sun Microsystems for adding Java
into its Navigator so that it could compete with Microsoft over the
web technologies and platforms. Now, two languages were there:
Java and the scripting language. Further, Netscape decided to give a
similar name to the scripting language as Java's. It led to 'Javascript'.
Finally, in May 1995, Marc Andreessen coined the first code of
Javascript named 'Mocha'. Later, the marketing team replaced the
name with 'LiveScript'. But, due to trademark reasons and certain
other reasons, in December 1995, the language was finally renamed
to 'JavaScript'. From then, JavaScript came into existence.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used
for:
221
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert
dialog box, confirm dialog box and prompt dialog box),
o Displaying clocks etc.
Example
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>
Output
Welcome to JavaScript
Hello JavaScript by JavaScript
JavaScript Example
Javascript example is easy to code. JavaScript provides 3 places to
put the JavaScript code: within body tag, within head tag and
external JavaScript file.
3 Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

222
1) JavaScript Example : code between the body tag
In the above example, we have displayed the dynamic content using
JavaScript. Let’s see the simple example of JavaScript that displays
alert dialog box.
<html>
<body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
</html>
2) JavaScript Example : code between the head tag
Let’s see the same example of displaying alert dialog box of
JavaScript that is contained inside the head tag.
In this example, we are creating a function msg(). To create function
in JavaScript, you need to write function with function_name as
given below.
To call function, you need to work on event. Here we are using
onclick event to call msg() function.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>

223
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
External JavaScript file
We can create external JavaScript file and embed it in many html
page.
It provides code re usability because single JavaScript file can be
used in several html pages.
An external JavaScript file must be saved by .js extension. It is
recommended to embed all JavaScript files into a single file. It
increases the speed of the webpage.
Let's create an external JavaScript file that prints Hello Javatpoint in
a alert dialog box.
message.js
function msg(){
alert("Hello Javatpoint");
}
Let's include the JavaScript file into html page. It calls the JavaScript
function on button click.
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>

224
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Advantages of External JavaScript
There will be following benefits if a user creates an external
javascript:
1. It helps in the reusability of code in more than one HTML file.
2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files,
which further reduces the page loading time.
4. It enables both web designers and coders to work with html and
js files parallelly and separately, i.e., without facing any code
conflictions.
5. The length of the code reduces as only we need to specify the
location of the js file.
Disadvantages of External JavaScript
There are the following disadvantages of external files:
1. The stealer may download the coder's code using the url of the
js file.
2. If two js files are dependent on one another, then a failure in one
file may affect the execution of the other dependent file.
3. The web browser needs to make an additional http request to get
the js code.
4. A tiny to a large change in the js code may cause unexpected
results in all its dependent files.
225
5. We need to check each file that depends on the commonly
created external javascript file.
6. If it is a few lines of code, then better to implement the internal
javascript code.
Types of JavaScript Comments
There are two types of comments in JavaScript.
Single-line Comment
It is represented by double forward slashes (//). It can be used before
and after the statement.
Multi-line Comment
It is represented by forward slash with asterisk then asterisk with
forward slash. For example:
/* your code here */
JavaScript Variable
A JavaScript variable is simply a name of storage location. There
are two types of variables in JavaScript : local variable and global
variable.
There are some rules while declaring a JavaScript variable (also
known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _
), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X
are different variables.
Example
var x = 10;
var _value="sonoo";

226
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A
variable i.e. declared outside the function or declared with window
object is known as global variable. For example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Javascript Data Types
JavaScript provides different data types to hold different types of
values. There are two types of data types in JavaScript.
1. Primitive data type
227
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to
specify type of the variable because it is dynamically used by
JavaScript engine. You need to use var here to specify the data type.
It can hold any type of values such as numbers, strings etc. For
example:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are
as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types

228
The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access


members

Array represents group of similar values

RegExp represents regular expression

3.1(b) JavaScript Operators:


JavaScript operators are symbols that are used to perform operations
on operands. For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on
the operands. The following operators are known as JavaScript
arithmetic operators.

229
Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus 20%10 = 0
(Remainder)

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands.
The comparison operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

230
> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The
bitwise operators are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift (10>>>2) = 2


with Zero

231
JavaScript Logical Operators
The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment
operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


232
The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition.


It is like if-else.

, Comma Operator allows multiple expressions to be


evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's


iterator.

JavaScript If-else
The JavaScript if-else statement is used to execute the code
whether condition is true or false. There are three forms of if
statement in JavaScript.
1. If Statement
2. If else statement
233
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of
JavaScript if statement is given below.
if(expression){
//content to be evaluated
}
Let’s see the simple example of if statement in javascript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output of the above example
value of a is greater than 10
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax
of JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

234
Let’s see the example of if-else statement in JavaScript to find out
the even or odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several
expressions. The signature of JavaScript if else if statement is given
below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}

235
else{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
JavaScript Switch
The JavaScript switch statement is used to execute one code from
multiple expressions. It is just like else if statement that we have
learned in previous page. But it is convenient than if..else..if because
it can be used with numbers, characters etc.
The signature of JavaScript switch statement is given below.
switch(expression){

236
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;

237
default:
result="No Grade";
}
document.write(result);
</script>
Output of the above example
B Grade
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for,
while, do while or for-in loops. It makes the code compact. It is
mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1) JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number
of times. It should be used if number of iteration is known. The
syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
Let’s see the simple example of for loop in javascript.
<script>
for (i=1; i<=5; i++)

238
{
document.write(i + "<br/>")
}
</script>

Output:
1
2
3
4
5
2) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite
number of times. It should be used if number of iteration is not
known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
239
}
</script>
Output:
11
12
13
14
15
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite
number of times like while loop. But, code is executed at least once
whether condition is true or false. The syntax of do while loop is
given below.
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21

240
22
23
24
3.1(c) JavaScript Functions:
JavaScript functions are used to perform operations. We can call
JavaScript function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save
coding.
2. Less coding: It makes our program compact. We don’t need to
write many lines of code each time to perform a common task.
JavaScript Function Syntax
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Functions can have 0 or more arguments.
JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not
has arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
241
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example
of function that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value
We can call function that returns a value and use it in our program.
Let’s see the example of function that returns value.
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello javatpoint! How r u?

242
JavaScript Function Object
In JavaScript, the purpose of Function constructor is to create a new
Function object. It executes the code globally. However, if we call
the constructor directly, a function is created dynamically but in an
unsecured way.
Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
functionBody - It represents the function definition.
JavaScript Function Methods
Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a


single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and


an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1
Let's see an example to display the sum of given numbers.
<script>
var add=new Function("num1","num2","return num1+num2");
243
document.writeln(add(2,5));
</script>
Output:
7
Example 2
Let's see an example to display the power of provided value.
<script>
var pow=new Function("num1","num2","return
Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>
Output:
8
3.2(a) JavaScript Objects:
A javaScript object is an entity having state and behavior (properties
and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.
JavaScript is an object-based language. Everything is an object in
JavaScript.
JavaScript is template based not class based. Here, we don't create
class to get the object. But, we direct create objects
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

244
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
OUTPUT:
102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";

245
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>

OUTPUT:
101 Ravi Malik 50000
3) By using an Object constructor
Here, you need to create function with arguments. Each argument
value can be assigned in the current object by using this keyword.
The this keyword refers to the current object.0
The example of creating object by object constructor is given below.
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
246
OUTPUT:
103 Vimal Jaiswal 30000
Defining method in JavaScript Object
We can define method in JavaScript object. But before
defining method, we need to add property in the function with same
name as method.
The example of defining method in object is given below.
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
247
OUTPUT:
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
3.2(b) 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).
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>

248
Output of the above example
Sonoo
Vimal
Ratan
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.
<html>
<body>
<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>
</body>
</html>
Output of the above example
Arun

249
Varun
John
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.
<html>
<body>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Output of the above example
Jai
Vijay
Smith

250
JavaScript Array Methods

Methods Description

concat() It returns a new array object that contains two


or more merged arrays.

copywithin() It copies the part of the given array with its own
elements and returns the modified array.

entries() It creates an iterator object and a loop that


iterates over each key/value pair.

every() It determines whether all the elements of an


array are satisfying the provided function
conditions.

flat() It creates a new array carrying sub-array


elements concatenated recursively till the
specified depth.

flatMap() It maps all array elements via mapping


function, then flattens the result into a new
array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy


of another array element.

filter() It returns the new array containing the elements


that pass the provided function conditions.

find() It returns the value of the first element in the


given array that satisfies the specified
condition.

findIndex() It returns the index value of the first element in


the given array that satisfies the specified
condition.

251
forEach() It invokes the provided function once for each
element of an array.

includes() It checks whether the given array contains the


specified element.

indexOf() It searches the specified element in the given


array and returns the index of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only


the keys of the array, then loops through these
keys.

lastIndexOf() It searches the specified element in the given


array and returns the index of the last match.

map() It calls the specified function for every array


element and returns the new array

of() It creates a new array from a variable number


of arguments, holding any type of argument.

pop() It removes and returns the last element of an


array.

push() It adds one or more elements to the end of an


array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value


initial) from left to right and reduces the array to a
single value.

reduceRight() It executes a provided function for each value


from right to left and reduces the array to a
single value.
252
some() It determines if any element of the array passes
the test of the implemented function.

shift() It removes and returns the first element of an


array.

slice() It returns a new array containing the copy of


the part of the given array.

sort() It returns the element of the given array in a


sorted order.

splice() It add/remove elements to/from the given


array.

toLocaleString() It returns a string containing all the elements of


a specified array.

toString() It converts the elements of a specified array


into string form, without affecting the original
array.

unshift() It adds one or more elements in the beginning


of the given array.

values() It creates a new iterator object carrying values


for each index in the array.

3.2(c)JavaScript Form:
In this tutorial, we will learn, discuss, and understand the JavaScript
form. We will also see the implementation of the JavaScript form
for different purposes.
Here, we will learn the method to access the form, getting elements
as the JavaScript form's value, and submitting the form.
Introduction to Forms

253
Forms are the basics of HTML. We use HTML form element in
order to create the JavaScript form. For creating a form, we can use
the following sample code:
<html>
<head>
<title> Login Form</title>
</head>
<body>
<h3> LOGIN </h3>
<formform ="Login_form" onsubmit="submit_form()">
<h4> USERNAME</h4>
<input type="text" placeholder="Enter your email id"/>
<h4> PASSWORD</h4>
<input type="password" placeholder="Enter your
password"/></br></br>
<input type="submit" value="Login"/>
<input type="button" value="SignUp" onClick="create()"/>
</form>
</html>
In the code:
o Form name tag is used to define the name of the form. The name
of the form here is "Login_form". This name will be referenced
in the JavaScript form.
o The action tag defines the action, and the browser will take to
tackle the form when it is submitted. Here, we have taken no
action.
o The method to take action can be either post or get, which is used
when the form is to be submitted to the server. Both types of
methods have their own properties and rules.
254
o The input type tag defines the type of inputs we want to create
in our form. Here, we have used input type as 'text', which means
we will input values as text in the textbox.
o Net, we have taken input type as 'password' and the input value
will be password.
o Next, we have taken input type as 'button' where on clicking, we
get the value of the form and get displayed.
o Other than action and methods, there are the following useful
methods also which are provided by the HTML Form Element
o submit (): The method is used to submit the form.
o reset (): The method is used to reset the form values.
Referencing forms
Now, we have created the form element using HTML, but we also
need to make its connectivity to JavaScript. For this, we use the
getElementById () method that references the html form element to
the JavaScript code.
The syntax of using the getElementById() method is as follows:
let form = document.getElementById('subscribe');
Using the Id, we can make the reference.
Submitting the form
Next, we need to submit the form by submitting its value, for which
we use the onSubmit() method. Generally, to submit, we use a
submit button that submits the value entered in the form.
The syntax of the submit() method is as follows:
<input type="submit" value="Subscribe">
When we submit the form, the action is taken just before the request
is sent to the server. It allows us to add an event listener that enables
us to place various validations on the form. Finally, the form gets
ready with a combination of HTML and JavaScript code.
Let's collect and use all these to create a Login form and SignUp
form and use both.
255
Login Form
<html>
<head>
<title> Login Form</title>
</head>
<body>
<h3> LOGIN </h3>
<formform ="Login_form" onsubmit="submit_form()">
<h4> USERNAME</h4>
<input type="text" placeholder="Enter your email id"/>
<h4> PASSWORD</h4>
<input type="password" placeholder="Enter your
password"/></br></br>
<input type="submit" value="Login"/>
<input type="button" value="SignUp" onClick="create()"/>
</form>
<script type="text/javascript">
function submit_form(){
alert("Login successfully");
}
function create(){
window.location="signup.html";
}
</script>
</body>
</html>
256
The output of the above code on clicking on Login button is shown
below:

SignUp Form
<html>
<head>
<title> SignUp Page</title>
</head>
<body align="center" >
<h1> CREATE YOUR ACCOUNT</h1>
<table cellspacing="2" align="center" cellpadding="8"
border="0">
<tr><td> Name</td>
<td><input type="text" placeholder="Enter your name"
id="n1"></td></tr>
<tr><td>Email </td>
<td><input type="text" placeholder="Enter your email id"
id="e1"></td></tr>
<tr><td> Set Password</td>
257
<td><input type="password" placeholder="Set a password"
id="p1"></td></tr>
<tr><td>Confirm Password</td>
<td><input type="password" placeholder="Confirm your
password" id="p2"></td></tr>
<tr><td>
<input type="submit" value="Create"
onClick="create_account()"/>
</table>
<script type="text/javascript">
function create_account(){
var n=document.getElementById("n1").value;
var e=document.getElementById("e1").value;
var p=document.getElementById("p1").value;
var cp=document.getElementById("p2").value;
//Code for password validation
var letters = /^[A-Za-z]+$/;
var email_val = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-
])+\.)+([a-zA-Z0-9]{2,4})+$/;
//other validations required code
if(n==''||e==''||p==''||cp==''){
alert("Enter each details correctly");
}
else if(!letters.test(n))
{
alert('Name is incorrect must contain alphabets only');
}
258
else if (!email_val.test(e))
{
alert('Invalid email format please enter valid email id');
}
else if(p!=cp)
{
alert("Passwords not matching");
}
else if(document.getElementById("p1").value.length > 12)
{
alert("Password maximum length is 12");
}
else if(document.getElementById("p1").value.length < 6)
{
alert("Password minimum length is 6");
}
else{
alert("Your account has been created successfully... Redirecting to
JavaTpoint.com");
window.location="https://www.javatpoint.com/";
}
}
</script>
</body>
</html>
The output of the above code is shown below:
259
3.2(d) AJAX:
AJAX stands for asynchronous Javascript and XML. AJAX is
not a programming language or technology, but it is a combination
of multiple web-related technologies like HTML, XHTML, CSS,
JavaScript, DOM, XML, XSLT and XMLHttpRequest object. The
AJAX model allows web developers to create web applications that
are able to dynamically interact with the user. It will also be able to
quickly make a background call to web servers to retrieve the
required application data. Then update the small portion of the web
page without refreshing the whole web page.
AJAX applications are much more faster and responsive as
compared to traditional web applications. It creates a great balance
between the client and the server by allowing them to communicate
in the background while the user is working in the foreground.
In the AJAX applications, the exchange of data between a web
browser and the server is asynchronous means AJAX applications
submit requests to the web server without pausing the execution of
the application and can also process the requested data whenever it
is returned. For example, Facebook uses the AJAX model so

260
whenever we like any post the count of the like button increase
instead of refreshing the whole page.
Working of AJAX
Traditional web applications are created by adding loosely
web pages through links in a predefined order. Where the user can
move from one page to another page to interact with the different
portions of the applications. Also, HTTP requests are used to submit
the web server in response to the user action. After receiving the
request the web server fulfills the request by returning a new
webpage which, then displays on the web browser. This process
includes lots of pages refreshing and waiting.

AJAX change this whole working model by sharing the


minimum amount of data between the web browser and server
asynchronously. It speedup up the working of the web applications.
It provides a desktop-like feel by passing the data on the web pages
or by allowing the data to be displayed inside the existing web
application. It will replace loosely integrated web pages with tightly
integrated web pages. AJAX application uses the resources very
well. It creates an additional layer known as AJAX engine in
between the web application and web server due to which we can
make background server calls using JavaScript and retrieve the
required data, can update the requested portion of a web page
without casing full reload of the page. It reduces the page refresh
timing and provides a fast and responsive experience to the user.
Asynchronous processes reduce the workload of the web server by
dividing the work with the client computer. Due to the reduced
workload web servers become more responsive and fast.
261
AJAX Technologies
The technologies that are used by AJAX are already implemented
in all the Morden browsers. So the client does not require any extra
module to run the AJAX application.The technologies used by
AJAX are −
• Javascript − It is an important part of AJAX. It allows you to
create client-side functionality. Or we can say that it is used to
create AJAX applications.
• XML − It is used to exchange data between web server and
client.
• The XMLHttpRequest − It is used to perform asynchronous
data exchange between a web browser and a web server.
• HTML and CSS − It is used to provide markup and style to the
webpage text.
• DOM − It is used to interact with and alter the webpage layout
and content dynamically.
Advantages of AJAX
The following are the advantages of AJAX −
• It creates responsive and interactive web applications.
• It supports the development of patterns and frameworks that
decrease the development time.
• It makes the best use of existing technology and feature instead
of using some new technology.

262
• It makes an asynchronous call to the web server which means
the client doesn't have to wait for the data to arrive before
starting rendering.
Disadvantages of AJAX
The following are the disadvantages of AJAX −
• AJAX is fully dependent on Javascript. So if anything happens
with javascript in the browser AJAX will not support.
• The debugging of AJAX applications is difficult.
• Bookmarking of AJAX-enabled pages required pre-planning.
• If one request can fail then it can fail the load of the whole
webpage.
• If JavaScript is disabled in your web browser then you are not
able to run the AJAX webpage.
3.3(a) Internet Protocol Address:
All the computers of the world on the Internet network
communicate with each other with underground or underwater
cables or wirelessly. If I want to download a file from the internet or
load a web page or literally do anything related to the internet, my
computer must have an address so that other computers can find and
locate mine in order to deliver that particular file or webpage that I
am requesting. In technical terms, that address is called IP Address
or Internet Protocol Address.
Let us understand it with another example, like if someone
wants to send you a mail then he/she must have your home address.
Similarly, your computer too needs an address so that other
computers on the internet can communicate with each other without
the confusion of delivering information to someone else’s computer.
And that is why each computer in this world has a unique IP
Address. Or in other words, an IP address is a unique address that is
used to identify computers or nodes on the internet. This address is
just a string of numbers written in a certain format. It is generally
expressed in a set of numbers for example 192.155.12.1. Here each
number in the set is from 0 to 255 range. Or we can say that a full
263
IP address ranges from 0.0.0.0 to 255.255.255.255. And these IP
addresses are assigned by IANA(known as Internet Corporation For
Internet Assigned Numbers Authority).
But what is Internet protocol? This is just a set of rules that
makes the internet work. You are able to read this article because
your computer or phone has a unique address where the page that
you requested (to read this article from GeeksforGeeks) has been
delivered successfully.
Working of IP addresses
ADVERTISING
The working of IP addresses is similar to other languages. It can also
use some set of rules to send information. Using these protocols we
can easily send, and receive data or files to the connected devices.
There are several steps behind the scenes. Let us look at them
• Your device directly requests your Internet Service Provider
which then grants your device access to the web.
• And an IP Address is assigned to your device from the given
range available.
• Your internet activity goes through your service provider, and
they route it back to you, using your IP address.
• Your IP address can change. For example, turning your router
on or off can change your IP Address.
• When you are out from your home location your home IP
address doesn’t accompany you. It changes as you change the
network of your device.

264
Types of IP Address
IP Address is of two types:
1. IPv4: Internet Protocol version 4. It consists of 4 numbers
separated by the dots. Each number can be from 0-255 in decimal
numbers. But computers do not understand decimal numbers, they
instead change them to binary numbers which are only 0 and 1.
Therefore, in binary, this (0-255) range can be written as (00000000
– 11111111). Since each number N can be represented by a group
of 8-digit binary digits. So, a whole IPv4 binary address can be
represented by 32-bits of binary digits. In IPv4, a unique sequence
of bits is assigned to a computer, so a total of (2^32) devices
approximately = 4,294,967,296 can be assigned with IPv4.
IPv4 can be written as:
189.123.123.90
Classes of IPv4 Address: There are around 4.3 billion IPv4
addresses and managing all those addresses without any scheme is
next to impossible. Let’s understand it with a simple example. If you
have to find a word from a language dictionary, how long will it
take? Usually, you will take less than 5 minutes to find that word.
You are able to do this because words in the dictionary are organized
in alphabetical order. If you have to find out the same word from a
dictionary that doesn’t use any sequence or order to organize the
words, it will take an eternity to find the word. If a dictionary with
one billion words without order can be so disastrous, then you can
imagine the pain behind finding an address from 4.3 billion
addresses. For easier management and assignment IP addresses are
organized in numeric order and divided into the following 5 classes

Address
IP Class Range Maximum number of networks

Class
1-126 126 (27-2)
A

265
Address
IP Class Range Maximum number of networks

Class
128-191 16384
B

Class
192-223 2097152
C

Class
224-239 Reserve for multitasking
D

Reserved for Research and


Class E 240-254
development

The 0.0.0.0 is a Non-routable address is that indicates an


invalid, or inapplicable end-user address.
A loopback address is a distinct reserved IP address range that
starts from 127.0.0.0 ends at 127.255.255.255 though
127.255.255.255 is the broadcast address for 127.0.0.0/8. The
loopback addresses are built into the IP domain system, enabling
devices to transmit and receive the data packets. The loopback
address 127.0.0.1 is generally known as localhost.
2. IPv6: But, there is a problem with the IPv4 address. With
IPv4, we can connect only the above number of 4 billion devices
uniquely, and apparently, there are much more devices in the world
to be connected to the internet. So, gradually we are making our way
to IPv6 Address which is a 128-bit IP address. In human-friendly
form, IPv6 is written as a group of 8 hexadecimal numbers separated
with colons(:). But in the computer-friendly form, it can be written
as 128 bits of 0s and 1s. Since, a unique sequence of binary digits is
given to computers, smartphones, and other devices to be connected
to the internet. So, via IPv6 a total of (2^128) devices can be
266
assigned with unique addresses which are actually more than
enough for upcoming future generations.
IPv6 can be written as:
2011:0bd9:75c5:0000:0000:6b3e:0170:8394
Classification of IP Address
An IP address is classified into the following types:
1. Public IP Address: This address is available publicly and it is
assigned by your network provider to your router, which further
divides it to your devices. Public IP Addresses are of two types,
• Dynamic IP Address: When you connect a smartphone or
computer to the internet, your Internet Service Provider provides
you an IP Address from the range of available IP Addresses.
Now, your device has an IP Address and you can simply connect
your device to the Internet and send and receive data to and from
your device. The very next time when you try to connect to the
internet with the same device, your provider provides you with
different IP Addresses to the same device and also from the same
available range. Since IP Address keeps on changing every time
when you connect to the internet, it is called a Dynamic IP
Address.
• Static IP Address: Static address never changes. They serve as a
permanent internet address. These are used by DNS servers.
What are DNS servers? Actually, these are computers that help
you to open a website on your computer. Static IP Address
provides information such as device is located on which
continent, which country, which city, and which Internet Service
Provider provides internet connection to that particular device.
Once, we know who is the ISP, we can trace the location of the
device connected to the internet. Static IP Addresses provide less
security than Dynamic IP Addresses because they are easier to
track.

267
2. Private IP Address: This is an internal address of your device
which are not routed to the internet and no exchange of data can take
place between a private address and the internet.
3. Shared IP addresses: Many websites use shared IP addresses
where the traffic is not huge and very much controllable, they decide
to rent it to other similar websites so to make it cost-friendly. Several
companies and email sending servers use the same IP address
(within a single mail server) to cut down the cost so that they could
save for the time the server is idle.
4. Dedicated IP addresses: A dedicated IP Address is an address
used by a single company or an individual which gives them certain
benefits using a private Secure Sockets Layer (SSL) certificate
which is not in the case of a shared IP address. It allows to access
the website or log in via File Transfer Protocol (FTP) by IP address
instead of its domain name. It increases the performance of the
website when the traffic is high. It also protects from a shared IP
address that is black-listed due to spam.
3.3(b) InetAddress class:
Java InetAddress class represents an IP address. The
java.net.InetAddress class provides methods to get the IP of any host
name for example www.javatpoint.com, www.google.com,
www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number.
An instance of InetAddress represents the IP address with its
corresponding host name. There are two types of addresses: Unicast
and Multicast. The Unicast is an identifier for a single interface
whereas Multicast is an identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful
and unsuccessful host name resolutions.

268
Factory InetAddress Class Methods

Method Description

public static InetAddress It returns the instance of


getByName(String host) InetAddress containing
throws LocalHost IP and name.
UnknownHostException

public static InetAddress It returns the instance of


getLocalHost() throws InetAdddress containing local
UnknownHostException host name and address.

public String getHostName() It returns the host name of the


IP address.

public String getHostAddress() It returns the IP address in


string format.
Example of Java InetAddress Class
Let's see a simple example of InetAddress class to get ip address of
www.javatpoint.com website.
InetDemo.java
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
269
}
Output:
Host Name: www.javatpoint.com
IP Address: 172.67.196.82
3.3(c) Instance Methods in Java:
Instance Methods are the group of codes that performs a particular
task. Sometimes the program grows in size, and we want to separate
the logic of the main method from other methods. A method is a
function written inside the class. Since java is an object-oriented
programming language, we need to write a method inside some
classes.
The important points regarding instance variables are:
1. Instance methods can access instance variables and instance
methods directly and undeviatingly.
2. Instance methods can access static variables and static methods
directly.
Instance Method without parameter
Syntax:
modifier return_type method_name( )
{
method body ;
}
• modifier: It defines the access type of the method, and it is
optional to use.
• return_type: Method may return a value. Ex:- int, void, String,
char, float, etc.
• method_name: This is the method name you can write anything
as you write the variable name.
• method body: The method body describes what the method does
with statements.
270
Example:
public void disp( )
{
int a= 10;
System.out.println(a);
}
Calling Instance Method:
You can not call an instance method in the static method
directly, so the Instance method can be invoked using an object of
the class. We know that the java program’s execution starts from the
main method and the main method is static, so we can not directly
call the instance method. We have to create the class object; then,
we can call the instance method in the main method.
Let’s see how we can call the Instance method:
Example 1:
// Java program to see how can we call
// an instance method without parameter

import java.io.*;

class GFG {
// static method
public static void main (String[] args) {

// Creating object of the class


GFG obj = new GFG();

271
// Calling instance method
obj.disp();

System.out.println("GFG!");
}

// Instance method
void disp()
{
// Local variable
int a = 20;
System.out.println(a);
}
}
Output
20
GFG!
3.4(a) TCP/IP:
The OSI Model we just looked at is just a reference/logical
model. It was designed to describe the functions of the
communication system by dividing the communication procedure
into smaller and simpler components.
TCP/IP was designed and developed by the Department of
Defense (DoD) in the 1960s and is based on standard protocols. It
stands for Transmission Control Protocol/Internet Protocol. The
TCP/IP model is a concise version of the OSI model. It contains four
layers, unlike the seven layers in the OSI model.

272
The number of layers is sometimes referred to as five or four.
Here In this article, we’ll study five layers. The Physical Layer and
Data Link Layer are referred to as one single layer as the ‘Physical
Layer’ or ‘Network Interface Layer’ in the 4-layer reference.
What Does TCP/IP Do?
The main work of TCP/IP is to transfer the data of a computer
from one device to another. The main condition of this process is to
make data reliable and accurate so that the receiver will receive the
same information which is sent by the sender. To ensure that, each
message reaches its final destination accurately, the TCP/IP model
divides its data into packets and combines them at the other end,
which helps in maintaining the accuracy of the data while
transferring from one end to another end.
What is the Difference between TCP and IP?
TCP and IP are different protocols of Computer Networks.
The basic difference between TCP (Transmission Control Protocol)
and IP (Internet Protocol) is in the transmission of data. In simple
words, IP finds the destination of the mail and TCP has the work to
send and receive the mail. UDP is another protocol, which does not
require IP to communicate with another computer. IP is required by
only TCP. This is the basic difference between TCP and IP.
How Does the TCP/IP Model Work?
Whenever we want to send something over the internet using
the TCP/IP Model, the TCP/IP Model divides the data into packets
at the sender’s end and the same packets have to be recombined at
the receiver’s end to form the same data, and this thing happens to
maintain the accuracy of the data. TCP/IP model divides the data
into a 4-layer procedure, where the data first go into this layer in one
order and again in reverse order to get organized in the same way at
the receiver’s end.

273
Layers of TCP/IP Model
1. Application Layer
2. Transport Layer(TCP/UDP)
3. Network/Internet Layer(IP)
4. Data Link Layer (MAC)
5. Physical Layer
The diagrammatic comparison of the TCP/IP and OSI model is as
follows:

TCP/IP and OSI


1. Physical Layer
It is a group of applications requiring network
communications. This layer is responsible for generating the data
and requesting connections. It acts on behalf of the sender and the
Network Access layer on the behalf of the receiver. During this
article, we will be talking on the behalf of the receiver.
2. Data Link Layer
The packet’s network protocol type, in this case, TCP/IP, is
identified by the data-link layer. Error prevention and “framing” are
also provided by the data-link layer. Point-to-Point Protocol (PPP)

274
framing and Ethernet IEEE 802.2 framing are two examples of data-
link layer protocols.
3. Internet Layer
This layer parallels the functions of OSI’s Network layer. It
defines the protocols which are responsible for the logical
transmission of data over the entire network. The main protocols
residing at this layer are as follows:
• IP: IP stands for Internet Protocol and it is responsible for
delivering packets from the source host to the destination host
by looking at the IP addresses in the packet headers. IP has 2
versions: IPv4 and IPv6. IPv4 is the one that most websites are
using currently. But IPv6 is growing as the number of IPv4
addresses is limited in number when compared to the number of
users.
• ICMP: ICMP stands for Internet Control Message Protocol. It
is encapsulated within IP datagrams and is responsible for
providing hosts with information about network problems.
• ARP: ARP stands for Address Resolution Protocol. Its job is to
find the hardware address of a host from a known IP address.
ARP has several types: Reverse ARP, Proxy ARP, Gratuitous
ARP, and Inverse ARP.
4. Transport Layer
The TCP/IP transport layer protocols exchange data receipt
acknowledgments and retransmit missing packets to ensure that
packets arrive in order and without error. End-to-end
communication is referred to as such. Transmission Control
Protocol (TCP) and User Datagram Protocol are transport layer
protocols at this level (UDP).
• TCP: Applications can interact with one another using TCP as
though they were physically connected by a circuit. TCP
transmits data in a way that resembles character-by-character
transmission rather than separate packets. A starting point that
establishes the connection, the whole transmission in byte order,
275
and an ending point that closes the connection make up this
transmission.
• UDP: The datagram delivery service is provided by UDP, the
other transport layer protocol. Connections between receiving
and sending hosts are not verified by UDP. Applications that
transport little amounts of data use UDP rather than TCP
because it eliminates the processes of establishing and validating
connections.
5. Application Layer
This layer is analogous to the transport layer of the OSI model.
It is responsible for end-to-end communication and error-free
delivery of data. It shields the upper-layer applications from the
complexities of data. The three main protocols present in this layer
are:
• HTTP and HTTPS: HTTP stands for Hypertext transfer
protocol. It is used by the World Wide Web to manage
communications between web browsers and servers. HTTPS
stands for HTTP-Secure. It is a combination of HTTP with
SSL(Secure Socket Layer). It is efficient in cases where the
browser needs to fill out forms, sign in, authenticate, and carry
out bank transactions.
• SSH: SSH stands for Secure Shell. It is a terminal emulations
software similar to Telnet. The reason SSH is preferred is
because of its ability to maintain the encrypted connection. It
sets up a secure session over a TCP/IP connection.
• NTP: NTP stands for Network Time Protocol. It is used to
synchronize the clocks on our computer to one standard time
source. It is very useful in situations like bank transactions.
Assume the following situation without the presence of NTP.
Suppose you carry out a transaction, where your computer reads
the time at 2:30 PM while the server records it at 2:28 PM. The
server can crash very badly if it’s out of sync.
The host-to-host layer is a layer in the OSI (Open Systems
Interconnection) model that is responsible for providing
276
communication between hosts (computers or other devices) on a
network. It is also known as the transport layer.
Some common use cases for the host-to-host layer include:
1. Reliable Data Transfer: The host-to-host layer ensures that
data is transferred reliably between hosts by using techniques
like error correction and flow control. For example, if a packet
of data is lost during transmission, the host-to-host layer can
request that the packet be retransmitted to ensure that all data
is received correctly.
2. Segmentation and Reassembly: The host-to-host layer is
responsible for breaking up large blocks of data into smaller
segments that can be transmitted over the network, and then
reassembling the data at the destination. This allows data to be
transmitted more efficiently and helps to avoid overloading the
network.
3. Multiplexing and Demultiplexing: The host-to-host layer is
responsible for multiplexing data from multiple sources onto a
single network connection, and then demultiplexing the data
at the destination. This allows multiple devices to share the
same network connection and helps to improve the utilization
of the network.
4. End-to-End Communication: The host-to-host layer provides
a connection-oriented service that allows hosts to
communicate with each other end-to-end, without the need for
intermediate devices to be involved in the communication.
3.4(b) TCP/IP Client Server Sockets:
TCP/IP sockets are used to implement reliable two-way,
persistent, point-to-point streaming connections between hosts on
the Internet. The Java I/O system can use sockets to connect to other
programs on the local system or on other systems on the Internet. It
is important to note that the applet establishes a reverse socket
connection to the host on which the applet is loaded. This restriction
exists because it is dangerous for applets loaded through a firewall
to access arbitrary systems. There are two types of TCP sockets in
277
Java.One for the server and one for the client. The ServerSocket
class is designed as a "listener", waiting for a client to connect before
doing anything. So ServerSocket is for servers. The Socket class is
for clients. It is designed to connect to a server socket and initiate a
protocol exchange. This is because client sockets are most
commonly used in Java applications. Creating a Socket object
implicitly establishes a connection between the client and server.
There is no method or constructor that explicitly exposes details
about setting up this connection.
Here are the two constructors used to create a client socket:
1. Socket(String hostName, int port) throws
UnknownHostException, IOException: Creates a socket
connected to the specified host and port.
2. Socket(InetAddress ipAddress, int port) throws IOException:
Creates a socket using a pre-existing InetAddress object and a
port.
Socket defines multiple instance methods. For example, a Socket
can always check for associated address and port information using
the following methods:
1. InetAddress getInetAddress( ): It returns the InetAddress
associated with the Socket object. It returns null if the socket
is not connected.
2. int getPort( ): It returns the remote port to which the invoking
Socket object is connected. It returns 0 if the socket is not
connected.
3. int getLocalPort( ): Returns the local port to which the
invoking Socket object is bound. It returns -1 if the socket is
not bound.
4. InputStream getInputStream( ) throws IOException: Returns
the InputStream associated with the invoking socket.
5. OutputStream getOutputStream( ) throws IOException:
Returns the OutputStream associated with the invoking socket.
6. connect( ): Allows you to specify a new connection

278
7. isConnected( ): Returns true if the socket is connected to a
server
8. isBound( ): Returns true if the socket is bound to an address
9. isClosed( ): Returns true if the socket is closed.
3.4(c) URL: Uniform Resource Locator:
URL stands for Uniform Resource Locator. It is the address of a
resource, which can be a specific webpage or a file, on the internet.
It is also known as web address when it is used with http. It was
created in 1994 by Tim Berners-Lee. URL is a specific character
string that is used to access data from the World Wide Web. It is a
type of URI (Uniform Resource Identifier).
Every URL contains the following information:
o The scheme name or protocol.
o A colon, two slashes.
o A host, normally called a domain name but sometimes as a literal
IP address.
o A colon followed by a port number.
o Full path of the resource.
The URL of a web page is displayed above on the page in the
address bar. A typical URL looks like this:
http://www.javatpoint.com/full-form
The above URL contains:
o protocol: http
o host or domain: www.javatpoint.com
o Path of the resource: /full-form
A URL can be entered manually by typing it in the address bar
of your web browser. If the URL does not contain a valid server, a
browser may display a "Server not found" error and if the path in the
URL is incorrect, the browser may display a "404 error". A URL
does not contain spaces and uses forward slashes to represent
different directories. So, dashes and underscores are used separate
the words of a web address.
279
URI
URI stands for Uniform Resource Identifier. It is a generic
term for all the name and addresses which show objects on the
World Wide Web. It is generally a sequence of characters which
identifies a logical resource or the name and location of a file or
resource in a uniform format.
A URI can be of two types: Uniform Resource Locator (URL) and
Uniform Resource Names (URNs). It enables resources to be
accessed by other computers across a network or over the World
Wide Web.
3.4(d) Java URLConnection Class:
The Java URLConnection class represents a communication link
between the URL and the application. It can be used to read and
write data to the specified resource referred by the URL.
What is the URL?
o URL is an abbreviation for Uniform Resource Locator. An URL
is a form of string that helps to find a resource on the World
Wide Web (WWW).
o URL has two components:
1. The protocol required to access the resource.
2. The location of the resource.
Features of URLConnection class
1. URLConnection is an abstract class. The two subclasses
HttpURLConnection and JarURLConnection makes the
connetion between the client Java program and URL resource
on the internet.
2. With the help of URLConnection class, a user can read and write
to and from any resource referenced by an URL object.
3. Once a connection is established and the Java program has an
URLConnection object, we can use it to read or write or get
further information like content length, etc.

280
Constructors

Constructor Description

1) protected It constructs a URL connection


URLConnection(URL url) to the specified URL.

URLConnection Class Methods

Method Description

void It adds a general request


addRequestProperty(String property specified by a key-
key, String value) value pair

void connect() It opens a communications link


to the resource referenced by this
URL, if such a connection has
not already been established.

boolean It returns the value of the


getAllowUserInteraction() allowUserInteraction field for
the object.

int getConnectionTimeout() It returns setting for connect


timeout.

Object getContent() It retrieves the contents of the


URL connection.

Object getContent(Class[] It retrieves the contents of the


classes) URL connection.

281
3.5(a) Datagram Sockets:
Datagram sockets allow processes to use UDP for
communication. Datagram sockets support bidirectional message
flow. It is a connection-less socket. A process on a datagram socket
may receive messages in a different order than the order in which
they are sent, and may receive duplicate messages. The record
boundaries of the data are preserved. The socket type is
SOCK_DGRAM.TCP/IP-style networking is appropriate for most
networking needs. It provides a serialized, predictable, reliable
stream of packet data. This is not without its cost, however. TCP
incorporates many state-of-the-art algorithms to deal with
congestion control on crowded networks, as well as pessimistic
expectations about packet loss. This leads to a somewhat inefficient
way to transport data. Datagrams provide an alternative.
Datagrams are vast amounts of information that is transmitted
between machines. Once the datagram has been released for its
intended purpose, there is no guarantee that it will arrive or even that
someone will be there to catch it. Similarly, when the datagram is
received, there is no guarantee that it hasn't been damaged in transit
or that anyone who sent it is still there to get a response.Java
implements datagrams on top of the UDP protocol by using two
classes: the DatagramPacket object is the data container, while the
DatagramSocket is the mechanism used to send or receive the
DatagramPackets.
DatagramSocket
DatagramSocket defines four public constructors. They are shown
here:
o DatagramSocket( ) throws SocketException- Creates a
Datagram socket bound to any unused port on the local
computer.
o DatagramSocket(int port) throws SocketException- Creates a
DatagramSocket bound to the port specified by the port.

282
o DatagramSocket(int port, InetAddress ipAddress) throws
SocketException- Constructs a DatagramSocket bound to the
specified port and InetAddress.
o DatagramSocket(SocketAddress address) throws
SocketException- Constructs a DatagramSocket bound to the
specified SocketAddress. SocketAddress is an abstract class that
is implemented by the concrete class InetSocketAddress.
InetSocketAddress encapsulates an IP address with a port
number. All can throw a SocketException if an error occurs
while creating the socket.
***

283
Chapter - 4
Enterprise Java Beans

4.1(a) Java Beans:


JavaBeans is a portable, platform-independent model written
in Java Programming Language. Its components are referred to as
beans. In simple terms, JavaBeans are classes which encapsulate
several objects into a single object. It helps in accessing these object
from multiple places. JavaBeans contains several elements like
Constructors, Getter/Setter Methods and much more.
JavaBeans has several conventions that should be followed:
• Beans should have a default constructor (no arguments)
• Beans should provide getter and setter methods
o A getter method is used to read the value of a readable property
o To update the value, a setter method should be called
• Beans should implement java.io.serializable, as it allows to save,
store and restore the state of a JavaBean you are working on
• Now that you are familiar with basics, let’s learn in detail about
the properties of JavaBeans.
4.1(b) Java Bean Properties:
A JavaBean property can be accessed by the user of the object. The
feature can be of any Java data type, containing the classes that you
define. It may be of the following mode: read, write, read-only, or
write-only. JavaBean features are accessed through two methods:
1. get Employee Name ()
For example, if the employee name is firstName, the method name
would be getFirstName() to read that employee name. This method
is known as an accessor. Properties of getter methods are as follows:
1. Must be public in nature
2. Return-type should not be void
284
3. The getter method should be prefixed with the word get
4. It should not take any argument
2.setEmployeeName ()
For example, if the employee name is firstName, the method
name would be setFirstName() to write that employee name. This
method is known as a mutator. Properties of setter methods:
1. Must be public in nature
2. Return-type should be void
3. The setter method has to be prefixed with the word set
4. It should take some argument
Now that you have attained some theoretical knowledge about
JavaBeans, let us move on and understand the implementation
process.
4.1(c) Writing a Simple Bean:
In this section you will learn more about Beans and the BeanBox by
• Creating a simple Bean
• Compiling and saving the Bean into a Java Archive (JAR) file
• Loading the Bean into the ToolBox
• Dropping a Bean instance into the BeanBox
• Inspecting the Bean's properties, methods, and events
• Generating an introspection report
Your Bean will be named SimpleBean. Here are the steps to create
it and view it in the BeanBox:
1. Write the SimpleBean code. Put it in a file named
SimpleBean.java, in the directory of your choice. Here's the code:
import java.awt.*;
import java.io.Serializable;
public class SimpleBean extends Canvas
implements Serializable
{
285
//Constructor sets inherited properties
public SimpleBean(){
setSize(60,40);
setBackground(Color.red);
}
}
SimpleBean extends the java.awt.Canvas component. SimpleBean
also implements the java.io.Serializable interface, a requirement for
all Beans. SimpleBean sets the background color and component
size.
Make sure the CLASSPATH environment variable is set to point to
all needed .class (or .jar) files. Here are some URLs that will help
you to set CLASSPATH correctly:
a. The Managing Source and Class Files lesson gives good
advice on how and when to set your CLASSPATH.
b. The JDK Tool Reference Page provides complete
CLASSPATH information for both Windows and Solaris platforms.
2.Compile the Bean: javac SimpleBean.java
This produces the class file SimpleBean.class
3.Create a manifest file.
Use your favorite text editor to create a file, we'll call it
manifest.tmp, that contains the following text:
Name: SimpleBean.class Java-Bean: True
4.Create the JAR file.
The JAR file will contain the manifest and the SimpleBean class
file:
jar cfm SimpleBean.jar manifest.tmp SimpleBean.class

286
5.Load the JAR file into the ToolBox. Select the File|LoadJar...
menu item. This will bring up a file browser. Navigate to the
SimpleBean.jar location and select it. SimpleBean will appear at the
bottom of the ToolBox. (Note that when the BeanBox is started, all
Beans in JAR files in the beans/jars directory are automatically
loaded into the ToolBox).
6.Drop a SimpleBean instance into the BeanBox. Click on the
word SimpleBean in the ToolBox. The cursor will change to a
crosshair. Move the cursor to a spot within the BeanBox and click.
SimpleBean will appear as a painted rectangle with a hatched
border. This border means that SimpleBean is selected. The
SimpleBean properties will appear in the Properties sheet.
4.1(d)Advantages of JavaBeans:
The following list enumerates some of the benefits of
JavaBeans:
Portable
JavaBeans components are built purely in Java, hence are fully
portable to any platform that supports the Java Run-Time
Environment. All platform specifics, as well as support for
JavaBeans, are implemented by the Java Virtual Machine.
Compact and Easy
JavaBeans components are simple to create and easy to use.
This is an important focus sector of the JavaBeans architecture. It
doesn’t take much effort to write a simple Bean. Also, a bean is
lightweight, so, it doesn’t have to carry around a lot of inherited
baggage to support the Beans environment.
Carries the Strengths of the Java Platform
JavaBeans is pretty compatible, there isn’t any new complicated
mechanism for registering components with the run-time system.

287
Disadvantages of JavaBeans
1. JavaBeans are mutable, hence lack the advantages offered by
immutable objects.
2. JavaBeans will be in inconsistent state partway through its
construction.
Manifest File
The manifest is a special file named `MANIFEST. MF` and resides
within the `META-INF` directory of a JAR file. This file provides a
multitude of capabilities that influence the behavior, discoverability,
and structure of the encapsulated JavaBeans components.
JAR files
JAR files can be used for packaging related class files, serialized
Beans, and other resources. This scheme allows multiple Beans to
be packaged in a single JAR file, providing a convenient way to
share common class files and resources. Optionally, a JAR file may
contain a manifest describing its contents.
4.2 (a) Enterprise Java Beans (EJB):
Enterprise Java Beans (EJB) is one of the several Java APIs
for standard manufacture of enterprise software. EJB is a server-side
software element that summarizes business logic of an application.
Enterprise Java Beans web repository yields a runtime domain for
web related software elements including computer reliability, Java
Servlet Lifecycle (JSL) management, transaction procedure and
other web services. The EJB enumeration is a subset of the Java EE
enumeration.
The EJB enumeration was originally developed by IBM in
1997 and later adopted by Sun Microsystems in 1999 and enhanced
under the Java Community Process.
The EJB enumeration aims to provide a standard way to
implement the server-side business software typically found in
enterprise applications. Such machine code addresses the same
types of problems, and solutions to these problems are often
288
repeatedly re-implemented by programmers. Enterprise Java Beans
is assumed to manage such common concerns as endurance,
transactional probity and security in a standard way that leaves
programmers free to focus on the particular parts of the enterprise
software at hand.
To run EJB application we need an application server (EJB
Container) such as Jboss, Glassfish, Weblogic, Websphere etc. It
performs:
1. Life cycle management
2. Security
3. Transaction management
4. Object pooling
4.2(b) Types of Enterprise Java Beans:
There are three types of EJB:
1. Session Bean: Session bean contains business logic that can be
invoked by local, remote or webservice client. There are two types
of session beans: (i) Stateful session bean and (ii) Stateless session
bean.
• (i) Stateful Session bean :
Stateful session bean performs business task with the help of a
state. Stateful session bean can be used to access various method
calls by storing the information in an instance variable. Some of the
applications require information to be stored across separate method
calls. In a shopping site, the items chosen by a customer must be
stored as data is an example of stateful session bean.
• (ii) Stateless Session bean :
Stateless session bean implement business logic without
having a persistent storage mechanism, such as a state or database
and can used shared data. Stateless session bean can be used in
situations where information is not required to used across call
methods.

289
2. Message Driven Bean: Like Session Bean, it contains the
business logic but it is invoked by passing message.
3. Entity Bean: It summarizes the state that can be remained in the
database. It is deprecated. Now, it is replaced with JPA (Java
Persistent API). There are two types of entity bean:
• (i) Bean Managed Persistence :
In a bean managed persistence type of entity bean, the programmer
has to write the code for database calls. It persists across multiple
sessions and multiple clients.
• (ii) Container Managed Persistence :
Container managed persistence are enterprise bean that persists
across database. In container managed persistence the container take
care of database calls.
4.2(c)Use Enterprise Java Beans:
1. 1.Application needs Remote Access. In other words, it is
distributed.
2. 2.Application needs to be scalable. EJB applications supports
load balancing, clustering and fail-over.
3. 3.Application needs encapsulated business logic. EJB
application is differentiated from demonstration and persistent
layer.
Advantages of Enterprise Java Beans
1. EJB repository yields system-level services to enterprise beans,
the bean developer can focus on solving business problems.
Rather than the bean developer, the EJB repository is
responsible for system-level services such as transaction
management and security authorization.
2. The beans rather than the clients contain the application’s
business logic, the client developer can focus on the presentation
of the client. The client developer does not have to code the
pattern that execute business rules or access databases. Due to

290
this the clients are thinner which is a benefit that is particularly
important for clients that run on small devices.
3. Enterprise Java Beans are portable elements, the application
assembler can build new applications from the beans that
already exists.
Disadvantages of Enterprise Java Beans
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.
4.2(d)EJB 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.

291
4.3 (a) Java JDBC:
JDBC stands for Java Database Connectivity. JDBC is a Java
API to connect and execute the query with the database. It is a part
of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to
connect with the database. There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
We can use JDBC API to access tabular data stored in any
relational database. By the help of JDBC API, we can save, update,
delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since


21st September, 2017. It is based on the X/Open SQL Call Level
Interface. The java.sql package contains classes and interfaces for
JDBC API. A list of popular interfaces of JDBC API are given
below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface

292
4.3(b) JDBC Driver:
JDBC Driver is a software component that enables java
application to interact with the database. There are 4 types of JDBC
drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect
to the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now discouraged
because of thin driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8.


Oracle recommends that you use JDBC drivers provided by the
vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.

293
Disadvantages:
o Performance degraded because JDBC method call is converted
into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database.
The driver converts JDBC method calls into native calls of the
database API. It is not written entirely in java.

Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client
machine.
o The Vendor client library needs to be installed on client
machine.

294
3) Network Protocol driver
The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-
specific database protocol. It is fully written in java.

Advantage:
o No client side library is required because of application server
that can perform many tasks like auditing, load balancing,
logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in the
middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully
written in Java language.

295
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
4.3(c)Main classes and interfaces of JDBC:
JDBC API is available in two packages java.sql, core API and
javax.sql JDBC optional packages. Following are the important
classes and interfaces of JDBC.
DriverManager This class manages the JDBC drivers. You
need to register your drivers to this.
It provides methods such as registerDriver()
and getConnection().
Driver This interface is the Base interface for every
driver class i.e. If you want to create a JDBC
Driver of your own you need to implement
this interface. If you load a Driver class
(implementation of this interface), it will
create an instance of itself and register with
the driver manager.
Statement This interface represents a static SQL
statement. Using the Statement object and
its methods, you can execute an SQL
statement and get the results of it.

296
It provides methods such as execute(),
executeBatch(), executeUpdate() etc. To
execute the statements.
PreparedStatement This represents a precompiled SQL
statement. An SQL statement is compiled
and stored in a prepared statement and you
can later execute this multiple times. You
can get an object of this interface using the
method of the Connection interface named
prepareStatement(). This provides methods
such as executeQuery(), executeUpdate(),
and execute() to execute the prepared
statements and getXXX(), setXXX()
(where XXX is the datatypes such as long
int float etc..) methods to set and get the
values of the bind variables of the prepared
statement.
CallableStatement Using an object of this interface you can
execute the stored procedures. This returns
single or multiple results. It will accept
input parameters too. You can create a
CallableStatement using the prepareCall()
method of the Connection interface.
Just like Prepared statement, this will also
provide setXXX() and getXXX() methods
to pass the input parameters and to get the
output parameters of the procedures.
Connection This interface represents the connection
with a specific database. SQL statements
are executed in the context of a
connection.This interface provides methods
such as close(), commit(), rollback(),
createStatement(), prepareCall(),
prepareStatement(), () setSavepoint() etc.
ResultSet This interface represents the database result
set, a table which is generated by executing
297
statements. This interface provides getter
and update methods to retrieve and update
its contents respectively.
ResultSetMetaData This interface is used to get the information
about the result set such as, number of
columns, name of the column, data type of
the column, schema of the result set, table
name, etc
It provides methods such as
getColumnCount(), getColumnName(),
getColumnType(), getTableName(),
getSchemaName() etc.

4.4 (a) Java Database Connectivity with 5 Steps:


There are 5 steps to connect any java application with the database
using JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to
follow 5 following steps.
In this example we are using MySql as the database. So we need to
know following informations for the mysql database:
1. Driver class: The driver class for the mysql database is
com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API,
mysql is the database, localhost is the server name on which
mysql is running, we may also use IP address, 3306 is the port
298
number and sonoo is the database name. We may use any
database, in such case, we need to replace the sonoo with our
database name.
3. Username: The default username for the mysql database is
root.
4. Password: It is the password given by the user at the time of
installing the mysql database. In this example, we are going to
use root as the password.
Let's first create a table in the mysql database, but before creating
table, we need to create database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql database
In this example, sonoo is the database name, root is the username
and password both.
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }

299
The above example will fetch all the records of emp table.
To connect java application with the mysql database,
mysqlconnector.jar file is required to be loaded.
download the jar file mysql-connector.jar
Two ways to load the jar file:
1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath
1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and
paste the jar file here.
2) Set classpath:
There are two ways to set the classpath:
o temporary
o permanent
How to set the temporary classpath
open command prompt and write:
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-
bin.jar;.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name
write classpath and in variable value paste the path to the
mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;.;
There are 5 steps to connect any java application with the
database using JDBC
1) Register the driver class
The forName() method of Class class is used to register the driver
class. This method is used to dynamically load the driver class.
300
Syntax of forName() method
public static void forName(String className)throws
ClassNotFoundException
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database
connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to
establish connection with the database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws
SQLException
public static Connection getConnection(String url,String
name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to
create statement. The object of statement is responsible to execute
queries with the database.
Syntax of createStatement() methodpublic Statement
createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();

301
4) Execute the query
The executeQuery() method of Statement interface is used to
execute queries to the database. This method returns the object of
ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used
to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
4.4(b)Java Database Connectivity with Oracle:
To connect java application with the oracle database, we need to
follow 5 following steps. In this example, we are using Oracle 10g
as the database. So we need to know following information for the
oracle database:
1. Driver class: The driver class for the oracle database is
oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G
database is jdbc:oracle:thin:@localhost:1521:xe where jdbc is
the API, oracle is the database, thin is the driver, localhost is
302
the server name on which oracle is running, we may also use
IP address, 1521 is the port number and XE is the Oracle
service name. You may get all these information from the
tnsnames.ora file.
3. Username: The default username for the oracle database is
system.
4. Password: It is the password given by the user at the time of
installing the oracle database.
Create a Table
Before establishing connection, let's first create a table in oracle
database. Following is the SQL query to create a table.
1. create table emp(id number(10),name varchar2(40),age
number(3));

Example to Connect Java Application with Oracle database


In this example, we are connecting to an Oracle database and getting
data from emp table. Here, system and oracle are the username and
password of the Oracle database.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
303
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));

//step5 close the connection object


con.close();

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

}
}

304
Chapter - 5
Servlets and Java Server Pages

5.1(a)Introduction to Servlets:
Servlet technology is used to create a web application (resides
at server side and generates a dynamic web page).
Servlet technology is robust and scalable because of java
language. Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side programming
language. However, there were many disadvantages to this
technology. We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API such as
Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse, etc.
Servlet is a technology which is used to create a web application.
Servlet is an API that provides many interfaces and classes including
documentation.
Servlet is an interface that must be implemented for creating any
Servlet.
Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
Servlet is a web component that is deployed on the server to create
a dynamic web page.

305
web application
A web application is an application accessible from the web. A web
application is composed of web components like Servlet, JSP, Filter,
etc. and other elements such as HTML, CSS, and JavaScript. The
web components typically execute in Web Server and respond to the
HTTP request.
CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program
and pass HTTP request information to the external program to
process the request. For each request, it starts a new process.

Disadvantages of CGI
There are many problems in CGI technology:

306
1. If the number of clients increases, it takes more time for
sending the response.
2. For each request, it starts a process, and the web server is
limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet

There are many advantages of Servlet over CGI. The web


container creates threads for handling the multiple requests to the
Servlet. Threads have many benefits over the Processes such as they
share a common memory area, lightweight, cost of communication
between the threads are low. The advantages of Servlet are as
follows:
1. Better performance: because it creates a thread for each request,
not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about
the memory leak, garbage collection, etc.
4. Secure: because it uses java language.
5.1(b)Servlets Architecture:
The following diagram shows the position of Servlets in a Web
Application.
307
Servlets Tasks:
Servlets perform the following major tasks −
1. Read the explicit data sent by the clients (browsers). This
includes an HTML form on a Web page or it could also come
from an applet or a custom HTTP client program.
2. Read the implicit HTTP request data sent by the clients
(browsers). This includes cookies, media types and
compression schemes the browser understands, and so forth.
3. Process the data and generate the results. This process may
require talking to a database, executing an RMI or CORBA
call, invoking a Web service, or computing the response
directly.
4. Send the explicit data (i.e., the document) to the clients
(browsers). This document can be sent in a variety of formats,
including text (HTML or XML), binary (GIF images), Excel,
etc.
5. Send the implicit HTTP response to the clients (browsers).
This includes telling the browsers or other clients what type of
document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.

308
5.1(c)Servlet API:
The javax.servlet and javax.servlet.http packages represent
interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that
are used by the servlet or web container. These are not specific to
any protocol.
The javax.servlet.http package contains interfaces and classes that
are responsible for http requests only.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as
follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as
follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
309
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as
follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as
follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
5.1(d) Life Cycle of a Servlet (Servlet Life Cycle):
The web container maintains the life cycle of a servlet instance. Let's
see the life cycle of the servlet:
1. Servlet class is loaded.
310
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a


servlet: new, ready and end. The servlet is in new state if servlet
instance is created. After invoking the init() method, Servlet comes
in the ready state. In the ready state, servlet performs all the tasks.
When the web container invokes the destroy() method, it shifts to
the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The
servlet class is loaded when the first request for the servlet is
received by the web container.

311
2) Servlet instance is created
The web container creates the instance of a servlet after
loading the servlet class. The servlet instance is created only once in
the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after
creating the servlet instance. The init method is used to initialize the
servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:
1. public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it
follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice
that servlet is initialized only once. The syntax of the service method
of the Servlet interface is given below:
1. public void service(ServletRequest request, ServletResponse
response)
2. throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the
servlet instance from the service. It gives the servlet an opportunity
to clean up any resource for example memory, thread etc. The syntax
of the destroy method of the Servlet interface is given below:
1. public void destroy()

312
5.1(e) Get vs. Post Request:

GET POST

1) In case of Get request, In case of post request, large


only limited amount of amount of data can be sent
data can be sent because data is because data is sent in body.
sent in header.

2) Get request is not Post request


secured because data is is secured because data is not
exposed in URL bar. exposed in URL bar.

3) Get request can be Post request cannot be


bookmarked. bookmarked.

4) Get request is idempotent . Post request is non-


It means second request will be idempotent.
ignored until response of first
request is delivered

5) Get request is more Post request is less


efficient and used more than efficient and used less than
Post. get.

5.1(f) Handling GET and POST Requests:


To handle HTTP requests in a servlet, extend the HttpServlet
class and override the servlet methods that handle the HTTP
requests that your servlet supports. This lesson illustrates the
handling of GET and POST requests. The methods that handle these
requests are doGet and doPost.
Handling GET requests
Handling GET requests involves overriding the doGet method.
The following example shows the BookDetailServlet doing this.
The methods discussed in the Requests and Responses section are
shown in bold.
313
public class BookDetailServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title>Book Description</title></head>" +
...);
//Get the identifier of the book to display
String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...

314
}

The servlet extends the HttpServlet class and overrides the


doGet method.Within the doGet method, the getParameter method
gets the servlet's expected argument.To respond to the client, the
example doGet method uses a Writer from the HttpServletResponse
object to return text data to the client. Before accessing the writer,
the example sets the content-type header. At the end of the doGet
method, after the response has been sent, the Writer is closed.
Handling POST Requests
Handling POST requests involves overriding the doPost
method. The following example shows the ReceiptServlet doing
this. Again, the methods discussed in the Requests and Responses
section are shown in bold.
public class ReceiptServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title> Receipt </title>" +
315
...);

out.println("<h3>Thank you for purchasing your books from


us " +
request.getParameter("cardname") +
...);
out.close();
}
...
}
The servlet extends the HttpServlet class and overrides the
doPost method.Within the doPost method, the getParameter method
gets the servlet's expected argument.To respond to the client,
theexample doPost method uses a Writer from the
HttpServletResponse object to return text data to the client. Before
accessing the writer the example sets the content-type header. At the
end of the doPost method, after the response has been set, the Writer
is closed.
5.2(a)SendRedirect in servlet:
The sendRedirect() method of HttpServletResponse interface
can be used to redirect response to another resource, it may be
servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser
to make another request. So, it can work inside and outside the
server.

316
Difference between forward() and sendRedirect() method
There are many differences between the forward() method of
RequestDispatcher and sendRedirect() method of
HttpServletResponse interface. They are given below:

forward() method sendRedirect() method

The forward() method works at server The sendRedirect() method works at


side. client side.

It sends the same request and response It always sends a new request.
objects to another servlet.

It can work within the server only. It can be used within and outside the
server.

Example: Example:
request.getRequestDispacher("servlet2 response.sendRedirect("servlet2");
").forward(request,response);

Full example of sendRedirect method in servlet


In this example, we are redirecting the request to the google server.
Notice that sendRedirect method works at client side, that is why we
can our request to anywhere. We can send our request within and
outside the server.
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

317
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse
res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
response.sendRedirect("http://www.google.com");
pw.close();
}}

Creating custom google search using sendRedirect


In this example, we are using sendRedirect method to send request
to google server with the request data.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
318
</body>
</html>
MySearcher.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySearcher extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");

response.sendRedirect("https://www.google.co.in/#q="+name);
} }

319
5.2 (b) Session Tracking in Servlets:
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:

320
Use Session Tracking:
To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
5.2(c)Cookies in Servlet:
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.
How Cookie works
By default, each request is considered as a new request. In
cookies technique, we add cookie with response from the servlet. So
cookie is stored in the cache of the browser. After that if request is
sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie

321
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.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the
cookie, gmail won't work.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using
cookies. It provides a lot of useful methods for cookies.

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a specified


value) name and value.

322
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.

Method Description

public void Sets the maximum age of the cookie in


setMaxAge(int expiry) seconds.

public String getName() Returns the name of the cookie. The name
cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void changes the name of the cookie.


setName(String name)

public void changes the value of the cookie.


setValue(String value)
Other methods required for using Cookies
For adding cookie or getting the value from the cookie, we need
some methods provided by other interfaces. They are:
1. public void addCookie(Cookie ck):method of
HttpServletResponse interface is used to add cookie in response
object.
2. public Cookie[] getCookies():method of HttpServletRequest
interface is used to return all the cookies from the browser.
Create Cookie:
Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating
cookie object
2. response.addCookie(ck);//adding cookie in the response
Delete Cookie:
Let's see the simple code to delete cookie. It is mainly used to logout
or signout the user.
323
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response
Getting Cookies:
Let's see the simple code to get all the cookies.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+"
"+ck[i].getValue());//printing name and value of cookie
4. }
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.

index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

324
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
325
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}
} }
web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
326
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Output

327
5.2(d) HttpSession interface:
In such case, container creates a session id for each user.The
container uses this id to identify the particular user.An object of
HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the
session identifier, creation time, and last accessed time.

328
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the
object of HttpSession:
1. public HttpSession getSession():Returns the current session
associated with this request, or if the request does not have a
session, creates one.
2. public HttpSession getSession(boolean create):Returns the
current HttpSession associated with this request or, if there is
no current session and create is true, returns a new session.
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique
identifier value.
2. public long getCreationTime():Returns the time when this
session was created, measured in milliseconds since midnight
January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the
client sent a request associated with this session, as the number
of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds
any objects bound to it.
Example of using HttpSession
In this example, we are setting the attribute in the session scope in
one servlet and getting that value from the session scope in another
servlet. To set the attribute in the session scope, we have used the
329
setAttribute() method of HttpSession interface and to get the
attribute, we have used the getAttribute method.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);

HttpSession session=request.getSession();
session.setAttribute("uname",n);

out.print("<a href='servlet2'>visit</a>");

out.close();
330
}catch(Exception e){System.out.println(e);}
}

}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);

out.close();

}catch(Exception e){System.out.println(e);}
331
} }
web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

332
5.3 (a) JSP (Java Server Pages):
JSP technology is used to create web application just like
Servlet technology. It can be thought of as an extension to Servlet
because it provides more functionality than servlet such as
expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP
pages are easier to maintain than Servlet because we can separate
designing and development. It provides some additional features
such as Expression Language, Custom Tags, etc.
Advantages of JSP over Servlet:
There are many advantages of JSP over the Servlet. They are
as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use
all the features of the Servlet in JSP. In addition to, we can use
implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.
(2)Easy to maintain
JSP can be easily managed because we can easily separate our
business logic with presentation logic. In Servlet technology, we
mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy
the project. The Servlet code needs to be updated and recompiled if
we have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags,
etc. that reduces the code. Moreover, we can use EL, implicit
objects, etc.

333
5.3 (b) The Lifecycle of a JSP Page:
The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService()
method).
o Destroy ( the container invokes jspDestroy() method).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle
methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet


by the help of JSP translator. The JSP translator is a part of the web
server which is responsible for translating the JSP page into Servlet.
After that, Servlet page is compiled by the compiler and gets
334
converted into the class file. Moreover, all the processes that happen
in Servlet are performed on JSP later like initialization, committing
response to the browser and destroy.
5.3 (c) Creating a simple JSP Page:
To create the first JSP page, write some HTML code as given below,
and save it by .jsp extension. We have saved this file as index.jsp.
Put it in a folder and paste the folder in the web-apps directory in
apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet
tag to put Java code in the JSP page. We will learn scriptlet tag later.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
It will print 10 on the browser.
How to run a simple JSP Page?
Follow the following steps to execute this JSP page:
o Start the server
o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL
http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp
Do I need to follow the directory structure to run a simple JSP?
No, there is no need of directory structure if you don't have class
files or TLD files. For example, put JSP files in a folder directly and
deploy that folder. It will be running fine. However, if you are using
Bean class, Servlet or TLD file, the directory structure is required.
335
The Directory structure of JSP
The directory structure of JSP page is same as Servlet. We contain
the JSP page outside the WEB-INF folder or in any Directory
structure.

5.4 (a) Jsp implicit objects:


There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.
The available implicit objects are out, request, config, session,
application etc.s
A list of the 9 implicit objects is given below:

Object Type

out JspWriter

336
request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

5.4 (b) JSP request implicit object:


The JSP request is an implicit object of type HttpServletRequest i.e.
created for each jsp request by the web container. It can be used to
get request information such as parameter, header information,
remote address, server name, server port, content type, character
encoding etc.
It can also be used to set, get and remove attributes from the jsp
request scope.
Let's see the simple example of request implicit object where we are
printing the name of the user with welcome message.
Example of JSP request implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
337
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
Output

338
5.4(c) JSP response implicit object:
In JSP, response is an implicit object of type HttpServletResponse.
The instance of HttpServletResponse is created by the web container
for each jsp request.
It can be used to add or manipulate response such as redirect
response to another resource, send error etc.
Let's see the example of response implicit object where we are
redirecting the response to the Google.
Example of response implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
Output

339
5.4(d) JSP directives:
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:
o page directive
o include directive
o taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
Attributes of JSP page directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage
Jsp Include Directive
The include directive is used to include the contents of any resource
it may be jsp file, html file or text file. The include directive includes
the original content of the included resource at page translation time
(the jsp page is translated only once so it will be better to include
static resource).
Advantage of Include directive
Code Reusability
340
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the header.html file.
To run this example you must create an header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Taglib directive
The JSP taglib directive is used to define a tag library that defines
many tags. We use the TLD (Tag Library Descriptor) file to define
the tags. In the custom tag section we will use this tag so it will be
better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary"
%>
Example of JSP Taglib directive
In this example, we are using our tag named currentDate. To use this
tag we must specify the taglib directive so the container may get
information about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag"
%>
<mytag:currentDate/>
341
</body>
</html
JSP Action Tags
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

jsp:forward forwards the request and response to 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.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and


include mostly.

jsp:fallback can be used to print the message if plugin is working. It


is used in jsp:plugin.

Example of jsp:forward action tag without parameter


In this example, we are simply forwarding the request to the
printdate.jsp file.
index.jsp
<html>

342
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Custom Tags in JSP:
Custom tags are user-defined tags. They eliminates the possibility
of scriptlet tag and separates the business logic from the JSP page.
The same business logic can be used many times by the use of
custom tag.
Advantages of Custom Tags
The key advantages of Custom tags are as follows:
1. Eliminates the need of scriptlet tag The custom tags eliminates
the need of scriptlet tag which is considered bad programming
approach in JSP.
2. Separation of business logic from JSP The custom tags separate
the the business logic from the JSP page so that it may be easy
to maintain.
3. Re-usability The custom tags makes the possibility to reuse the
same business logic again and again.
Syntax to use custom tag

343
There are two ways to use the custom tag. They are given below:
<prefix:tagname attr1=value1....attrn=valuen />
<prefix:tagname attr1=value1....attrn=valuen >
body code
</prefix:tagname>
5.4 (e) JSP Custom Tag API:
The javax.servlet.jsp.tagext package contains classes and interfaces
for JSP custom tag API. The JspTag is the root interface in the
Custom Tag hierarchy.

344

You might also like