Appendix: Informatics Practices
Appendix: Informatics Practices
Appendix: Informatics Practices
1 191
1 COMPUTER NETWORKING
7 WEB APPLICATIONS
CONTENTS
39 244
270
9
56
3
GUI PROGRAMMING - MORE ON DATABASES
A REVIEW AND SQL
103 315
4 10
BASICS OF OBJECT ADVANCED RDBMS
ORIENTED PROGRAMMING CONCEPTS
122 334
5 11
ADVANCED PROGAMMING
CONCEPTS IT APPLICATIONS
150 362
6 DATA CONNECTIVITY
APPENDIX
A PTE
H
1
R
C
COMPUTER NETWORKING
Learning objectives
Have you ever worked on Internet? Have you ever used an ATM? Have you ever
given the print command on a computer to get the printout on a printer attached
to some other computer? Have you ever transferred songs from your computer to a
cell phone or vice-versa? If the answer to any of these questions is YES, then you
have experienced and utilized the services of a computer network. In this chapter
you will study about various types of computer networks, their benefits, and what
is required to create computer networks.
Puzzle 1
Can you place 10 coins in such a way that they lie in 5 straight lines and on each line there
are exactly 4 coins?
Such situations are faced by the designers of computer networks. They have to think of
various ways of interconnecting the computers so that the specific goals of network setup
are achieved.
1
COMPUTER NETWORKING
Why do we have computer networks? Are there any advantages of networked computers
over stand alone computers? Yes, there are many. A few of these advantages are:
• Resource Sharing
• Cost saving
• Time saving
• Increased storage
Resource Sharing:
In a networked computer lab when print command is given on one computer the
document may be printed by the printer which is attached to some other computer. This
printer is able to print documents from multiple users on the network. It means that the
printer is being shared by more than one users. This is an example of resource sharing,
and this is possible only when the computers are interconnected to form a network.
Similarly other resources like Hard Disk, DVD Drive, and Scanner etc. can also be shared
on a computer network. Software resources like Application Softwares, Anti-Virus tools
etc. can also be shared on computer networks. You can very easily conclude that this
resource sharing also leads to cost-saving.
2
COMPUTER NETWORKING
Let us take one more example of a school. Here we assume that all the computers in the
school are connected to one main computer (called server). After the exams, teachers
have to exchange marks with each other for result preparation. So all the teachers enter
the marks class wise for their respective subjects at one centralized location and from
there the class teachers can copy the marks of their classes and can prepare the result.
This way data is shared on a computer network. Similar is the case with other
computerized organizations also.
Increased Storage:
All these advantages are there for a small organization like a school as well as for big
business organizations and for governments. Today, small as well as big organizations,
and governments keep their data on secured large scale computers called servers. They
share this data with authorized users. This ensures security. Customer care cells of
companies share the resources and data and they also communicate among themselves as
well as with customers with the help of computer networks only.
3
COMPUTER NETWORKING
Networking Hardware
To form a computer network a lot of hardware devices are required. Some of these
devices along with their functionalities are mentioned below :
Transmission Media
Computers on a network are able to share data and other resources. They are also able to
communicate among themselves. To make all this possible there must be some medium
over which the data can travel from one computer to another. A medium of data
transmission over a computer network is called a channel or a transmission medium.
Channels may be guided (wired) or unguided (wireless).
Wired Media
A number of various types of cables are used to transfer data over computer networks.
These are Twisted Pair Cable, Co-axial Cable, and Optical Fiber Cable. Let us know about
these in some details.
Twisted Pair Cable - This is probably the most widely used cable for creating small
computer networks. It contains four twisted pairs covered in an outer shield. These pairs
are colour coded. An RJ-45 connecter is used to connect this cable to a computer. It is of
two types:
UTP (Unshielded Twisted Pair): As the name suggests in UTP cables individual pairs are
not shielded.
4
COMPUTER NETWORKING
• Due to its thickness (1cm diameter) and less flexibility, it is difficult to install as
compared to twisted pair cable.
Earlier coaxial cable was also used for connecting computers in small networks but now
UTP/STP cables are more commonly used for this purpose.
5
COMPUTER NETWORKING
• Core - It is the thin glass rod at the center through which the light travels
• Cladding - It is the outer optical material surrounding the core that reflects the
light back into the core
• Buffer coating - It is the plastic coating that protects the cable from damage
and moisture
These optical fibers are arranged in bundles of hundreds and thousands and are protected
by the cable's outer covering, called jacket.
Characteristics of Optical Fiber Cable:
• It can carry data for a very large distance at a stretch.
• Not susceptible to electromagnetic fields
• Specially skilled people are required to install optical fiber cables.
• Till date it is the most expensive and at the same time the most efficient cable
available for computer networks.
Comparison of wired media
6
COMPUTER NETWORKING
Wireless Media
Electromagnetic waves are used for wireless communication over computer networks.
Frequencies of waves are measured in Hertz (Hz). As the frequencies of electromagnetic
waves change, their properties also change. Based on their frequencies, electromagnetic
waves are categorized into various categories. These categories are (in increasing order
of frequencies): radio waves, microwaves, infrared radiation, visible light, ultraviolet
radiation, X-rays, and Gamma rays.
Electromagnetic Spectrum
Category Long Radio Radiowaves Microwaves Infrared R O Y G B I V Ultraviolet X-Rays Gamma
Rays Visible Light Rays Rays
Frequency Less than 3 x 103 to 3 x 108 to 3 x 1011 to 4.3x1014 to More than 1014
3 9 11 14 14
(Hz) 3x10 3 x 10 3 x 10 4 x 10 7.5x10
Out of these only radio waves, microwaves, and infrared rays are used for wireless
communication. Let us now study about these waves in some details.
7
COMPUTER NETWORKING
(Recall when you throw a stone in a pond, circular waves are generated and
spread outwards. Similarly, radio waves are generated by the transmitter and
spread in all the directions.)
Micro Waves - Micro waves have a frequency range of 300MHz (0.3 GHz) to 300 GHz. This
range has some overlapping portion (0.3GHz - 3GHz) with radio waves as there is no clear-
cut demarcation between radio waves and micro waves. Microwaves travel in straight
lines and cannot penetrate any solid object. Therefore for long distance microwave
communication, high towers are built and microwave antennas are put on their tops.
Distance between two microwave towers depends on many factors including frequency of
the waves being used and heights of the towers. These waves travel in straight lines and
therefore the sending and receiving antennas have to be aligned with each other.
In the big cities where land is very costly and a lot of formalities have to be completed to
get permission to dig land for cabling, microwave antennas can be put on top of high rise
buildings and communication can be started in a short time.
8
COMPUTER NETWORKING
Micro Wave
Micro Wave
Office 1 Office 2
Micro Wave
Tower
9
COMPUTER NETWORKING
Bluetooth - Bluetooth technology uses radio waves in the frequency range of 2.402 GHz
to 2.480 GHz. This technology is used for short range communication (approx. 10m) in a
variety of devices for wireless communication. Baby monitors, door openers, and cell
phones are some of the devices that utilize Bluetooth communication.
Satellite Link - Satellite links are used for very long distance wireless communication
which may range from intercity to intercontinental. Transmission from the earth to a
satellite is known as uplink. Transmission from a satellite to the earth is known as
downlink. There are multiple micro wave frequency bands which are used for satellites
links. Frequency used for uplink varies from 1.6 GHz to 30.0 GHz and that for downlink
varies from 1.5GHz to 20.0GHz. Downlink frequency is always lower than the uplink
frequency. For example, the uplink frequency is 6.0GHz, and the corresponding downlink
frequency is 4.0 GHz. A communications satellite is a relay station in orbit above the earth
that receives, regenerates, and redirects signals carried on a specific frequency. The
satellite system is very expensive but its area coverage and fringe benefits compensate
for the expenses. Communication satellites are normally owned by governments or by
government approved organizations of various countries
10
COMPUTER NETWORKING
Communication
Satellite
Orbit
Uplink Uplink
Downlink
Downlink
Earth Earth
Station Station
Europe Asia
Communication
Medium
Guided Unguided
(Wired) (Wireless)
11
COMPUTER NETWORKING
Network Devices
Other than the transmission media many other devices are required to form computer
networks. Some of these devices are:
NIC: Any computer which has to be a part of a computer network must have an NIC
(Network Interface Card / Unit) installed in it. A computer communicates with other
computers on a network with the help of an NIC only. Now a days, in most of the PCs and
the laptops, NIC is an integral part of the motherboard.
Socket for
RJ-45
Connector
Hub/Switch
12
COMPUTER NETWORKING
A Hub is an electronic device that connects several nodes to form a network and
redirects the received information to all the connected nodes in broadcast mode.
Switch: A switch is an intelligent hub. It looks exactly like a hub. It has the same function
as that of a hub: to connect multiple computers/devices in a network. But the difference
between the two is in the way they re-transmit the received information. Unlike a hub,
instead of broadcasting (sending to each device attached to it) the received information,
a switch sends the information selectively only to those computers for which it is
intended. This makes a switch more efficient than a hub.
Repeater: When the data is transmitted over a network for long distances, the data
signal gets weak after certain distance. This distance depends on the data transfer range
of transmission channel being used and can be from a few meters to a few kilometers. If
the signal becomes weak, it cannot reach its destination. Therefore, some device is
required which can re-strengthen the data signal before it gets too weak. Repeater is
such a device. A repeater regenerates the received signal and re-transmits it to its
destination
Gateway: There are a large number of computer networks in this world. As common
examples you can consider your school's computer network, ATM network of a bank, a big
company's computer network spread over a city, etc. There are thousands of computer
networks that exist. These networks use different hardware and software. Many times
these networks need to communicate with each other. For example, companies X, Y, and
Z do business with each other and therefore they want to interconnect their computer
networks. Another example is the internet which contains a large number of different
types of networks spread over the globe. Different networks are sometimes incompatible
13
COMPUTER NETWORKING
with each other. It is like a group of persons using different languages for conversation.
When two or more networks using different hardware and software have to be
connected, some device is needed which can translate one network's language into the
other's. A gateway is a device, which is used to connect different types of networks. A
gateway is capable of understanding address architectures used in different networks
and seamlessly translate between these address architectures.
Network Topologies
Before we start discussion on network topologies, let us understand the term 'NODE'.
Any device (Computer, Scanner, Printer, etc.) which is directly connected to a computer
network is called a node. Suppose you are working on a PC at your home and then you
connect it to internet. As soon as it becomes a part of internet (which is a computer
network), it becomes a node. Similarly, in your school, all the computers which are linked
to school's computer network are nodes.
Once we know about different communication media and devices to form a computer
network, we can procure these media and devices and start constructing a computer
network. Suppose we have 10 computers and we want to interconnect them to form a
network. How can we interconnect them?
Recall the puzzle given in the beginning of this lesson. Is that not similar to the problem of
connecting nodes in a network?
14
COMPUTER NETWORKING
Bus Topology: In bus topology all the nodes are connected to a main cable called
backbone. If any node has to send some information to any other node, it sends the signal
to the backbone. The signal travels through the entire length of the backbone and is
received by the node for which it is intended. A small device called terminator is attached
at each end of the backbone. When the signal reaches the end of backbone, it is absorbed
by the terminator and the backbone gets free to carry another signal. This prevents the
reflection of signal back on the cable and hence eliminates the chances of signal
interference.
Node Node-Printer Node
Backbone
Terminator Terminator
Node
Node (Server) Node Node
Bus Topology
• It is easy to install.
15
COMPUTER NETWORKING
Star Topology: In star topology each node is directly connected to a hub/switch. If any
node has to send some information to any other node, it sends the signal to the
hub/switch. This signal is then broadcast (in case of a hub) to all the nodes but is
accepted by the intended node(s). In the case of a switch the signal is sent only to the
intended node(s).
Node Node
Hub/
Switch
Node Node
• It is easy to install
Tree Topology: Tree topology is a combination of bus and star topologies. It is used to
combine multiple star topology networks. All the stars are connected together like a bus.
This bus-star hybrid approach supports future expandability of the network
16
COMPUTER NETWORKING
Tree Topology
• Even if one network (star) fails, the other networks remain connected and
working.
Network Protocols
A computer network can be set up after procuring all the required hardware. But the
network devices will be able to communicate with each other only after they know the
rules of communication. Think of a group discussion session where all the participants can
speak. Each participant can speak a lot. But the group discussion can be started and can
be conducted well if each participant knows the rules of discussion. If all the participants
start speaking suddenly and suddenly they stop, or a person stands up randomly and starts
interrupting the discussion, or any such thing happens, the group discussion cannot be
conducted at all. A more complex situation exists in the case of computer networks where
the participating devices have no common sense and they follow each defined rule to the
T. So it is essential that the rules of communication are very well defined. A set of rules is
also known as a protocol.
17
COMPUTER NETWORKING
There are a number of protocols defined for computer networks. Here we discuss three of
them - HTTP, TCP/IP, PPP.
HTTP (Hyper Text Transfer Protocol): HTTP is used to transfer all files and other data
(collectively called resources) from one computer to another on the world wide web.
When an HTTP client (a browser) sends a request to an HTTP server (web server) , the
server sends responses back to the client. This transfer of requests and responses is done
following HTTP protocol.
PPP (Point to Point Protocol): It is a protocol for direct communication between two
computers, typically a personal computer connected by phone line to a server. Most
Internet service providers (ISPs) use PPP for customer dial-up access to the Internet. PPP
is used over many types of physical networks including cellular telephone, serial cable,
phone line, trunk line, specialized radio links, and fiber optic links.
Know More!
There are a lot of other communication protocols like SMTP, POP, UDP etc. You can
explore the net to find more about these protocols.
18
COMPUTER NETWORKING
Types of Networks
A computer network may span any amount of geographical area. It can be on a table, in a
room, in a building, in a city, in a country, across continents or around the world. On the
basis of area covered computer networks are classified as:
A PAN
When you have to transfer songs from one cell phone to another, you set up a PAN of two
phones. When files are transferred from a PC to an MP3 player, a PAN is set up between
the two. There can also be multiple devices in PAN. A PAN can be set up using guided
media (USB cable) or unguided media (Bluetooth, Infrared).
19
COMPUTER NETWORKING
Warehouse
Branch Office
Central Office
A Metropolitan Area Network
Factory
20
COMPUTER NETWORKING
LAN
PC
PC PC
MAN
LAN
A Wide Area Network
21
COMPUTER NETWORKING
The following table summarizes the characteristics of PANs, LANs, MANs, and WANs.
Parameter
Area Covered Small Area A few meters A city and its Entire country,
(Upto 10m to a few vicinity continent, or
radius) kilometers (Upto 100Km globe
(Upto 10Km radius) (No upper limit)
radius)
Once a network has been set up, the nodes can communicate among themselves. But for
proper communication, the nodes should be uniquely identifiable. If a node X sends some
information for node Y on a network, then it is mandatory that nodes X and Y are uniquely
identifiable on the network. Let us see how this is achieved.
MAC (Media Access Control) address: Each NIC has a universally unique address assigned
to it by its manufacturer. This address is known as the MAC (Media Access Control) address
of the card. It means that a machine with an NIC can be identified uniquely through its
NIC's MAC address. MAC address of an NIC is permanent and does never change.
MAC addresses are 12-digit hexadecimal (or 48 bit) numbers. By convention, MAC
addresses are usually written in one of the following two formats:
MM:MM:MM:SS:SS:SS
MM-MM-MM-SS-SS-SS
22
COMPUTER NETWORKING
The first half (MM:MM:MM) of a MAC address contains the ID number of the adapter
manufacturer. The second half (SS:SS:SS) of a MAC address represents the serial number
assigned to the adapter (NIC) by its manufacturer.
00:A0:C9 : 14:C8:35
The prefix 00:A0:C9 indicates that the manufacturer is Intel Corporation. And the last
three numbers 14:C8:35 are given by the manufacturer (Intel in this example) to this NIC.
IP Address: Every machine in a network has another unique identifying number, called its
IP Address. An IP address is a group of four bytes (or 32 bits) each of which can be a number
from 0 to 255. A typical IP address looks like this:
59.177.134.72
On a network, IP address of a machine, and not the MAC address of its NIC, is used to
identify it. Do you recall IP protocol? IP protocol identifies a machine with its IP address to
route the packets.
MAC address is used only when a specific machine is to be targeted. For example, suppose
we want to block a specific PC to access some network resource. If we use the PCs IP
address, then the PC is not blocked permanently as its IP address may change when it
connects to the network next time. Instead, if the PCs MAC address is used for the
purpose, then the job is done!
23
COMPUTER NETWORKING
Know More!
There are two versions of IP addresses: version 4 (IPv4) and version 6 (IPv6). IPv6
uses 128 bits (IPv4 uses 32 bits) for an IP address. Using IPv4 only 232 (approximately
4 billion) distinct devices can be addressed. In the current scenario and in the near
future, this is a small fraction of the number of objects which need to be allocated
IP addresses. As the human population and also the number of devices which need
to be online (mobile phones, home appliances, personal communication devices,
etc.) is increasing at a very fast pace, IPv4 addresses are being exhausted. To
address this problem IPv6 was developed and it is now being deployed. Using IPv6
2128 (approximately 4 Bn x 4 Bn x 4 Bn x 4 Bn) distinct devices can be addressed. IPv6
also includes an important feature: a set of possible migration and transition plans
from IPv4.There are many other features of IPv6. You can explore the internet and
find more information about IPv6.
IP Address Vs MAC Address: You might wonder how an IP address differs from a MAC
address. In fact, the IP address is assigned by the network administrator or the internet
service provider while the MAC address is assigned by the manufacturer. Thus if a
computer is transferred from one network to another, its IP address gets changed where
as the MAC address remains the same.
From the IP address it is usually possible to track the tentative location of the computer
but this is not the case with a MAC address.
24
COMPUTER NETWORKING
A domain name usually has more than one parts: top level domain name or primary
domain name and sub-domain name(s). For example, in the domain name cbse.nic.in, in
is the primary domain name; nic is the sub-domain of in; cbse is the sub-domain of nic.
There are only a limited number of top level domains, and these are divided into two
categories: Generic Domain Names and Country-Specific Domain Names. For example:
·mil - Military
.in - India
·au - Australia
·ca - Canada
.ch - China
.pk - Pakistan
.jp - Japan
.us - United States of America
25
COMPUTER NETWORKING
Domain Name Resolution: Domain Name Resolution is the process of getting the
corresponding IP address from a domain name. It happens as follows:
Suppose you mention a URL in the web-browser to visit a website. The browser first
checks your computer to find if the IP address of the server corresponding to the Domain
Name (embedded in the URL) is present. If this address is present then with the help of
this address, the corresponding server is contacted and then the website opens in your
browser. Otherwise the browser sends this domain name to some specific servers (called
domain name servers) to find the corresponding IP address. Once the IP address is known,
the server is contacted and then the website opens in your browser.
Know More!
Network Security
Computer networks are communication highways on which the data travels. Data travels
on a network when an e-mail is sent or received, any transaction is made using a credit or
a debit card, a web site is accessed, chatting is done, or any other work is done on a
network. Data travelling over a network is vulnerable to attacks and thefts. There are
some people who want to illegally access this data for any reason: using a credit/debit
card data for shopping, using a company's data to sell it to some rival company, to find the
kind of web sites a person accesses, or may be hundreds of other reasons. These people
26
COMPUTER NETWORKING
may sometimes also want to destroy the data on its way, or block the services of some
resources or sites. As the data goes from one point to another point on the Internet, for
example, it may pass through several points along the way, giving other users the
opportunity to access, and even alter it. Even other users on your system may maliciously
transform your data. Unauthorized access to your system may be obtained by intruders,
who then use advanced knowledge to impersonate you, steal information or even deny
your access to your own resources.
Denial of service attacks: A Denial of Service (DoS) attack is an attempt to make one or
more network resources unavailable to their legitimate users. Examples of such attacks
are:
Snooping - Have you ever tried to read someone else's slam book secretly? This is
snooping. Have you ever tried to read what someone else is writing in his/her
letter/email to someone else? This is snooping. Do you think your parents try to secretly
check your mobile phone to find its contents? If yes, then what your parents are doing is
snooping.
27
COMPUTER NETWORKING
• Using some softwares which keeps track of the activities and data being sent or
received on someone's computer.
Eavesdropping - Do you ever find that when you are talking to someone else, another
person is secretly trying to listen to your talks? What that person is doing is
'eavesdropping'. Have you ever tried to secretly listen to the conversation between two
teachers regarding your class? If yes, then what you have done is 'eavesdropping'.
• By installing some receiver which captures the data while on its way.
Login-Password: By assigning login names and strong passwords to the users of a system,
it can be ensured that only authorized people access a computer. This helps in increasing
the computer as well as network security. A strong password is the one which is easy to
28
COMPUTER NETWORKING
remember for the user but difficult (almost impossible) for the others to guess
successfully. On the other hand a weak password is generally the name of a person or
organization, the registration number of a vehicle, year of birth of a person and so on. A
weak password can be cracked in a few attempts. Examples of strong passwords may be
raavanisdead (raavan is dead - with spaces removed), 2aur2paanch (name of an old Hindi
movie) or anything like that.
Anti Virus Software: These days anti-virus softwares work against not only the virus but
also against almost all kinds of malware. Therefore by installing a full version legal (not
the pirated one or freeware) anti-virus software network security can be increased.
Think of a hypothetical Educational Society (say XYZ Educational Society) with its head
29
COMPUTER NETWORKING
office in Chennai (Tamil Nadu) and schools in various parts of the globe. The society is
setting up a new senior secondary school, 'SF School', in Bahadurgarh (Haryana).
The 'SF School' will have 3 computer labs with 30 computers in each, 1 Accounts office
with 3 computers, 1 Administrative block with 5 computers, and 1 Principal's office with 1
computer. Let us see how a computer network can be set up in the school.
First of all we can draw a rough sketch of the school with computers at various locations
as follows:
Computer Lab1, Computer Lab2, Computer Lab3, Administrative Block, Accounts Office.
These LANs can be set up in STAR topology using UTP cable (economical, reliable, and
easily available). For this 1 switch (with suitable number of ports) will be required in
each of these buildings. More than one switches can be used in computer labs if a switch
with more than 30 ports is not available.
Two internet connections (broadband for high speed) can be procured in Administrative
Office. Two connections should be procured from two different ISPs so that
(i) Internet connection in Administrative office can be kept separate from the
other Computer labs where students may do a lot of experimentation.
(ii) If one internet connection is not working, the other can be used in case of
urgent requirements.
30
COMPUTER NETWORKING
Server (if any) of the school may be placed in Administrative block so that it remains safe
(physically) and a firewall can be set up so that the whole network remains safe from any
kinds of virus or intrusion attacks.
There is no need to do any extra efforts or expenses to link the school to its head office.
This can be taken care of using the internet connections.
SUMMARY
• A computer network is a collection of interconnected computers and other
devices which are able to communicate with each other.
• Communication Media are the links over which the data is sent from one node
to another over a network.
• Hardware devices used to form a network are: Cables, NIC, Hub, Switch,
Repeater, and Gateway.
• Repeaters are used to regenerate the signal which gets weakened during its
transmission. Repeater are generally used to connect two networks which are
more than 80 m apart.
31
COMPUTER NETWORKING
• Denial of service, snooping and intrusion are some common threats for network
security.
Future Trends
4G Technology
The scenario of how computers are networked is changing very fast. Before full
implementation of a technology, a new technology is visible at the horizon. One
such new technology is 4G. 4G stands for fourth generation of mobile technology.
Change from one generation to another involves a major advancement in the
technology used. 1G technology was used in the first mobile phones. 1G used
analog radio signals. 1G was introduced in 1980s and continued until 1992 when
2G was introduced. 2G technology used a digital format and introduced text
messaging. 2G also introduced data services for mobiles, starting with SMS. 3G
technology has introduced more efficient ways of carrying data, making it
possible to have faster web-services, live chat, fast downloading, video
conferencing etc. over mobile phones. Today we are living in the world of 3G.
Soon, 4G will rule the mobile market. Unlike previous generations of mobile
technology, 4G mobile technology will be used for internet access on computers
also, and it will be totally wireless! 4G will provide internet access, high quality
streaming video and "anytime, anywhere" voice and data transmission at a much
faster speed than 3G. The "anytime, anywhere" feature of 4G is also referred to
as "MAGIC" (Mobile multimedia; Anytime/anywhere; Global mobility support;
Integrated wireless solution; Customized personal services).
32
COMPUTER NETWORKING
Cloud Computing
This is an emerging area of demand based resource sharing, resulting into drastic
saving of energy and cost. This is also referred to as 'Green IT'.
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. Which of the following topologies is a combination of more than one topologies?
a. Bus b. Tree
c. Modem d. Microwaves
33
COMPUTER NETWORKING
7. Snooping is
8. A repeater
a. PANs b. LANs
a. A URL b. An IP address
2. What is meant be communication channels? Give two examples of guided media and
two examples of unguided media.
a. Setting up a LAN
g. Communication within a city and its vicinity where cost of cabling is too high.
34
COMPUTER NETWORKING
Factory A
Administrative
Sales Office
Office
Factory B
35
COMPUTER NETWORKING
Factory A to Factory B 50 m
Administrative Office 15
Factory A 25
Factory B 18
Sales Office 15
1. Suggest a cable layout of connections between the buildings so that each building is
directly connected to Administrative Office.
2. Suggest the most suitable place (i.e. building) to house the server of this production
unit with a suitable reason.
(i) Repeater
(ii) Hub/Switch
4. The Administrative office of this unit is to be linked with the head office situated in
Patiala (Punjab). What will be the most economical way to do this? Justify your
answer.
36
COMPUTER NETWORKING
LAB EXERCISES
1. Find the IP addresses of at least five computers in your school.
2. Find the MAC addresses of at least 2 computers in your lab. Then verify their
manufacturer's name on the net.
3. Find the layout of LAN in your school's labs. If you think some modifications can be
done in the layout, note these down in your notebook.
• All the computers in the school should have internet access. (The school does
not want to have any other new internet connection.)
• For internet access a computer should be dependent only on one point and not
on multiple points. It means that if the internet connection is active, any
computer should be able to access it directly irrespective of whether some
other computer in the school is ON or OFF.
• Any two computers in the school should be able to communicate with each
other irrespective of whether any other computer in the school is ON or OFF.
The job of each team is to design a layout for this new network structure. Each team
has to specify
37
COMPUTER NETWORKING
• How the design will be able to fulfill all the mentioned requirements.
2. Find the average price and specifications of each of the following network devices in
the market: Switch , Cable (UTP), LAN Card. Each team has to specify:
• Different types of switches available in the market, their prices, and number of
ports.
• Names of brands of UTP Cable available in the market, along with their prices.
• Different types of LAN cards available in the market along with their prices.
38
A PTE
H
2
R
C
Puzzle 2
Write the numbers 1 to 8 in the given circles so that no two numbers joined by a line differ
by 1.
Introduction
Computers and internet have transformed our lives. Software is required to work on a
computer but the software that we buy or download only comes in the compiled ready-
39
OPEN SOURCE CONCEPTS
to-run version. It is next to impossible to modify the compiled version of the software. At
times we feel the need to change certain features of the software but are unable to do so.
In this chapter we will study about software which are developed collaboratively and
they can be modified as well. Such software are available in many forms like Free
Software, Open Source Software (OSS), Free Open Source Software (FOSS) and
Free/Liberal Open Source Software (FLOSS).Well, have you noticed something common
in all these terms. That's right! It is the word free. People often correlate this word with
the cost. They think that these software are available for free. Practically, these software
can be acquired at very little or no cost. But, here, "free" means freedom to use.
These software can be studied, copied, redistributed freely and even modified according
to one's need without seeking any kind of permission. In order to modify such software the
developers also provide the source code to the users.
There do exist software which are actually "free" in the sense of price. These are known as
Freeware. Lots of freeware can be downloaded from the internet for various different
purposes such as currency converters, drawing graphs and charts etc. But freeware may
not come with the source code. Therefore freeware differ from free software. The focus
in this chapter is on free software rather than freeware.
The first formal definition of "free software" was given in 1983 by Richard Stallman, a long
time member of the hacker community at the MIT Artificial Intelligence Laboratory. He
insisted that a free software should give the following four freedoms to users:
• Freedom 1: The freedom to study how the program works, and change it to
make it do what you wish.
Examples of free software include the Linux Kernel, MySQL Relational Database, Apache
web server, OpenOffice.org office suite and TeX and LaTeX typesetting systems.
40
OPEN SOURCE CONCEPTS
Later on, the term "free software" was recoined as "open source software (OSS)" and soon
after as "free open source software (FOSS)". In order to avoid the ambiguity in the word
"free", in 2001, FOSS was termed as FLOSS, short form of "free/liberal open source
software".
Know More!
You can get more information on open source software from opensource.org.
NRCFOSS :
National Resource Centre for Free and Open Source Software (NRCFOSS) is an initiative of
the Department of Information Technology, Ministry of Communications & Information
Technology, Government of India. NRCFOSS contributes to the growth of FOSS in India
through Research & Development, Human Resource Development, Networking &
Entrepreneurship development, as well as serves as the reference point for all FOSS
related activities in the country.
Examples of FLOSS/FOSS :
41
OPEN SOURCE CONCEPTS
Office software
• Mozilla Foundation
Other
• Wine - a compatibility layer for computers running Linux that enables them to
run many applications that were originally written for MS Windows
Programming related
42
OPEN SOURCE CONCEPTS
• Python - versatile, clean and powerful programming language used for cross-
platform desktop applications, server-side scripting for websites, and scripting
within java and .net environments
43
OPEN SOURCE CONCEPTS
"If anyone can contribute to open source software, doesn't it become a free-for-all
full of loopholes?"
The Answer is while anyone can propose a contribution to an open source project, any
actual change must go through a small core group of maintainers first. Getting a change
incorporated into an open source project is thus rather like getting an article published in
a scientific journal.
Open source software is more heavily tested than their commercial counterparts as it can
be downloaded by anybody around the world and any one of them can discover a bug or
security flaw and submit those reports back to the project.
44
OPEN SOURCE CONCEPTS
Also since it's an Open Source, if any bug or flaw is found, project's core maintainers,
while potentially embarrassed, have no further reason to cover up the flaw like their
proprietary counterpart. Also the loop-hole or bug is available to every one and the
customer can take the preventive measure accordingly and fix comes faster.
The Open Document format (ODF) is a format for office documents, such as spreadsheets,
databases, presentations and word-processing documents. Open Document is a free and
open format. For governments, businesses, archivists and others, it's critical to store
documents in a way that can be read for years to come. Proprietary digital file formats
are typically changing with every new version of the software, so there should be some
format which supports files created in any application. The data should be the center of
importance not the application. Office suite applications, as always, need a file format
that is designed to organize the data when it moves away from the application. People
with different machines in different places should be able to open and edit the data in a
file. ODF offers an open alternative to the formats used by all of the existing Office
application versions for text, spreadsheet, presentation, and other kinds of documents.
Open Document's main file extensions are .odt (for text documents), .ods (for
spreadsheets), and .odp (for presentations). These will be more commonly recognized
when more people and organizations adopt Open Document-ready software.
Ogg Vobris
Character Encoding
A character encoding system consists of a code that associates each character from a
given system with something else, such as a sequence of natural numbers, binary
numbers or electrical pulses, in order to facilitate the transmission of data (generally
numbers and/or text) through telecommunication networks or for storage of text in
45
OPEN SOURCE CONCEPTS
computers. ASCII, EBCDIC, and UNICODE are the most widely used character encoding
systems for computers.
On one hand, more and more work had been undertaken to facilitate the use of Indian
languages on computers but on the other hand it was becoming difficult to maintain
consistency across different programs developed for the same set of Indic characters. In
such a scenario, it was important to have a common standard for coding Indian scripts. In
1991, the Bureau of Indian Standards (BIS) adopted the Indian Script Code for Information
Interchange (ISCII), the ISCII standard that was evolved by a standardization committee,
under Department of Electronics during 1986-88.
ISCII is an 8 bit encoding system as compared with the 7 bit ASCII. The lower 128 code
points are plain ASCII while the upper 128 code points are ISCII specific containing the
basic alphabets required for the 10 Indian scripts (Assamese, Bengali, Devanagari,
Gujarat, Gurmukhi, Kannada, Malayalam, Oriya, Tamil and Telugu) which have originated
from the Brahmi script.
46
OPEN SOURCE CONCEPTS
Know More!
UNICODE
For a long time ASCII has been the standard code used worldwide. ISCII was the Indian
contribution to work with Indian languages. Similarly, to work with other languages of the
world, people were making efforts to use ASCII along with the extra 8th bit. Efforts were
continued to conceive a single standard code which could cater to all world's languages
and it was UNICODE.
Unicode was developed with the aim to conceive a single standard code which could
manage to represent all languages of the world.
Unicode characters are represented in one of the three encoding forms: a 32-bit form
(UTF-32), a 16-bit form (UTF-16), and an 8 bit form (UTF-8). The 8-bit, byte oriented
form, UTF-8, has been designed for ease of use with existing ASCII-based systems.
Advantages of Unicode
• With the usage of Unicode, single versions of software were developed instead
of language-specific versions that reduced the complexity.
47
OPEN SOURCE CONCEPTS
This font format was developed by Adobe in 1980's. This font consists of two parts which
are both necessary for the font to be properly printed and displayed on screen. With most
operating systems, these fonts can be installed simply by being placed in the system's
folder. However, for Micro Soft operating systems predating windows 2000, they need to
be installed using ATM (Adobe Type Manager) utility.
True Type
This format was jointly developed by Apple and Microsoft in the late 80s. These fonts
contain both the screen and printer font data in a single component, making the fonts
easier to install. And that is why these are a good choice for those who find the
installation of fonts difficult.
Open Type
This is the latest font format which is a joint effort by Apple and Microsoft. Like True Type
fonts, this contains both the screen and printer font data in a single component. However,
open type fonts support multiple platforms and expanded character sets. Additionally,
open type format allows the storage of upto 65,000 characters. This additional space
provides freedom to include add-ons such as small caps, old style figures, alternate
characters and other extras that previously needed to be distributed as separate fonts.
However, not all open type fonts contain additional characters. Many fonts have been
converted from either PostScript or TrueType formats without expanded character sets to
take advantage of the cross-platform functionality benefits of Open Type. OpenType
fonts that do contain expanded character sets are referred to informally as OpenType Pro
fonts. Support for OpenType Pro fonts is increasing, but the format is yet to be fully
supported by all applications.
48
OPEN SOURCE CONCEPTS
Static fonts - In these types of fonts the characters are designed and digitized and then
stored in font files. Every time printing takes place, same character will appear with
same shape e.g. Times New Roman, Arial etc.
Dynamic fonts - Dynamic font is a web browser technology used when visiting any
website that uses fonts which are not installed on client's machine. The web browser
would not be able to display the page properly, but will select one of fonts available on
client machine. In this the characters are redefined at each occurrence (everytime they
are displayed or printed). All hand written fonts such as handwritten alphabets,
calligraphic letters, graffiti etc are dynamic fonts because of individual variations.
49
OPEN SOURCE CONCEPTS
Indian language keymaps are known as INSCRIPT keymaps or Indian Script Keymaps.
The ASCII characters of a standard QWERTY keyboard are on the left half of a key. The INSCRIPT
(Indian Script) overlay characters are shown on the right half of a key. CAPS LOCK is used to select
the INSCRIPT overlay.
When Nukta "-" is typed after character, the character shown to its left on the
key, is obtained.
50
OPEN SOURCE CONCEPTS
Know More!
Future Trends
At present very few open source endeavors which involve few people are there and
are largely unstructured and undisciplined. But as this concept matures in future
more OSS projects will come up and will adopt more structured methodologies to
code, control and coordinate. In future this concept will be adopted at a big level
by private and government sector. This will force companies to embrace open
source and will force the open source community to innovate in line with more
complex need of government and business.
51
OPEN SOURCE CONCEPTS
Summary
• Free and open source software, also OSS, FOSS, or FLOSS (free/libre open
source software) is software that is liberally licensed to grant the user right to
use, study, change, and improve its design through the availability of its source
code.
• NRCFOSS - National Resource Centre for Free and Open Source Software.
• ODF (Open Document Format) offers an open alternative to the formats used
by all of the existing software.
• ISCII - Indian Script Code for Information Interchange is common standard for
coding Indian Scripts.
• UNICODE - Universal Code is a single standard code which can cater to all the
world's languages.
• Post Script font consists of two parts which are both necessary for the font to be
properly printed and displayed on screen.
• True type fonts contain both the screen and printer font data in a single
component.
• Open type fonts support multiple platforms and expanded character sets.
• On the basis of their configuration, fonts are categorized as static fonts and
dynamic fonts.
• For entering text in Indian script keymap based or phonetic text based entry
can be done.
52
OPEN SOURCE CONCEPTS
EXERCISES
MULTIPLE CHOICE QUESTIONS
53
OPEN SOURCE CONCEPTS
7) ISCII is
54
OPEN SOURCE CONCEPTS
8) What is UNICODE?
LAB EXERCISES
1) Find out which software in your school lab are open source.
2) Procure BOSS and install it (with the permission of your teacher) on your computer
and write down the features which are similar to windows and also which are not
similar to windows.
55
A PTE
H
3
R
C
• Identify, name and state the usage of the different components of the
NetBeans IDE.
• Identify and name the various methods and properties associated with the
various form controls
Puzzle 3
This group of phrases has something amazing hidden in it. Try and find out what is so
unusual about this group of phrases? Is there any specific pattern in each line? *
Bar crab
Borrow or rob
Straw warts
56
GUI PROGRAMMING - A REVIEW
Live evil
Delia failed.
Evil olive
Step on no pets.
We found an interesting pattern in the puzzle and we will use this concept to develop an
application in netbeans.
Introduction
Let us take a journey back in time and think as to what the world was like 15 years ago.
Amazon was a large river in South America. Yahoo was a term from Gulliver's Travels. A
googol was a very large number (one followed by a hundred zeroes) and to get our tickets
booked we had to go to shops called 'travel agents'. In case we fell sick and went to a
hospital, our records were maintained on paper. If the doctor wanted to refer to a
particular patient's record, he had to instruct a assistant to hunt for information from the
pile of files.
Nowadays hospitals use computers to keep the records of patients - medical history,
details on what medication to give to a patient, the prescribed dosage and also personal
details that can be accessed at the click of a button. The entire information is entered
into a computer using a front end that accepts the different patient details. We learnt
how to design valid front end forms in class XI in Java using the NetBeans IDE. This chapter
will help us recapitulate all the concepts learnt in class XI.
57
GUI PROGRAMMING - A REVIEW
NetBeans IDE
It can be used to create java applications very easily using the efficient GUI builder. Let us
quickly recap the different components of the NetBeans IDE:
1. Title Bar
3. Toolbars
4. GUI builder: It is an area to place components on the form visually. There are two
views of the GUI builder- the Design View and the Source View. We can switch over
from one view to another by simply clicking on the source and design tabs directly
above the Design Area.
58
GUI PROGRAMMING - A REVIEW
6. Inspector Window: This window is used to display a hierarchy of all the components
or controls placed on the current form.
7. Properties Window: Using this window we can make changes in the properties of
currently selected control on the form.
8. Code Editor Window: - It is the area where we write code for our java application.
Components
Components (also known as "widgets") are the basic interface elements the user interacts
with: jlabels, jbuttons, jtextfields etc. Components are placed on a container (like the
jFrame). There are two types of controls :
• Parent or container controls: They act as a background for other controls. For
example-Frame. When we delete a parent control, all its child controls get
deleted. When we move a parent control all its child controls also move along
with it.
• Child controls: controls placed inside a container control are called child
controls. For example-Text Field, Label, Button etc.
Child controls
59
GUI PROGRAMMING - A REVIEW
1. Select New Project from the File menu. You can also click the New Project button in
the IDE toolbar.
2. In the Categories pane, select the General node. In the Projects pane, choose the
Java Application type. Click the Next button.
3. Enter the name of the project in the Project Name field and specify the project
location. Do not create a Main class here.
Let us recap the relation between a Project, Form and Components. Each application is
treated as a Project in NetBeans and each project can have one or multiple forms and this
fact is clear from the Projects window as shown in Figure 3.3.
Project Name
Multiple Forms
under one Project
Further each form can have one or more elements - some of which may be visible and
some invisible. The visible components are all shown under the Frame Component and
the non-visible components are part of Other components.
We use the drag and drop feature of NetBeans to place components on the form to design
an effective interface for our applications. The first step that we undertook while
designing our applications was adding a new jFrame form. The jFrame is a window with
60
GUI PROGRAMMING - A REVIEW
title, border, (optional) menu bar and is used to contain all other components placed by
the user on the form. Some of the properties of the jFrame form are
defaultCloseOperation and Title.
Property Description
61
GUI PROGRAMMING - A REVIEW
control, an event happens and that event invokes (sends a call to) the corresponding part
of the code and the application behaves accordingly.
After setting the properties of the jFrame we can start placing components like jButton
on the jFrame form. A button is a component that the user presses or pushes to trigger a
specific action. When the user clicks on the button at runtime, the code associated with
the click action gets executed. The various methods and properties associated with the
jButton are summarized in Figure 3.5.
Property Description
Background Sets the background color.
Enabled Contains enabled state of component - true if enabled
else false.
Font Sets the font.
Foreground Sets the foreground color.
horizontal alignment Sets the horizontal alignment of text displayed on the
button.
Label Sets the display text.
Text Sets the display text
Method Description
getText() Retrieves the text typed in jButton.
String result=<button-name>.getText( );
62
GUI PROGRAMMING - A REVIEW
We developed simple real life applications wherein on the click of the button we
accepted the data from the user in the jTextField and after processing the data the result
was displayed in a jTextField or a jLabel. jTextField allows editing/displaying of a single
line of text. jTextField is an input area where the user can type in characters whereas a
jLabel provides text instructions or information. It displays a single line of read-only text,
an image or both text and image. The various methods and properties associated with the
jTextField and jLabel are summarized in Figure 3.6 and 3.7 respectively.
Property Description
Border Sets the type of border that will surround the text field.
toolTipText Sets the text that will appear when cursor moves over
the component.
Method Description
getText() Retrieves the text in typed in jTextField.
String result=<textfield-name>.getText( );
63
GUI PROGRAMMING - A REVIEW
setEditable Sets whether the user can edit the text in the textField.
true if editable else false.
<textfield-name>.setEditable(boolean b);
Property Description
64
GUI PROGRAMMING - A REVIEW
Method Description
When we had become familiar with the usage of jTextField and jLabel controls then we
developed an application in which we wanted to accept multiline input and display
multiline output. Well can you recall the name of the component. Exactly the component
is Text Area component. This component allows us to accept multiline input from the user
or display multiple lines of information. This component automatically adds vertical or
horizontal scroll bars as and when required during run time. The various methods and
properties associated with the jTextArea are summarized in Figure 3.8.
Property Description
65
GUI PROGRAMMING - A REVIEW
Method Description
append() Adds data at the end.
<textarea-name>.append(String str);
getText() Retrieves the text in typed in jTextArea.
String str = <textarea-name>.getText();
isEditable() Returns true if the component is editable else returns
false.
boolean b = <textarea-name>.isEditable();
isEnabled() Returns true if the component is enabled, else returns
false.
boolean b = <textarea-name>.isEnabled();
setText() Changes the display text at runtime.
<textarea-name>.setText(String t);
66
GUI PROGRAMMING - A REVIEW
Property Description
Well we used radio buttons when we wanted to provide the user several choices and
allowed him to select one of the choices (the radio buttons belong to a group allowing the
user to select single option). But radio buttons occupy a lot of space. Thus, in case of too
many options we used Combo boxes as they help save space and are less cumbersome to
design as compared to radio button. We used check box and list when we wanted to
display multiple options like selecting favourite sports or ordering multiple food items in
a restaurant. The list is a preferred option over check box in situations wherever multiple
options are required to be selected from a large number of known set of options as they
help save space and are less cumbersome to design as compared to check boxes. The
properties and methods of jRadioButton are summarized below:
Property Description
background Sets the background color.
buttonGroup Specifies the name of the group of button to which the
jRadioButton belongs.
enabled Contains enabled state of component -true if enabled else false.
font Sets the font.
foreground Sets the foreground color.
label Sets the display text.
text Sets the display text.
Selected Sets the button as selected, if set to true, default is false.
67
GUI PROGRAMMING - A REVIEW
Method Description
jCheckBox is a small box like component that is either marked or unmarked. When you
click on it, it changes from checked to unchecked or vice versa automatically. The
properties and methods of jCheckBox are summarized below:
Property Description
background Sets the background color.
buttonGroup Specifies the name of the group of button to which the
jCheckBox belongs.
font Sets the font.
foreground Sets the foreground color.
label Sets the display text.
text Sets the display text
selected Sets the check box as selected if set to true, default is
false.
68
GUI PROGRAMMING - A REVIEW
Method Description
getText() Retrieves the text typed in
String str = <checkbox-name>.getText();
Property Description
background Sets the background color.
buttongroup Specifies the name of the group of button to which the
jComboBox belongs.
editable If set true user can edit ComboBox. Default is true.
enabled Contains enabled state of component- True if enabled else false.
font Sets the font.
foreground Sets the foreground color.
model Contains the values to be displayed in the combobox.
text Sets the display text
selectedIndex Sets the index number of the element which should be selected
by default.
selectedItem Sets the selected item in the combobox. selectedItem and
selectedIndex are in synchronization with each other.
69
GUI PROGRAMMING - A REVIEW
Method Description
setModel() Sets the data model that the combo box uses to get its
list of elements.
<combobox-name>.setModel
(ComboBoxModel aModel);
Property Description
70
GUI PROGRAMMING - A REVIEW
Method Description
We used JOptionPane when we wanted to request information from the user, display
information to the user or a combination of both. It required an import statement at the
top of the program. Well can you recollect the import statement? That's right it is:
import javax.swing.JOptionPane;
OR
import javax.swing.*;
Either of them is acceptable. The difference is that the latter will import the entire
library as denoted by the star whereas the first statement will just import the
JOptionPane library.
Method Description
showMessageDialog() Shows a one-button, modal dialog box that gives the user
some information.
Example :
JOptionPane.showMessageDialog(this,"Java
and NetBeans");
71
GUI PROGRAMMING - A REVIEW
Example:
Confirm=
JOptionPane.showConfirmDialog(null,"quit?")
showInputDialog() Shows a modal dialog that prompts the user for input. It
prompts the user with a text box in which the user can enter
the relevant input.
Example :
name=
JOptionPane.showInputDialog(this,"Name:");
Variables help us to hold value for some input coming from the user or to
hold intermediate result of some calculation or the final result of an
operation. In other words, variables are like containers that can be used to
store whatever values are needed for a specific computation. However, as
different materials require different containers, and so we used different
data types to hold different values.
72
GUI PROGRAMMING - A REVIEW
Java programming language requires that all variables must first be declared
before they can be used.
When programming, we store the variables in our computer's memory, but the computer
has to know what kind of data we want to store in them, since it is not going to occupy the
same amount of memory to store a simple number or to store a single letter or a large
number, and they are not going to be interpreted the same way so variables were used
along with datatypes. The data types supported by java are summarized as follows:
Data type states the way the values of that type are stored, the operations that can be
done on that type, and the range for that type.
73
GUI PROGRAMMING - A REVIEW
The decision about which numeric data type to use should be based on the range of values
that a variable can take.
These data types are used to store characters. Character data types can store any type of
values - numbers, characters and special characters. When we want to store a single
character, we use char data type and when we want to store a group of characters we use
string data type. For example to store grades (A, B, C, D, E) of a student we will use char
type but to store name of a student, we will use string type. The char data type value is
always enclosed inside ' ' (single quotes), whereas a string data type value is enclosed in " "
(double quotes).
Operators
With the introduction of variables and constants there arose a need to perform certain
operations on them. We performed operations on variables and constants using
operators. The operators available in java are summarized below:
Assignment Operator :
One of the most common operator is the assignment operator "=" which is used to assign a
value to a variable. We assign the value given on the right hand side to the variable
specified on the left hand side. The value on the right hand side can be a number or an
arithmetic expression. For example:
int sum = 0;
int prime = 4*5;
Arithmetic Operators :
These operators perform addition, subtraction, multiplication, and division. These
symbols are similar to mathematical symbols. The only symbol that is different is "%",
which divides one operand by another and returns the remainder as its result.
+ additive operator
- subtraction operator
74
GUI PROGRAMMING - A REVIEW
* multiplication operator
/ division operator
% remainder operator
Relational Operator :
A relational operator is used to test for some kind of relation between two entities. A
mathematical expression created using a relational operator forms a relational
expression or a condition. The following table lists the various relational operators and
their usage:
75
GUI PROGRAMMING - A REVIEW
Unary Operators :
The unary operators perform different kind of operations on a single operand .The
operations performed are increasing/decreasing a value, negating a value/ expression,
or inverting a boolean value.
Increment/Decrement Operators :
The increment/decrement (++,--) operators can be a prefix or a postfix. In a pre
increment/decrement expression (++ x or -- x), an operator is applied before an operand
while in a post increment/decrement expression (x++ or x --) an operator is applied after
an operand. In both conditions 1 is added to the value of the variable and the result is
stored back to the variable. However, in a prefix expression, value is incremented first
then this new value is restored back to the variable. In postfix expression the current
value is assigned to a variable then it is incremented by 1 and restored back to the original
variable.
Let us now try and recollect the conversion methods that we have used in java. When a
Java program receives input data from a user, it must often convert it from one form
(e.g., String) into another (e.g., double or int) for processing.
Conversion methods
• To convert a string value to a number (For example, to convert the String value in a
text field(jTextField1) to an int, long, float or double), we can use parse methods.
Assume the following declarations:
String num1=jTextField1.getText();
int sum; long product;
float amount; double simple_int;
76
GUI PROGRAMMING - A REVIEW
int sum=Integer.parseInt(jTextField1.getText());
long product=Long.parseLong(num1);
long product=Long.parseLong(jTextField1.getText());
float amount=Float.parseFloat(num1);
float amount=Float.parseFloat(jTextField1.getText());
double simple_int=Double.parseDouble(num1);
OR
simple_int=Double.parseDouble(jTextField1.getText());
• To convert a number to string we used valueOf method. Assume the following code:
int i = 100;
double d = 400.0;
long l = 100000;
77
GUI PROGRAMMING - A REVIEW
• To convert a number to string, we also used toString method. Assume the following
code :
int i = 100;
double d = 400.0;
long l = 100000;
78
GUI PROGRAMMING - A REVIEW
Control Structures
We used control structures when we wanted to control the flow of the program. We learnt
two types of control structures in class XI namely, Selection statements and Iteration
statements.
Control structures allow us to control the flow of our program's execution. If left
unchecked by control-flow statements, a program's logic will flow through
statements from top to bottom. We can have some control on the flow of a
program by using operators to regulate precedence of operations, but control
structures provide the power to change statement order and govern the flow of
control in a program.
Selection Statements:
A selection statement selects among a set of statements depending on the value of a
controlling expression. The selection statements are the if statement and the switch
statement, which are discussed below:
Simple if Statement - The if statement allows selection (decision making) depending
upon the outcome of a condition. If the condition evaluates to true then the statement
immediately following if will be executed and otherwise if the condition evaluates to
false then the statements following the else clause will be executed. The selection
statements are also called conditional statements or decision statements.
The syntax of if statement is as shown below:
Syntax:
if (conditional expression)
{
Statement Block;
}
else
{
Statement Block;
}
79
GUI PROGRAMMING - A REVIEW
• The else clause is optional and needs to be included only when some action is to
be taken if the test condition evaluates to false.
Nested if . . . else - These control structures are used to test for multiple conditions as
against the simple if statement which can be used to test a single condition. The syntax of
nested if else is as follows:
Syntax:
if (conditional expression1)
{
statements1;
}
else if (conditional expression2)
{
statements2;
}
else if (conditional expression3)
{
statements3;
}
else
{
statements4;
}
80
GUI PROGRAMMING - A REVIEW
1. Add a new JFrame Form and change its title property to Quick Multiple Checker.
4. Add three radio buttons on the form - Set the text of each of them as "Multiple of 3",
"Multiple of 5" and "Multiple of 7".Group the radio buttons so that only one can be
selected.
In this application we ask the user to enter a number and then the user will select one of
the radio buttons and depending upon the button selected the multiple check for that
number will be performed. Let us now write the code for the above mentioned
application. Code to check for multiple of 3 is given. Try and write the code to perform a
similar check for multiple of 5 and multiple of 7.
81
GUI PROGRAMMING - A REVIEW
private void
jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
double Number=Double.parseDouble(jTextField1.getText());
if (Number%3==0)
JOptionPane.showMessageDialog(this,"It is multiple of 3");
else
JOptionPane.showMessageDialog
(this,"It is NOT multiple of 3");
}
• retrieves the value entered by the user in the text field using getText().This
value by default is treated as a string and not as a number so it needs to be
converted to a double type and this is achieved using the parseDouble()
method.The value is then stored in the variable Number.
if (Number%3=0)
• check whether the number when divided by 3 gives 0 as the remainder.If the
remainder is zero then the number is divisible by 3 else it is not.
Switch Statement - This selection statement allows us to test the value of an expression
with a series of character or integer values. On finding a matching value the control
jumps to the statement pertaining to that value and the statement is executed, till the
break statement is encountered or the end of switch is reached. The expression must
either evaluate to an integer value or a character value. It cannot be a string or a real
number. The syntax of the switch statement is as follows:
82
GUI PROGRAMMING - A REVIEW
switch (Variable/Expression)
{
case Value1:statements1 ;
break ;
case Value2:statements2 ;
break ;
.
.
default:statements3 ;
}
Comparing Switch and If..else Statements - Switch is used to select sections of code
depending on specific integer or character values. If we are handling specific coded
values (eg, the number of the button that was clicked in a JOptionPane), or processing
characters(whose codes are treated like numbers), then switch is useful. The limitations
of switch are as follows:
• It requires either integers or characters and doesn't allow useful types like
String.
83
GUI PROGRAMMING - A REVIEW
case 2: comment =
"You're quite competent for so little experience.";
break;
default: comment =
"Oops -- something is wrong with this code.";
Equivalent if statement
if (choice == 0)
else if (choice == 1)
else if (choice == 2)
else
A switch statement can often be rewritten as an if statement. Let us look at the example
given above, when a selection is to be made based on a single value, the switch statement
is generally easier to read. The switch is useful when you need to manage a lot of if /else
if / else. It has a shorter syntax and is more appropriate in this case.
Let us now design an application in which we will calculate the selling price depending
upon the profit percent selected by the user. Design the application as shown in figure
3.26. Set the relevant properties of the components.
84
GUI PROGRAMMING - A REVIEW
In this application depending upon the profit percent selected by the user we will
calculate the selling price .Let us now write the code.
//Business Calculator
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
double CP,Profit=0,SP;
CP=Double.parseDouble(jTextField1.getText());
Profit=jComboBox1.getSelectedIndex();
SP=CP+CP*(Profit/100);
jTextField2.setText(Double.toString(SP));
85
GUI PROGRAMMING - A REVIEW
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
jTextField1.setText("");
jComboBox1.setSelectedIndex(0);
jTextField2.setText("");
• retrieves the value entered by the user in the text field using getText().This
value by default is treated as a string and not as a number so it needs to be
converted to a double type and this is achieved using the parseDouble()
method. The value is then stored in the variable CP.
jComboBox.getSelectedIndex()
• retrieves the index of the selected item so if the user selects 1st item profit is 0
and if the user selects 3rd, item profit is 2.This value is saved in a variable
profit.
SP=CP+CP*(Profit/100)
86
GUI PROGRAMMING - A REVIEW
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
double CP,Profit=0,SP;
CP=Double.parseDouble(jTextField1.getText());
switch (jComboBox1.getSelectedIndex())
{
case 0:Profit=5;break;//if first item selected profit is 5
case 1:Profit=10;break;//if second item selected profit is 10
case 2:Profit=15;break;
case 3:Profit=20;break;
case 4:Profit=25;break;
default:Profit=0;break;
}
Figure 3.29 Code for Business Calculator version 1.2
87
GUI PROGRAMMING - A REVIEW
Iteration Statements :
These statements are used to perform a set of instructions repeatedly while the
condition is true. Iteration statements are also called looping statements.
for loop - The loop has four different elements that have different purposes. These
elements are:
a) Initialization expression: Before entering in a loop, its variables must be
initialized.
b) Test Expression: The test expression decides whether the loop body will be
executed or not. If the test condition is true, the loop body gets executed otherwise
the loop is terminated.
c) Increment/Decrement Expression: The Increment/Decrement expression changes
the value of the loop variable.
d) The Body of the loop: The statements, which are executed repeatedly while the
test expression evaluates to true form the body of the loop.
The syntax of the for loop is:
Syntax
for( initialization; test exp; increment/decrement exp)
{
statements;
}
The three expressions inside the round braces of for loop are optional. Using this fact an
infinite loop can be created as follows:
for (int I = 1 ;I <= 5 ;I++ )
{
jTextArea1.setText (jTextArea1.getText()+I);
//It will display 12345 in jTextArea1
}
88
GUI PROGRAMMING - A REVIEW
While Loop - The while loop is an entry-controlled loop. It means that the loop condition
is tested before executing the loop body. If the loop condition is initially false, for the
first iteration, then loop may not execute even once. The main characteristic of the
while loop is that it can be used in both cases i.e. when the number of iterations is known
as well as when it is unknown. The syntax of the while loop is as follows:
Syntax
while(test expression)
loop body
Remember that in while loop, a loop control variable should be initialized before the loop
begins and the loop variable should be updated inside the body of the while loop (else it
will become an endless loop).
Do..While Loop - Do..While loop is an exit-controlled loop. In the do..while loop, the test
occurs at the end of the loop. This ensures that the do..while loop executes the
statements included in the loop body at least once. After the first execution of the
statement, it evaluates the test expression. If the expression evaluates to true, then it
executes the statements of the loop body again. Like if and while statements, the
condition being checked must be included between parenthesis. The while statement
must end with a semicolon. The syntax of the loop is as follows:
Syntax
do
loop body
89
GUI PROGRAMMING - A REVIEW
Comparing Do…While and While - The difference between do-while and while is that do-
while evaluates its expression at the end of the loop instead of at the beginning.
Therefore, the statements within the do block are always executed at least once. Do-
while is an exit controlled loop and while is an entry controlled loop.
int ctr;
ctr=0;
JOptionPane.showMessageDialog(this,ctr);
// Display Number
ctr = ctr + 1;
// Increment LoopCounter
The same code is written using do while. In do while counter is checked at the end of loop
body,therefore loop body is executed at least once.
int ctr = 0;
do // Loop Begins
JOptionPane.showMessageDialog(this,ctr);
// Display Number
ctr = ctr + 1;
// Increment LoopCounter
90
GUI PROGRAMMING - A REVIEW
Let us now develop a few applications which will help us to strengthen our programming
concepts learnt in class XI.
Let us now design an application in which we will generate the series and its sum. Design
the application as shown in figure 3.30. Set the relevant properties of the components.
2+4+6+8+10
2+7+12+17+22
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
int Start,Step,Terms,Sum=0;
Start=Integer.parseInt(jTextField1.getText());
91
GUI PROGRAMMING - A REVIEW
Step =jComboBox1.getSelectedIndex()+1;
//step in the series
Terms=Integer.parseInt(jTextField2.getText());
// no of terms
for (int I=1;I<=Terms;I++)
{
Sum+=Start;
Start+=Step;
}
jTextField3.setText(Integer.toString(Sum));
}
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
//Index -1 indicates no selection
jComboBox1.setSelectedIndex(-1);
}
Figure 3.31 Code to generate the series and the Sum of Series
• retrieves the value entered by the user in the text field using getText().This
value by default is treated as a string and not as a number so it needs to be
converted to an integer type and this is achieved using the parseInt() method.
The value is then stored in the variable Start.
92
GUI PROGRAMMING - A REVIEW
jComboBox.getSelectedIndex()+1
• retrieves the index of the selected item so if the user selects 1st item as Step
then 1 is added to the index value of the 1st item. This value is saved in a
variable Step.
Integer.parseInt(jTextField1.getText())
• retrieves the value entered by the user in the text field using getText().This
value by default is treated as a string and not as a number so it needs to be
converted to an integer type and this is achieved using the parseInt()
method.The value is then stored in the variable Terms.
Now we have the value from where the user wants to start the series, the terms in the
series and the step between numbers of the series.
for (int I=1;I<=Terms;I++)
{
Sum+=Start;
Start+=Step;
}
jTextField3.setText(Integer.toString(Sum));
• the for loop is executed as many times as the Terms and the Step is added to
Start which in turn is added to Sum and finally the Sum of the numbers is
displayed.
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jComboBox1.setSelectedIndex(-1);
• On clicking the reset button all the three textfields are set to "" and the
setselectedIndex value of combobox is set to -1. Index -1 indicates that no item
is selected.
93
GUI PROGRAMMING - A REVIEW
Let us now develop an application to reverse the given number and also find out whether
the number is a palindrome or not.(The pattern that we found in the phrases was that
each line had a palindrome hidden in it.)
Let us now write the code for reversing a given number and check whether the given
number is a palindrome or not.
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
long Number,Temp,RevNumber=0;
Number=Long.parseLong(jTextField1.getText());
Temp=Number;
94
GUI PROGRAMMING - A REVIEW
RevNumber=(RevNumber*10)+(Temp%10);
Temp=Temp/10;
jTextField2.setText(Long.toString(RevNumber));
if (Number==RevNumber)
JOptionPane.showMessageDialog
(this,"Number is Palindrome");
else
JOptionPane.showMessageDialog
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
jTextField1.setText("");
jTextField2.setText("");
95
GUI PROGRAMMING - A REVIEW
• retrieves the value entered by the user in the text field using getText().This
value by default is treated as a string and not as a number so it needs to be
converted to long type and this is achieved using the parsetLog() method. The
value is then stored in the variable Number.
Temp=Number
• while loop will continue as long as temp is greater than zero. In this loop we
divide temp by 10 and obtain the remainder. The remainder is then added to
the value in the variable RevNumber multiplied by 10.Initially
RevNumber=0.The value of variable temp is divided by 10 every time the loop
is executed. The loop is executed as long as temp is greater than 0.
if (Number==RevNumber)
JOptionPane.showMessageDialog
(this,"Number is Palindrome");
else
JOptionPane.showMessageDialog
(this,"Number is not Palindrome");
• If the reverse of the number, which is stored in variable RevNumber and the
number entered by the user which is stored in Number are the same then the
number is a palindrome otherwise it is not a palindrome.
96
GUI PROGRAMMING - A REVIEW
We have revised the concepts learnt in class XI. Now in the next few chapters we will
enhance our knowledge of NetBeans and delve further into programming concepts.
Summary
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. What will be the output of the program given below. Which number is printed twice?
int sum1 = 3;
sum1++;
jTextField1.setText(""+sum1);
++sum1;
jTextField2.setText(""+sum1);
jTextField3.setText(""+(++sum1));
97
GUI PROGRAMMING - A REVIEW
jTextField4.setText(""+sum1++);
jTextField5.setText(""+sum1);
a. 5 b. 6
c. 4 d. 7
if (anumber >=10){
if (anumber == 10)
jLabel1.setText("first string");
jLabel2.setText("third string");
3. What value for X above will print EXACTLY 20 lines to standard output :
int count = 0;
while(count++ < X ) {
a. 0 b. 5
c. 10 d. 11
4. What will be the value of total after the loop finishes execution.
98
GUI PROGRAMMING - A REVIEW
total += count;
a. 10 b. 16
c. 45 d. 36
6. If there is more than one statement in the block of a for loop, which of the
following must be placed at the beginning and the ending of the loop block?
int a = 11;
int b = 22;
int c = 33;
int d = 11;
99
GUI PROGRAMMING - A REVIEW
vii) a >= c
100
GUI PROGRAMMING - A REVIEW
LAB EXERCISES
1. Design a GUI application in which the user enters a number in the text field and on
clicking the button the sum of the digits of the number should be displayed in a
label.
Hint : Suppose user enters 123 the output should be 6(1+2+3).
2. Design a GUI application to accept a String from the user in a text field and print
using option pane whether it is a palindrome or not.
3. Design a GUI application to accept the cost price and selling price form the user in
two text fields then calculate the profit or loss incurred.
4. Design a GUI application to accept a character in a text field and print in a label if
that character is a vowel: a, e, i, o, or u. The application should be case sensitive.
5. Design a GUI application that repeatedly accepts numbers in a option pane and once
the typed number is 0 the maximum and minimum of all numbers typed are
displayed.
7. Design a GUI application in java to convert kilograms into grams, litres into
milliliters, rupees into paisa using combobox and text fields.
Bookseller - 25%
School - 20%
Customer - 5%
101
GUI PROGRAMMING - A REVIEW
Basic DA HRA
2. Students will visualize the details that have to be provided while developing a
domicile certificate for a student of class XII. Each team has to design the form using
NetBeans IDE. The team has to specify the following:
102
A PTE
H
BASICS OF OBJECT
4
R
C
ORIENTED PROGRAMMING
Learning Objectives
Over the last lesson, we have reviewed the core Java language. We have learnt
how to work with variables and data, perform operations on that data, make
decisions based on the data and also loop repeatedly over the same section of
code. Now we will move on to learn a concept that is central to Java, namely
Object Oriented Programming. Object Oriented Programming is a very user
friendly yet a powerful approach to solve basic to difficult problems. The idea
was created for developing a language that could be used for system
description (for people) and system prescription (as a computer program
through a compiler). There are several object-oriented languages. The three
most common ones are, Smalltalk, C++ and Java.
Puzzle 4
A student and a lady are travelling in a train. They get around talking and the lady decides
to give a puzzle to the student. She tells him that she has 3 children whose product of ages
is equal to the maximum number of runs possible to score in an over without any
illegitimate ball being bowled (i.e. NB, Wide, etc). Also, the sum of their ages is equal to
her berth number. However, the student isn't able to answer. The lady then gives him a
further hint that the eldest of her children has only one eye. At this information, the
103
BASICS OF OBJECT ORIENTED PROGRAMMING
student knows the ages of the three children. Without knowing the lady's berth number,
can you guess the ages of her children?
Introduction
James Alexander is a resident of a developed nation and works as a freelance consultant.
He is hired by one of the corporate houses of a developing nation to plan a strategy to
improve production in one of their factories which is located in a remote village named
Khabri. The consultant decides to submit a quick action plan and so starts searching for
information about the remote village. He has never visited any of the remote locations
and so tries to simply imagine the problems faced by remote people. Mohan Swamy is a
resident of one of the developing countries and he also is a freelance consultant. He
completed his studies from a top notch university and to actually put his theoretical
knowledge to practice, he started staying in the remote village Khabri. He wanted to
actually experience the hardships faced by people residing in remote areas. To sustain
himself he decides to pick up a job in the only factory situated in Khabri. The HR manager
impressed with his in-depth knowledge and qualifications requests him to also plan a
strategy to improve production of their factory. Who do you think will be able to provide a
more viable solution? The obvious answer for most of us would be that the person sitting
in the remote village and literate enough to solve the problem will be able to provide a
better strategy because he closely understands the real problems of the residents as
compared to a person sitting far away. But what does this teach us about programming?
This teaches us that in programming also functions/methods/programs written for
specific situations are able to manipulate data of their respective entities more
efficiently. Now, let us understand a little about the various programming paradigms.
Introduction to Programming
Computer programming is a process of designing, writing, testing, debugging and
maintaining the source code of computer programs written in a particular programming
language. The purpose of programming is to organize instructions that are capable of
solving real life problems. The process of writing source code of programs requires
expertise in subject, knowledge of desired application domain, a formal logic and
knowledge of syntax of the relevant programming language. Writing instructions in the
desired order gives the required results from the program but when these instructions
104
BASICS OF OBJECT ORIENTED PROGRAMMING
1. Class
2. Object
105
BASICS OF OBJECT ORIENTED PROGRAMMING
Class and objects are related to each other in the same way as data type and variables.
For example, when we declare float variable named marks, the variable marks can be
thought of as an object of type float which can be assumed as the class. If we take another
hypothetical case in which Human is a class, Mr. Arun Shah, Mr. Aneek Ram will be the
objects of this Human class.
In real java programming, this data will be required to conform to a specific data type as
in char, int, float or double whereas the methods will be a sequence of steps written
together to perform a specific task on the data. Carefully observe the illustration given in
Figure 4.1 to reinstate the theoretical concepts learnt above.
106
BASICS OF OBJECT ORIENTED PROGRAMMING
Class Employee
Data Members
• EmpNo
• Name
• Salary
Method
• AddNewEmployee()
• DisplayEmployee()
• CalculateSalary()
Figure 4.1 Illustration Showing the Class, Object, Members and Methods
Referring to the situation presented in the introduction of the chapter, just like the
person residing in the village can efficiently solve problems pertaining to his village,
similarly the methods of specific classes are able to manipulate data of their respective
classes efficiently resulting in better security of data in an Object Oriented Programming
paradigm.
Now that you are clear about the concept of a class and an object, you will be able to
appreciate and identify classes and methods that we have already been using throughout
our class XI. Do you know JTextField, JLabel, JTextArea, JButton, JCheckBox and
JRadioButton are all classes and the jTextField1, jLabel1, jTextArea1, jButton1,
jCheckBox1 and jRadioButton1 components are all objects. The setText(), setEnabled(),
pow(), substring() are all methods of different classes. This concept is illustrated in
Figure 4.2.
107
BASICS OF OBJECT ORIENTED PROGRAMMING
Class
JTextField
Data Members
• Text
• Editable
• Enabled
• toolTipText
Object 1 Object 2
Method
jTextField1 jTextField2
• setText()
• "Amit Khanna" • getText() • "Indian"
• true • setEditable() • false
• false • setEnabled() • false
• "Enter Name" • setToolTipText() • "Citizenship"
Class
JLabel
Data Members
• Text
• Editable
• toolTipText
Object 1 Object 2
Method
jLabel1 jLabel2
• setText()
• "Age" • getText() • "Gender"
• (21-62 Years) • setToolTipText() • (Male/Female)
• True • setEnabled() • True
Notice that the properties like Text, Enabled, Editable are actually the data
members in the class because they store specific values as data. For example
the property Text of jTextField1object contains the actual text to be
displayed in the text field.
108
BASICS OF OBJECT ORIENTED PROGRAMMING
The following two tables summarize the data members (properties) and methods of all
classes learnt during the course till now:
109
BASICS OF OBJECT ORIENTED PROGRAMMING
• Font • setText()
• Foreground • isSelected()
• Label • setSelected()
• Selected
• Text
• Enabled • isSelected()
• Font • setSelected()
• Foreground
• Label
• Selected
• Text
• Font • setText()
• Foreground • getText()
• Text • isEnabled()
• Columns
• toolTipText
• ButtonGroup • getSelectedIndex()
• Editable • setModel()
• Enabled
110
BASICS OF OBJECT ORIENTED PROGRAMMING
• Font
• Foreground
• Model
• SelectedIndex
• SelectedItem
• Text
JList jList1 • Background • getSelectedValue()
• Enabled
• Font
• Foreground
• Model
• SelectedIndex
• SelectedItem
• SelectionMode
• Text
JTable jTable1 • model • addRow()
• getModel()
Polymorphism :
111
BASICS OF OBJECT ORIENTED PROGRAMMING
If the argument passed to the round() method is of type double then it rounds off the
double value and returns the closest long value. On the other hand, if the argument
passed to the round() method is of type float then it rounds off the float value and returns
the closest integer value. This simply means that the round() method is overloaded on the
basis of the type of arguments supplied to it. Figure 4.3 illustrates the concept of method
overloading as demonstrated by the round()method. For example:
float f = 12.5;
double d = 123.6543;
Notice that if the argument is of type double and we try to round it to an integer,
then it results in an error because no such method is pre-defined which takes a
double argument and rounds it to integer type.
If a single argument is passed to the substring() method then it returns all characters from
the start position to the end of the string whereas if two arguments are passed to the
substring() method then it returns a substring of the characters between the two
specified positions of the string. This simply means that the substring() method is
overloaded on the basis of the number of arguments supplied to it. For example:
String Message = "Good Morning", Message1, Message2;
112
BASICS OF OBJECT ORIENTED PROGRAMMING
Abstract Class :
The classes for which objects are required to be
Abstract Class
declared are known as concrete classes like JLabel,
JOptionPane
JTextField, JComboBox etc. The classes for which it is
not essential to declare objects to use them are known Methods
• showMessageDialog()
as abstract classes like JOptionPane. Abstract classes
• showingputDialog()
are normally used as base class in inheritance for
• showConfirmDialog()
which no direct object is required to be created. Also
abstract classes are used for defining generic methods Figure 4.4
where there is no requirement of storing results. Example of an Abstract Class
Notice that the JOptionPane Class which is an abstract class has no data members
and so it will not be able to store any values. The reason behind this is that
because we cannot create objects of an abstract class, so we will not be able to
provide any data to this class. Therefore, there is no point of having a data
member.
Inheritance :
Inheritance is the most powerful feature of Object Oriented Programming, after classes
themselves. Inheritance is a process of creating new class (derived class or sub class or
child class) from existing class (base class or super class or parent class). The derived
classes not only inherit capabilities of the base class but also can add new features of
113
BASICS OF OBJECT ORIENTED PROGRAMMING
their own. The process of Inheritance does not affect the base class. Observe the base
and the derived class shown in Figure 4.5 carefully. Notice that the derived class inherits
the data members namely Colour and Height from the base class and has a new data
member defined in itself namely the Type. Similarly the derived class inherits the
methods namely getColour() and getHeight() from the base class and has a new method
defined in itself namely the setType().
Car
Derived Class
(Sub Class) (Inherits all data members of class Vehicle)
Type
(Inherits all methods of class Vehicle)
setType
The most important aspect of inheritance is that it allows reusability of code, and also a
debugged class can be adapted to work in different situations. Reusability of code saves
money as well as time and increases program reliability. Inheritance is very useful in
original conceptualization and design of a programming problem. The idea of inheritance
helps you to include features of already existing class (debugged) in a new class.
Properties (data members) and methods included in super class can be invoked/accessed
from the subclass. A subclass inherits all the members (data members and methods) from
its superclass.
PERSON VEHICLE
EMPLOYEE CAR
114
BASICS OF OBJECT ORIENTED PROGRAMMING
The new class can, in turn, can serve as the basis for another class definition. It is
important to know that all Java objects use inheritance and every Java object can trace
back up the inheritance tree to the generic class Object.
If you look at the pre-fabricated code (code automatically added by the compiler) in any
of your application (JFrame Form) created in NetBeans, you will observe that
javax.swing.JFrame acts as a base class (super class) and the name given by you for the
JFrame Form acts as the name for the derived class (sub class). Each new JFrame Form
added to the application inherits all the features of the javax.swing.JFrame class. The
screen shot from one such application is shown below to illustrate the same. Here,
javax.swing.JFrame is the base class and Example is the derived class.
Notice that the extends keyword is used to inherit data members and methods of
the JFrame base class for the Example class which is the derived class.
115
BASICS OF OBJECT ORIENTED PROGRAMMING
Summary
• Class, object, data members and methods are the major components of an
Object Oriented Programming paradigm.
• A class is used to encapsulate data and methods together in a single unit and an
object is an instance of a class.
• The round() method of the Math class and the substring() method of the String
class are good examples of method overloading.
• The classes for which it is not essential to declare objects to use them are
known as abstract classes. JOptionPane is one of the examples of an abstract
class.
• The extends keyword is used to inherit data members and methods of the base
class and allows the derived class to use these methods.
116
BASICS OF OBJECT ORIENTED PROGRAMMING
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. Which of the following is not a feature of Object Oriented Programming?
a. Inheritance b. Data Overloading
c. Polymorphism d. Objects
2. Identify which of the following are not valid examples of method overloading?
a. round() b. subString()
c. subStr() d. getText()
3. Which of the following statements about the Java language is true?
a. Both procedural and OOP are supported in Java
b. Java supports only procedural approach
c. Java supports only OOP approach
d. None of the above
4. Which of the following is an Abstract class?
a. JTextArea b. String
c. Math d. JFrame
5. Which of the following statements is false about objects?
a. Object is an instance of a class
b. Object is capable of storing data
c. Each object has its own copy of methods
d. None of the above
6. A class can have many methods with the same name as long as the number of
parameters or type of parameters is different. This OOP concept is known as
a. Method Overriding b. Method Overloading
c. Method Invocating d. Method Labelling
117
BASICS OF OBJECT ORIENTED PROGRAMMING
String C = A + B;
C = B.substring(1);
B = A.substring(3);
3. Write a short note on Operator overloading and Method Overloading citing examples
for both.
4. Carefully study the code given below. It is giving an error whenever it is compiled:
float f = 12.5;
double d = 123.6543;
118
BASICS OF OBJECT ORIENTED PROGRAMMING
Msg1 = Message.substring(7);
Msg2 = Message.substring(0,5);
What will be the contents of the variables Msg1 and Msg2 after the above statements
are executed?
6. Study the following code and answer the questions that follow:
String SMS=jTextArea1.getText();
int L=SMS.length(),Balance;
Balance=160-L;
jTextField2.setText(Integer.toString(L));
jTextField3.setText(Integer.toString(Balance));
a. Name any one native class of Java used in the above code.
d. Name the method used to convert one type of data to another and also mention
the data type before and after conversion.
7. Study the following code and answer the questions that follow:
public class Example extends javax.swing.JFrame
{
/** Creates new form named Example */
119
BASICS OF OBJECT ORIENTED PROGRAMMING
public Example()
{
initComponents();
}
}
8. Compare and contrast the Procedural Programming paradigm and the Object
Oriented Programming paradigm by writing a simple program of a mathematical
calculator using both approaches. (Note: The teacher may illustrate the Procedural
Programming Paradigm using any other simple programming language but should
not test the students on it).
LAB EXERCISES†
1. Create a GUI application to accept a string and display it in reverse order using the
substring() method.
2. Create a GUI application to create random whole numbers between 2 float numbers
input by the user.
3. Create a GUI application to accept 3 numbers in separate text fields and display
their sum, average, maximum or minimum after rounding the results on the click of
appropriate buttons (There are four separate buttons - one for sum, one for
average, one for maximum and one for minimum). The result should be displayed in
the fourth text field.
4. Create a GUI application to accept the date (as 1), month (as a number like 3 for
March) and year (as 2010) in separate text fields and display the date in the format:
dd/mm/yy. Take care of the following points while creating the application:
† The students should be encouraged to design appropriate forms for the applications themselves.
120
BASICS OF OBJECT ORIENTED PROGRAMMING
• Verify the date input before displaying it in the suggested format and display
error messages wherever applicable
• The date is accepted as 1 (for the first of any month) but should be displayed as
01 in the final format.
2. Divide the class into three groups and tell each group to create presentations on one
of the following topics (The topics may be allocated using a draw system):
a) Programming Paradigms
121
A PTE
H
ADVANCED
5
R
C
PROGRAMMING CONCEPTS
Learning Objectives
• Understand the need and use of methods pow() and round() of Math class
• Develop small applications involving the methods learnt of Math and String
classes.
In the last lesson, we introduced the concept of Object Oriented Programming and
learnt about the different elements of an Object Oriented Programming
Language. Now we will move on to learn about two important classes we
commonly use in Java - namely Math and String. The lesson focuses on how to use
some of the popular methods of these classes appropriately and appreciate how
they simplify many programming tasks for us.
Puzzle 5
Find a 9-digit number, which you will gradually round off starting with the number placed
at units, then tens, hundreds etc., until you get to the last numeral, which you do not
round off. The rounding alternates (down, up, down ...) which means that the first
number from the right is rounded down while the second number from the right is
rounded up and so on. After rounding off 8 times, the final number is 500000000. The
original number is commensurable by 6 and 7, all the numbers from 1 to 9 are used, and
after rounding four times the sum of the not rounded numerals equals 24.
122
ADVANCED PROGRAMMING CONCEPTS
Math Class
The Math class contains built-in methods for performing basic numeric operations such as
the elementary exponential, rounding of a number, square root, and trigonometric
functions. These functions can be used directly by the user in the program. These
methods are highly reliable and can tremendously reduce the amount of coding required
for an application.
Some of the most commonly used Math class methods are as follows:
Method Description
pow(double a, double b) Returns the value of the first argument raised to the
second argument.
It is not necessary to import any package for the Math class because this is already in the
java.lang package. Therefore in-built methods of the Math class can be used directly in
the application just like the other methods, as we have learnt in the previous class. Let us
learn the usage of these methods by building some simple applications. First let us create
an application that calculates the power of a number. Observe the following form
carefully.
123
ADVANCED PROGRAMMING CONCEPTS
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
124
ADVANCED PROGRAMMING CONCEPTS
double Number,Raise,Result;
Number=Double.parseDouble(jTextField1.getText());
Raise=Double.parseDouble(jTextField2.getText());
Result=Math.pow(Number, Raise);
jTextField3.setText(Double.toString(Result));
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
• Declare three variables named Number, Raise and Result of type double.
Number=Double.parseDouble(jTextField1.getText()); and
Raise=Double.parseDouble(jTextField2.getText());
• Retrieve the values input by the user from the text fields using the method
getText() and store these values in the variables Number and Raise
respectively.
125
ADVANCED PROGRAMMING CONCEPTS
Result=Math.pow(Number, Raise);
• Calculate the number (value stored in variable Number) raised to the value
stored in the variable Raise using the pow() method and store the final value in
the variable Result.
jTextField3.setText(Double.toString(Result));
• Display the final result in the third text field using the setText() method after
converting it to string type using the toString() method.
Next, let us give a quick look to the coding of the RESET button:
jTextField1.setText(""); and
jTextField2.setText(""); and
jTextField3.setText("");
• The display text of all the three buttons is set to an empty string (i.e. blank)
using the setText() method.
Next let us learn the usage of another method of the Math class namely round(). Observe
the following form carefully.
Let us first design the form as shown in Figure 5.3. First add a new JFrame form and set its
title property to "Number Rounding Off". Now, add the following components on the form:
126
ADVANCED PROGRAMMING CONCEPTS
• Four radio buttons -to give a choice to the user for rounding off the number
upto 0, 1, 2 or 3 digits
• Three labels - one against each of the text field and one against the radio
button group to appropriately direct the user.
Change the properties of the components so that the form looks exactly like the one
displayed in Figure 5.3. The next step is to associate code with the radio buttons. Double
click on the buttons one by one in the design window to reach the point in the source
window where the code needs to be written. Add the code for each of the buttons as given
in Figure 5.5. A sample run of the application is shown in Figure 5.4.
private void
jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt)
double Number,RoundedNumber;
Number=Double.parseDouble(jTextField1.getText());
RoundedNumber=Math.round(Number);
jTextField2.setText(Double.toString(RoundedNumber));
127
ADVANCED PROGRAMMING CONCEPTS
private void
jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt)
{ //to round off the number to 1 digit
double Number,RoundedNumber;
Number=Double.parseDouble(jTextField1.getText());
//You need to divide by a real number and so 10.0 and
not 10
RoundedNumber=Math.round(Number*10)/10.0;
jTextField2.setText(Double.toString(RoundedNumber));
}
private void
jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt)
{ //to round off the number to 2 digits
double Number,RoundedNumber;
Number=Double.parseDouble(jTextField1.getText());
RoundedNumber=Math.round(Number*100)/100.0;
jTextField2.setText(Double.toString(RoundedNumber));
}
private void
jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt)
{ //to round off the number to 3 digits
double Number,RoundedNumber;
Number=Double.parseDouble(jTextField1.getText());
RoundedNumber=Math.round(Number*1000)/1000.0;
jTextField2.setText(Double.toString(RoundedNumber));
}
128
ADVANCED PROGRAMMING CONCEPTS
• Retrieve the value input by the user in the first text field using the getText()
method and store it in the variable Number after converting it to type double
(using the parseDouble() method)
RoundedNumber=Math.round(Number*10)/10.0;
• Calculate the rounded number using the round method and store it in the
variable RoundedNumber. Since the round method does not allow the user to
specify the precision digits, so we first multiply the number by 10 (for rounding
off to 1 digit and similarly multiply by 100 for rounding off to 2 digits and so on)
and then divide the result by 10 to get the closest double number.
jTextField2.setText(Double.toString(RoundedNumber));
• Display the calculated result in the second text field using the setText()
method after converting it to type String using the toString() method.
Next let us learn a few methods of another important class, namely String class, of Java.
String Class :
The String class includes methods for examining individual characters of a string
sequence, for converting strings to uppercase or lowercase, for extracting substrings, for
joining two strings together, for calculating the length of a string and also for creating a
new string by omitting the leading and trailing whitespaces.
When using most of the String class's methods, it should be kept in mind that a string is
just a series of individual characters and that each character has a position or index, a
little like a queue. Remember that in strings the first position, or index, is labelled 0 and
not 1. So, if we create a string "HAPPY" then the characters will be stored as shown below:
129
ADVANCED PROGRAMMING CONCEPTS
Character Index 0 1 2 3 4
Character stored H A P P Y
Method Description
concat(String str) Concatenates the specified string to the end of this
string.
length() Returns the length of the string.
substring (int beginpos Returns a substring of the characters between the two
[, int endpos]) specified positions of the string. The second parameter
is optional; if not included then all characters from the
start position to the end of the string are included. The
character at the ending position (n2) is not included.
toLowerCase() Returns the string converted to lower case.
toString() Returns the object as a string.
toUpperCase() Returns the string converted to upper case.
trim() Returns the string, after removing the leading and the
trailing whitespaces
The most important methods are case conversion methods toUpperCase() and
toLowerCase(), so let us first develop a "Case Changer" application. Observe the following
form carefully:
130
ADVANCED PROGRAMMING CONCEPTS
Let us first design the form as shown in Figure 5.6. First add a new JFrame form and set its
title property to "Case Changer". Now, add the following components on the form:
• One editable text field to accept the string to be converted to uppercase and
lowercase
• Two non-editable text fields - one to display the string converted to uppercase
and the other to display the string converted to lowercase
• Two buttons - one to convert & display the converted strings and one to reset
the form components
• Three appropriate labels - one against each of the text field to direct the user.
Change the properties of the components so that the form looks exactly like the one
displayed in Figure 5.6. The next step is to associate code with both the buttons. Double
click on the buttons one by one in the design window to reach the point in the source
window where the code needs to be written. Add the code for each of the buttons as
given in Figure 5.7.
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
String Str=jTextField1.getText();
jTextField2.setText(Str.toLowerCase());
jTextField3.setText(Str.toUpperCase());
131
ADVANCED PROGRAMMING CONCEPTS
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
• Declare a variable named Str of type String and initialize it with the value input
by the user in the first text field. The value entered in the text field is retrieved
using method getText().
jTextField2.setText(Str.toLowerCase());
• Convert the string named Str to lower case using the toLowerCase() method
and then display the converted string in the second text field using the
setText() method.
jTextField3.setText(Str.toUpperCase());
• Convert the string named Str to upper case using the toUpperCase() method
and then display the converted string in the third text field using the setText()
method.
The coding of the RESET button is exactly the same as learnt in the earlier examples.
Now that we know how to use the methods of the String class, let us next learn two more
new methods - one to extract specified number of characters from a string and next to
join two strings together. To learn these two methods, let us design an application called
132
ADVANCED PROGRAMMING CONCEPTS
Short Name. The aim of the application is to accept the First Name, Middle Name and the
Last Name from the user and display his short name (i.e Last Name followed by his
initials). Observe the following form carefully.
Let us first design the form as shown in Figure 5.8. First add a new JFrame form and set its
title property to "Short Name". Now, add the following components on the form:
• Three editable text fields to accept the first, middle and last name from the
user
• Two buttons - one to convert & display the short name and one to reset the form
components
• Four labels - one against each of the text field to appropriately direct the user.
Change the properties of the components so that the form looks exactly like the one
displayed in Figure 5.8. The next step is to associate code with both the buttons. Double
click on the buttons one by one in the design window to reach the point in the source
window where the code needs to be written. Add the code for each of the buttons as given
in Figure 5.9.
133
ADVANCED PROGRAMMING CONCEPTS
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
// To convert a full name to a short name
String FirstName,MiddleName,LastName,ShortName="";
FirstName=jTextField1.getText().substring(0,1);
MiddleName=jTextField2.getText().substring(0,1);
LastName=jTextField3.getText();
ShortName=ShortName.concat(LastName);
ShortName=ShortName.concat(" "); // to add a blank space
ShortName=ShortName.concat(FirstName);
ShortName=ShortName.concat("."); // to add a dot to
separate FN and MN
ShortName=ShortName.concat(MiddleName);
ShortName=ShortName.concat(".");
jTextField4.setText(ShortName);
}
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
// Clear all text fields by initializing them with blank
spaces
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
}
134
ADVANCED PROGRAMMING CONCEPTS
• Declare four variables of type String and initialize them with blanks (to ensure
that it is an empty string).
FirstName=jTextField1.getText().substring(0,1); and
MiddleName=jTextField2.getText().substring(0,1);
• First retrieve the values of First Name and Middle Name entered in the first and
second text fields using the getText() method and then extract the first
character of both the First Name and Middle Name using the substring()
method and store them in the variables FirstName and MiddleName
respectively.
LastName=jTextField3.getText();
• Retrieve the value of the Last Name entered by the user in the third text field
using getText() method and store it in the variable named LastName.
ShortName=ShortName.concat(LastName); and
ShortName=ShortName.concat(" "); and
ShortName=ShortName.concat(FirstName); and
ShortName=ShortName.concat("."); and
ShortName=ShortName.concat(MiddleName); and
ShortName=ShortName.concat(".");
• The ShortName is then displayed in the fourth text field using the setText()
method.
135
ADVANCED PROGRAMMING CONCEPTS
Let us first design the form as shown in Figure 5.10. First add a new JFrame form and set
its title property to "SMS Testing". Now, add the following components on the form:
• Two non-editable text fields - one to display the number of characters entered
by the user and the other to display how many more characters can be entered
(to reach the maximum allowed length)
• Three labels - one against each of the text field to appropriately direct the
user.
Change the properties of the components so that the form looks exactly like the one
displayed in Figure 5.10. The next step is to associate code with the text field. Double
click on the text field in the design window to reach the point in the source window where
the code needs to be written. Add the code as given in Figure 5.11.
private void
jTextField1ActionPerformed(java.awt.event.ActionEvent evt)
//entered in a SMS
136
ADVANCED PROGRAMMING CONCEPTS
String SMS=jTextField1.getText();
int L=SMS.length(); // calculate the current length of
the input message
int Balance;
Balance=160-L; // calculate the remaining no. of
characters
jTextField2.setText(Integer.toString(L));
jTextField3.setText(Integer.toString(Balance));
}
• Declare a variable named SMS of type String and initialize it with the value
input by the user in the first text field. The value entered in the text field is
retrieved using method getText().
int L=SMS.length(),Balance;
• Declare two variables - Balance and L of integer type. Initialize the variable
named L with the length of the SMS entered by the user. The length is
calculated using the in-built method length() of the String class.
Balance=160-L;
• Convert the variables L and Balance to type String using the toString() method
and then display these values in the relevant text fields using the setText()
method.
137
ADVANCED PROGRAMMING CONCEPTS
The SMS sample application developed above can further be modified with the help of a
Text Area to give a better view of the SMS. Let us first design the form as shown in Figure
5.12. First add a new JFrame form and set its title property to "SMS Typist". Now, add the
following components on the form:
• Two non-editable text fields - one to display the number of characters entered
by the user and the other to display how many more characters can be entered
(to reach the maximum allowed length)
• Three labels - one against each of the two text fields and the text area to
appropriately direct the user.
• Two buttons - one to reset the form components and the second to exit from the
application
Change the properties of the components so that the form looks exactly like the one
displayed in Figure 5.12. The next step is to associate code with the Text Area and the
buttons. Double click on the text area and the two buttons, one by one, in the design
window to reach the point in the source window where the code needs to be written. Add
the code for the each of the three components as given in Figure 5.13.
138
ADVANCED PROGRAMMING CONCEPTS
private void
jTextArea1CaretUpdate(javax.swing.event.CaretEvent evt)
{
// Display the total number of characters input and
remaining for an SMS
String SMS=jTextArea1.getText();
int L=SMS.length(),Balance;
Balance=160-L;
jTextField2.setText(Integer.toString(L));
jTextField3.setText(Integer.toString(Balance));
}
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{ // Clear all text fields by initializing them with blank
spaces
jTextArea1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{ //Exit the application
System.exit(0); //The parameter 0 indicates a normal
termination
}
139
ADVANCED PROGRAMMING CONCEPTS
The code for the text area is exactly same as the one written in the previous example with
just a minor difference. In this case, the SMS is retrieved from the text area instead of the
text field. The rest of the code is exactly the same. The code for the two buttons is also
similar to all previous applications having a RESET and a STOP button.
Extra Reading
String SMS=jTextField1.getText();
int L=SMS.length(),Balance;
Balance=160-L;
jTextField2.setText(Integer.toString(L));
jTextField3.setText(Integer.toString(Balance));
Note: For writing the code for jTextField1CaretUpdate Event, we need to use
the Steps as shown in the following figure:
140
ADVANCED PROGRAMMING CONCEPTS
Figure 5.14 Steps for writing the code for jTextField1CaretUpdate Event
What will happen if the user enters more number of characters than the permissible
range or enters unnecessary blank spaces before the beginning of the string? The SMS
example can further be modified to solve the above problem. We will now develop an
application which will remove the unwanted leading and trailing blanks and also truncate
the SMS to the permissible range using the trim() and the substring() methods of the
String class. Let us first design the form as shown in Figure 5.15. First add a new JFrame
form and set its title property to "SMS Generator". Now, add the following components on
the form:
• Two editable text areas - one to accept the SMS message and the second to
display the final truncated SMS.
• Two non-editable text fields - one to display the number of characters entered
by the user and the other to display how many more characters can be entered
(to reach the maximum allowed length).
• Four labels - one against each of the two text areas and the two text fields to
appropriately direct the user.
• Two buttons - one to truncate and display the SMS in the text area and the other
to reset the form components.
141
ADVANCED PROGRAMMING CONCEPTS
Change the properties of the components so that the form looks exactly like the one
displayed in Figure 5.15. The next step is to associate code with both the buttons. Double
click on the buttons one by one in the design window to reach the point in the source
window where the code needs to be written. Add the code for each of the buttons as given
in Figure 5.16.
• Retrieve the SMS entered by the user in the first text area using the getText()
method and store it in the variable SMS.
if (SMS.length()>160)
SMS=SMS.substring(0,159);
142
ADVANCED PROGRAMMING CONCEPTS
• Check if the length of the SMS entered by the user is greater than 160 (using the
length() method), then extract only first 160 characters (using substring()
method) and store it in the variable SMS.
FinalSMS=SMS.trim();
• Remove White Spaces from both sides of the SMS input by the user and store the
resultant SMS in the variable named Final SMS.
FinalSMS="*"+FinalSMS+"*";
• Display the final sms in the second text area using the setText() method.
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
String SMS,FinalSMS;
SMS=jTextArea1.getText();
if (SMS.length()>160)
jTextArea2.setText(FinalSMS);
143
ADVANCED PROGRAMMING CONCEPTS
private void
jButton2ActionPerformed(java.awt.event.ActionEvent evt)
jTextArea1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextArea2.setText("");
private void
jTextArea1CaretUpdate(javax.swing.event.CaretEvent evt)
String SMS=jTextArea1.getText();
int L=SMS.length(),Balance;
Balance=160-L;
jTextField2.setText(Integer.toString(L));
jTextField3.setText(Integer.toString(Balance));
Figure 5.16 Steps for writing the code for jTextField1CaretUpdate Event
144
ADVANCED PROGRAMMING CONCEPTS
Summary
• Java supports native classes like Math and String with predefined methods to
make the programming process simpler.
• The pow(d1,d2) method of the Math class returns the value d1raised to d2.
• The round(d) method of the Math class returns the closest integer/float to d.
• The concat(str) method of the String class concatenates the string named str to
the string calling the method.
• The length() method of the String class returns the number of characters in the
string.
• The toLowerCase() and toUpperCase() methods of the String class return the
string converted to lower case and upper case respectively.
• The substring(n1, n2) method of the String Class returns the extracted
characters starting from the position n1 till n2.
• The trim() method of the String class returns the string after removing the
leading and the trailing blanks.
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. The ____________ method is used to extract specified number of characters from a
string.
A. subStr() B. subString()
C. takeString() D. extract()
A. pow() B. toLowerCase()
A. The trim() method is used to trim a string by removing spaces from one side
145
ADVANCED PROGRAMMING CONCEPTS
A. 5 B. 9
C. 10 D. 6
8. Which of the following is not a primitive data type in Java?
A. float B. int
C. string D. void
146
ADVANCED PROGRAMMING CONCEPTS
1. What is a class?
2. Name any four native classes of Java and briefly explain the use of each.
3. Give two appropriate advantages of using in-built methods over creating user
defined methods.
4. Explain the general syntax of using any method of the String class. Is it in anyway
different from using a method of the Math class?
5. What will be the contents of F1 and F2 after the following code is executed?
String F1="Hello",F2="Friend";
F1=F1.concat(F2);
8. Study the following code and answer the questions that follow:
double Number,RoundedNumber;
Number=Double.parseDouble(jTextField1.getText());
RoundedNumber=Math.round(Number*1000)/1000.0;
jTextField2.setText(Double.toString(RoundedNumber));
a) How many variables have been declared in the above code? Identify and name
them.
b) How many objects have been declared in the above code?
c) Name any one native class of Java used in the above code.
d) Identify and name a method of this native class.
147
ADVANCED PROGRAMMING CONCEPTS
e) Name the method used to convert one type of data to another and also mention
the data type before and after conversion.
LAB EXERCISES†
1. Create an application to accept two strings - First Name and Last name from the user
and display the message Welcome with the complete name of the user.
2. Create an application to accept the radius of a circle, calculate the area and
circumference and display the results in a message box after rounding off the area
and circumference to an integer number.
3. Modify application to make sure that the user has not input the complete name in
the first name text field.
4. Modify the Case Changer application developed in the lesson to display the input
text in Title case using the substring(), toLowerCase() and toUpperCase() methods.
a. The form should accept the name and password from the user
b. Only if the password matches with the pre-input password, the user should be
allowed to proceed. (Hint - need to check the length and the contents and also
convert the string to a particular case)
c. Hide the initial text fields and now create form elements to accept input of
first name, middle name and last name along with the age.
d. Ensure that the age input is an integer and the first name, middle name and the
last name are not more than 12 characters long.
2. Divide the students into groups of 6 and then give each group an algorithm which is
predesigned by the teacher, and tell them to execute it. This algorithm should draw
a figure with the children; the first team to find the figure and name it wins.
† The students should be encouraged to design appropriate forms for the applications themselves.
148
ADVANCED PROGRAMMING CONCEPTS
For example :
child[1].AtLeftOf(child[2])
child[0].InFrontOf(child[2])
child[2].InFrontOf(child[4])
child[3].AtRightOf(child[2])
child[4]. InFrontOf(child[5])
The algorithm given above is to form the shape of an arrow as depicted in the
following figure:
Child 0
Child 1 Child 3
Child 4
Child 5
149
A PTE
H
6
R
C
DATABASE CONNECTIVITY
Learning Objectives
In the earlier lessons, you have learnt how to develop a GUI Interface using
Netbeans and creating & manipulating data in a table of a database as two
independent concepts. This lesson will help you to combine both these concepts
together and help you to develop complete applications in which the GUI
Interface will act as Front-End or Client Side application and Database will act as
Back-End or Server-Side application.
Puzzle 6
A person wanted to withdraw X rupees and Y paise from the bank. But the cashier made a
mistake and gave him Y rupees and X paise. Neither the person nor the cashier noticed
that. After spending 20 paise, the person counts the money. And to his surprise, he has
double the amount he wanted to withdraw. Find X and Y.
(1 Rupee=100 paise)
Introduction
Imagine a swanky air-conditioned car showroom in prime location of the city with all
modern car accessories available in an outlet within the showroom. The showroom has a
150
DATABASE CONNECTIVITY
151
DATABASE CONNECTIVITY
Table: Employee
Empno Name Salary
Obviously, you do not expect the user to learn all these commands to perform these
activities. User always likes to access the information using the computer with some
clicks of mouse or by typing in little textual input as per instructions provided preferably
in his/her local language. So, there is a need to provide him/her with an interface to
access or modify the information available in the database.
152
DATABASE CONNECTIVITY
After going through the above paragraphs, you can understand that there is a
requirement of creating an interface (the form), which a user may use for accessing
information and also there is a requirement of keeping the information saved in the
database (table) in an organized manner for future references and uses. So, we need to
combine both these concepts together to develop a complete application for various
domain specific problems. Now after learning about the front end and the back end, the
next step is to learn how to set up a database connection that allows the front end to
communicate with the back end. The two components essential to establish this
connectivity are enumerated below and demonstrated in Figure 6.1:
• The JDBC API - software used to provide RDBMS access and execute SQL
statements within java code.
• The JDBC Driver for MySQL - software component enabling a java application to
interact with a MySQL database.
Database: School
Application:Form
Table: Student
Name Class
jdbc Driver Arun 12
Name
Class Ajay 11
OK Cancel
Table: Fee
Name Fee
Arun 6500
Ajay 4500
Figure 6.1 Communicating With a Database Using JDBC API and Driver
153
DATABASE CONNECTIVITY
Know more
An application programming interface (API) is an interface implemented by a
software program which enables it to interact with other software. It facilitates
interaction between different software programs similar to the way the user
interface facilitates interaction between humans and computers.
Step 1: Right click on the Project name and select the Properties option as shown in
Figure 6.2.
iii. From the Add Library dialog box choose the MySQL JDBC Driver
154
DATABASE CONNECTIVITY
iv
ii
iii
Figure 6.3 Adding the MySQL JDBC Driver From Available Libraries
Know more
The JDBC (Java Database Connectivity) API is a software for executing SQL
statements. It provides RDBMS access by allowing you to embed SQL inside Java
code. We can create a table, insert values into it, query the table, retrieve
results, and update the table with the help of JDBC.
The driver is now added to the compile time libraries and this can be verified by clicking
on the Compile Time Libraries tab in the Project Properties dialog box as shown in Figure
6.4. Click on OK to close the Project Properties dialog box.
155
DATABASE CONNECTIVITY
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
Let us quickly understand the basic purpose for each of these class libraries:
• The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager is considered the backbone of
JDBC architecture. DriverManager class manages the JDBC drivers that are
installed on the system. Its getConnection() method is used to establish a
connection to a database. It uses a username, password, and a jdbc url to
establish a connection to the database and returns a connection object.
In case any of these libraries are missing, then the execution results in an error as shown
in Figure 6.5.
156
DATABASE CONNECTIVITY
Now that we have learnt the basics about establishing a connection, let us start
developing an application that uses database connectivity. The aim of the first
application that we will develop is to add data into a table.
Using MySQL command prompt, create a Table named "Contact" in the Database CBSE,
with the specified table structure. The relevant command is shown in Figure 6.6.
Table
Structure
Name VARCHAR(20)
Command for Mobile VARCHAR(12)
creating the Table
USE CBSE;
CREATE TABLE Contact (Name VARCHAR(20),Mobile VARCHAR(12),
Email VARCHAR(25));
Figure 6.6 Command for creating the back end Table with a specified structure
Now let us design the form as shown in Figure 6.7. First add a new JFrame form and set its
title property to "Contact List". Now, add the following components on the form:
• Three editable text fields to accept the name, mobile number and email
address from the user.
• Three appropriate labels - one against each of the text field to direct the user.
157
DATABASE CONNECTIVITY
• Two buttons - one to add the data supplied by the user in the database and one
to exit from the application.
Change the properties of the components as learnt earlier so that the form looks exactly
like the one displayed in Figure 6.7. The next step is to associate code with both the
buttons. Double click on the buttons one by one in the design window to reach the point in
the source window where the code needs to be written. Add the code for each of the
buttons as given in Figure 6.8.
158
DATABASE CONNECTIVITY
{
Class.forName("java.sql.DriverManager");
Connection con = (Connection)
DriverManager.getConnection
("jdbc:mysql://localhost:3306/cbse",
"root", "abcd1234");
Statement stmt = (Statement) con.createStatement();
String query="INSERT INTO Contact VALUES
('"+Name+"','"+Mobile+"','"+Email+"');";
stmt.executeUpdate(query);
}
catch(Exception e)
//this block is executed in case of an exception
{
//Display an error message in the dialog box for an exception
159
DATABASE CONNECTIVITY
Know more
To catch an exception in Java, you write a try block with one or more catch
clauses. Each catch clause specifies one exception type that it is prepared to
handle. The try block delimits a bit of code that is under the watchful eye of the
associated catchers. If the bit of code delimited by the try block throws an
exception, the associated catch clauses will be examined by the Java virtual
machine. If the virtual machine finds a catch clause that is prepared to handle the
thrown exception, the program continues execution starting with the first
statement of that catch clause. For example, in the above code if any error occurs
while establishing a connection or executing the SQL query then the error message
will be displayed in a message box due to the catch block immediately following
the try block.
• Declare three variables named Name, Mobile and Email of type String and
initialize them with the values input by the user in the text fields. The values
are retrieved from the text fields using the getText() method.
Class.forName("java.sql.DriverManager");
• In this step of the jdbc connection process, we load the driver class by calling
Class.forName() method with the Driver class name as an argument. Once
loaded, the Driver class creates an instance of itself. A client can then connect
to the Database Server through JDBC Driver.
Connection con = (Connection)
DriverManager.getConnection
("jdbc:mysql://localhost:3306/cbse", "root", "abcd1234");
160
DATABASE CONNECTIVITY
• Instantiate a Statement object called stmt from the connection object (named
con created in the previous statement) by using the createStatement()
method. A statement object is used to send and execute SQL statements to a
database.
String query="INSERT INTO Contact VALUES
('"+Name+"','"+Mobile+"','"+Email+"');";
• Create a variable called query of type String and initialize it with the SQL
statement to be executed (in this case the INSERT INTO statement).
stmt.executeUpdate(query);
• Execute the SQL statement stored in the variable query, using the
executeUpdate() method of the Statement class. This results in adding the
values stored in the three variables (Name, Mobile & Email) in the table
Contact of the cbse database.
catch (Exception e)
161
DATABASE CONNECTIVITY
Note that the forName() method is used to load the class specified as its argument
at runtime.
Figure 6.9 Sample Run of the Contact List Application Showing Error Message
The above application can be modified to handle basic data validations as shown in Figure
6.10.
Note that Data validation is the process of ensuring that a program operates on
clean, correct and useful data. It uses routines, often called "validation rules" or
"check routines", that check for correctness, meaningfulness, and security of data
that are input to the system. For example, telephone numbers should include the
digits and possibly the characters + & -. A more sophisticated data validation
routine may check to see the user has entered a valid country code, i.e., that the
number of digits entered match the convention for the country or area specified.
162
DATABASE CONNECTIVITY
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{ String Name=jTextField1.getText();
String Mobile=jTextField2.getText();
String Email=jTextField3.getText();
if (Name.isEmpty())
else if (Mobile.isEmpty())
else if (Email.isEmpty())
else
{ try
Class.forName("java.sql.DriverManager");
DriverManager.getConnection
("jdbc:mysql://localhost:3306/cbse", "root",
"abcd1234");
163
DATABASE CONNECTIVITY
('"+Name+"','"+Mobile+"','"+Email+"');";
stmt.executeUpdate(query);
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
catch (Exception e)
Figure 6.10 Code for the Contact List Application with Data Validations
Let us now understand the purpose of the additional commands added to the above code:
if (Name.isEmpty())
else if (Mobile.isEmpty())
else if (Email.isEmpty())
else { …..}
• Check if the value of any of the three variables (Name, Mobile, Email) is empty
using the isEmpty() method with the help of the if..else conditional statement.
In case any of the values is empty then display a error message in a dialog box
using the showMessageDialog() method.
164
DATABASE CONNECTIVITY
catch (Exception e)
The code for the exit button is the same as all our previous applications.
After executing the Contact List Application, if you need to verify whether the row has
been added to the table or not, then you need not go back to the MySQL prompt.
Netbeans allows one to directly run SQL commands from the GUI interface.
Therefore, the content of the table can directly be tested by running SQL in Netbeans. To
execute an SQL command in Netbeans perform the following steps:
Step 1: In the Services tab, right click on the Databases and select the New Connection
option from the drop down menu.
Step 2: The New Database Connection dialog window opens up as shown in the Figure
6.11. Provide the values as shown in the figure and click OK. Clicking on OK in
the above dialog window adds the connection to the existing list as shown in
the Figure 6.12. Note that this step is required to be done only once - the first
time when creating a connection.
165
DATABASE CONNECTIVITY
Step 3: Right click on the newly added Connection and select the Connect option from
the drop down menu. This step is to be repeated every time you start Netbeans.
In the Connect dialog box that opens up, enter the user name and password and
select the Remember Password checkbox (Selecting this checkbox ensures that
this step is not to be repeated every time you start Netbeans) as shown in
Figure 6.12.
Newly added
connection
166
DATABASE CONNECTIVITY
After establishing the connection, right click on the connection driver and select the
Execute Command option from the drop down menu. The screen as shown in Figure 6.13 is
displayed. Now, type in any SQL to be executed on the database and execute the
command. The result is displayed in the bottom half of the window as shown in Figure
6.13.
SQL Command
Rows
retrieved from
the database
• One editable text field to accept the mobile number from the user.
• Two non-editable text fields to display the details - Name and E-mail of the
contact being searched.
167
DATABASE CONNECTIVITY
• Three appropriate labels - one against each of the text field to direct the user.
• Two buttons - one to search for the details on the basis of a mobile number
supplied by the user and one to exit from the application.
Change the properties of the components as learnt earlier so that the form looks exactly
like the one displayed in Figure 6.14. The next step is to associate code with both the
buttons. Double click on the buttons one by one in the design window to reach the point in
the source window where the code needs to be written. Add the code for each of the
buttons as given in Figure 6.15.
168
DATABASE CONNECTIVITY
{
jTextField2.setText("");
jTextField3.setText("");
JOptionPane.showMessageDialog
(this,"Enter the Mobile No");
}
// This part is executed if a Mobile No is
// input in the text field
else
{
try
{
Class.forName("java.sql.DriverManager");
Connection con = (Connection)
DriverManager.getConnection
("jdbc:mysql://localhost:3306/cbse",
"root", "abcd1234");
Statement stmt = (Statement) con.createStatement();
String query="SELECT NAME,EMAIL FROM CONTACT
WHERE MOBILE='"+Mobile+"';";
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
String Name = rs.getString("Name");
//Retrieve the name
169
DATABASE CONNECTIVITY
jTextField2.setText(Name);
jTextField3.setText(Email);
else
JOptionPane.showMessageDialog
catch (Exception e)
JOptionPane.showMessageDialog(this, e.getMessage());
System.exit(0);
170
DATABASE CONNECTIVITY
• Declare a variable called mobile and initialize it with the value input by the
user in the first text field which has been retrieved using the getText() method.
if (Mobile.isEmpty())
jTextField2.setText("");
jTextField3.setText("");
• Check if the mobile variable is empty i.e. in case the user has not input any
mobile number then reinitialize both the text fields with blank spaces using the
setText() method and show an error message using the showMessageDialog()
method.
else
try
Class.forName("java.sql.DriverManager");
DriverManager.getConnection
("jdbc:mysql://localhost:3306/cbse",root",
"abcd1234");
WHERE MOBILE='"+Mobile+"';";
171
DATABASE CONNECTIVITY
• If the user has entered a valid mobile number then perform all the steps for
setting up a connection and initializing a query as learnt in the first database
application.
ResultSet rs=stmt.executeQuery(query);
• Instantiate an object named rs of the ResultSet class and initialize it with the
records returned by executing the SQL statement stored in the query variable.
The executeQuery() method is used when we simply want to retrieve data from
a table without modifying the contents of the table.
if (rs.next())
• Check if there is a matching record in the result set using the if construct. The
next() method of the result set is used to move to the next record of the
database.
String Name = rs.getString("Name");
String Email = rs.getString("Email");
jTextField2.setText(Name);
jTextField3.setText(Email);
• Create two variables named Name and Email and initialize them with the
values retrieved from the table using the getString() method. Next display
these values retrieved from the table in the relevant text fields using the
setText() method.
else
{ JOptionPane.showMessageDialog
(this,"Sorry!No such Mobile No"); }
• If there is no matching record found in the table then display an error message
using the showMessageDialog() method.
catch (Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
172
DATABASE CONNECTIVITY
A sample run of the validation check applied in the above application is shown in Figure
6.16
Just like we need to add the DriverManager, Connection and Statement class libraries,
similarly we need to import the ResultSet class library when we are retrieving data from a
database. In case the above mentioned library is not imported then the error window is
displayed as shown in Figure 6.17.
Data Connectivity Application 3: To Display the Details Stored in the Back-end Based
on the Name Input by the User in a Form.
Observe the sample run of our next application as shown in Figure 6.18 carefully. Can you
observe the difference in this application as compared to our previous one?
173
DATABASE CONNECTIVITY
In the previous application, we are searching on mobile number which will be unique i.e.
we will always have a single matching record. What will happen if we perform a search on
Name? In this case there is a possibility that we may have more than one matching record.
So the major difference between the two applications is that in the new application we
will aim at performing a search in which multiple records may be returned.
Figure 6.18 Sample Run of the Search For Contacts (For Given Name)
The form design and most of the coding is similar with minor differences. Observe the
code given in Figure 6.19 carefully and try to point out the differences.
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
String name=jTextField1.getText();
if (name.isEmpty())
else
174
DATABASE CONNECTIVITY
try
Class.forName("java.sql.DriverManager");
DriverManager.getConnection
("dbc:mysql://localhost:3306/cbse", "root",
"abcd1234");
WHERE Name='"+name+"';";
ResultSet rs=stmt.executeQuery(query);
int Found=0;
while(rs.next())
jTextField2.setText(mobile);
jTextField3.setText(email);
JOptionPane.showMessageDialog
(null,"Click OK to continue!!!");
Found++;
175
DATABASE CONNECTIVITY
if (Found==0)
JOptionPane.showMessageDialog
catch (Exception e)
JOptionPane.showMessageDialog(this, e.getMessage());
Figure 6.19 Code for the Search for Contacts (For Given Name) Application
Let us now discuss the changes (additional commands) made to the previous code one by
one:
i) The first change is declaration of a new integer variable named Found. This
variable is initialized to 0 and is used to keep a track of how many matching
records have been found.
ii) The second change is that we have used while loop to traverse through all the
records in the table to find all possible matching records.
iii) The third change is the statement used to increment the variable found each
time a matching record is encountered.
176
DATABASE CONNECTIVITY
First, create a new table named Official with the same structure as that of table Contact.
Add few records in this table.
Now let us design the form. First add a new JFrame form and set its title property to
"Contact List". Now, add the following components on the form:
• Two radio buttons to select whether the records of the Contact table are
displayed or the records of the Official table are displayed.
• Two appropriate labels - one against each of the radio button to direct the user.
• Three buttons - one to refresh data displayed in the table, one to reset the
table and one to exit from the application.
Change the properties of the radio buttons, labels and button components as learnt
earlier so that the form looks exactly like the one displayed in Figure 6.20. Before
associating the code with the buttons, we need to customize the table component.
Right click on the table component and select Table Contents option to open the
Customizer Dialog window. In this window choose the Columns tab and customize the
column names by changing the Title property of each column as shown in Figure 6.21.
177
DATABASE CONNECTIVITY
Next choose the Rows tab and delete all the four default rows. These rows have to be
deleted otherwise they appear as blank rows in the final output and the retrieved data is
displayed from fifth row onwards.
Once the form has been totally customized, the next step is to associate code with all the
three buttons. Double click on the buttons one by one in the design window to reach the
point in the source window where the code needs to be written. Add the code for each of
the buttons as given in Figure 6.22.
Figure 6.21 Customizing Columns and Rows of the Table Component of the Form
Before proceeding to writing the code, let us understand the purpose of the two buttons -
Refresh Data and Reset Table. The purpose of the Refresh Data button is to display the
data from the selected table without clearing the previous data. This means that the new
data will be displayed in continuation of the previous displayed data. Whereas, if we
press the Reset Table button, then it deletes all previous rows of the table component of
the form.
178
DATABASE CONNECTIVITY
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
DefaultTableModel model = (DefaultTableModel)
jTable1.getModel();
try
{
Class.forName("java.sql.DriverManager");
Connection con = (Connection)
DriverManager.getConnection
("jdbc:mysql://localhost:3306/cbse",
"root", "abcd1234");
Statement stmt = (Statement) con.createStatement();
String Tname;
if (jRadioButton1.isSelected())
Tname="Contact";
else
Tname="Official";
/* The query is executed on different tables depending
upon the Purpose */
String query="SELECT * FROM "+Tname+";";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
String Name = rs.getString("Name");
179
DATABASE CONNECTIVITY
180
DATABASE CONNECTIVITY
• To retrieve the Model of the newly created table and type cast it to the Default
Model.
Class.forName("java.sql.DriverManager");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/cbse",
"root", "abcd1234");
Statement stmt = (Statement) con.createStatement();
• Declare a variable named Tname of type String. This variable will be sued to
store the name of the table from which the data has to be retrieved.
if (jRadioButton1.isSelected())
Tname="Contact";
else
Tname="Official";
• Check which radio button has been selected and accordingly initialize the
variable Tname.
String query="SELECT * FROM "+Tname+";";
• Create a variable called query of type String and initialize it with the SQL
statement to retrieve all records from the specified table. The value of the
specified table is stored in the variable Tname and so this variable is
concatenated with the normal SQL statement.
ResultSet rs = stmt.executeQuery(query);
• Execute the SQL query using the executeQuery() method. Instantiate a variable
named rs of class ResultSet to store the records returned by the SQL query.
181
DATABASE CONNECTIVITY
while(rs.next())
• Till there are records in the database, keep retrieving the values of Name,
Mobile and Email from the table one by one using the getString() method and
store them in the three String variables using the assignment operator.
• After storing the values in the variables, display these values in the table
component on the form using the addRow() method.
int rows=model.getRowCount();
• Declare a variable named rows of type integer and initialize it with the total
number of rows in the table component of the form using the getRowCount()
method.
if (rows>0)
model.removeRow(0);
• If the number of rows is greater than zero, then use a for loop to reset the table
component i.e. delete all the rows using the removeRow() method. Note that
the parameter passed to the removeRow() method is always zero as we are
always deleting the topmost row and this process is repeated rows number of
times to ensure that all the rows are deleted.
182
DATABASE CONNECTIVITY
Now that we are clear about data connectivity, let us learn a new feature - to add
multilingual support facility to our Netbeans form and database and then display records
in our native language as shown in Figure 6.23.
Figure 6.23 Form Design of the Contact List Application with a Hindi Interface
Note that the DEFAULT CHARACTER SET UTF8 has been added to the above command to
have Unicode support for entering and processing data in HINDI language. Adding this
command while creating the database ensures that all tables created within this
database support Hindi language processing.
Next create a table named Contact in the CBSEHINDI database using the following
command:
CREATE TABLE Contact (Name VARCHAR(20),Mobile VARCHAR(12),
Email VARCHAR(25));
Now while creating the form as shown above for the Netbeans application, remember to
use unicode supported fonts for jTextFields, jLabels and jButtons (such as Arial Unicode
MS) as shown in Figure 6.24.
183
DATABASE CONNECTIVITY
The code will be similar as the earlier example shown in Data Connectivity Application 1
(Only change the name of the database to cbsehindi as shown in the following code) and
DriverManager.getConnection("jdbc:mysql://localhost:3306/cbsehindi","root",
"abcd1234");
Clicking on this
button will add Clicking on this
the given button will
details in the terminate the
database application
Figure 6.25 Sample Run of the Contact List Application with Hindi Interface
All the records in the cbsehindi database are stored in Hindi. Therefore, if we execute an
SQL command to display all the records of the database then the records will be displayed
in Hindi as shown in Figure 6.26.
184
DATABASE CONNECTIVITY
Records
displayed
in Hindi
Figure 6.26 Running Simple SQL Statement in Netbeans for Data Display in Hindi
Future Trends
Cloud Computing
Summary
• A GUI (The Front-End) helps the user to design forms to accept data and provide
instructions for retrieving information from the backend.
• A database (The Back-End) helps in storing data in organized manner for future
reference and use
185
DATABASE CONNECTIVITY
• A link needs to be established between the front end form and the back end
table using jdbc driver (or an equivalent) to facilitate communication between
the two.
• The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver.
• The JDBC Connection interface defines methods for interacting with the
database via the established connection.
• The executeQuery() method is used when we simply want to retrieve data from
a table without modifying the contents of the table.
• The next() method of the result set is used to move to the next record of the
database.
186
DATABASE CONNECTIVITY
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. We may use ____________ to develop the Front-End of an application.
A. GUI B. Database
C. Table D. None of the above
2. The ______________ method is used when we simply want to retrieve data from a
table without modifying the contents of the table
A. execute() B. queryexecute()
C. query() D. executeQuery()
3. Which of the following class libraries are essentially required for setting up a
connection with the database and retrieve data?
A. DriverManager B. Connection
C. Statement D. All of the above
4. The _____________ is required to establish connectivity between the Java code and
the MySQL database.
E. JDBC API F. JDBC Driver
G. Both A and B
5. To execute SQL statements, you need to instantiate a _____________ object using
the ______________ object.
A. Connection , Statement B. Statement, Connection
C. JDBC Driver, Statement D. JDBC DriverManager, Statement
6. Which of the following statements are false?
A. The getConnection() method is used to establish a connection.
B. An application can have more than one connection with a database.
C. An application cannot have more than one connection with a database.
187
DATABASE CONNECTIVITY
A. getConnection() B. getStatement()
C. createConnection() D. createStatement()
8. The ____________ method is used to move to the next row of the result set.
A. next() B. findNext()
C. last() D. forward()
188
DATABASE CONNECTIVITY
LAB EXERCISES†
1. Modify the SMS application developed in Chapter 5 to store the messages in a table
along with the number of characters in a message.
2. Modify the password application developed in Chapter 5 to store the name and
password of users in a table. The application should also update the password
whenever the user modifies his password and should keep a count on how many
times the password is being updated.
3. Design a GUI Interface for executing SQL queries for the above developed Password
Application to accomplishing the following tasks:
B. Retrieve a list of names where name begins with a specific character input by
the user and display it in a table form.
189
DATABASE CONNECTIVITY
2. Each group should next write SQL queries (to be executed on the above created
table) for the following(and design appropriate interface element):
B. Retrieve a list of users whose name begins with a specific character input by
the user and display it one at a time in a form.
C. Search and display records of the users whose birthday is in a particular month
where month is input by the user.
190
A PTE
H
7
R
C
WEB APPLICATIONS
Learning Objectives
The World Wide Web (or simply the Web or WWW) is a system of sharing
interlinked hypertext documents over the internet. These documents are stored
on web-servers on the internet and contain text, images, videos and other
multimedia. These documents also contain hyperlinks to navigate among them.
HTML (Hyper Text Markup Language) is the basic language which is used to create
Hypertext documents. In this lesson we are going to learn how to create hyper
text documents using HTML.
Puzzle 7
You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained
in one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar has the
contaminated pills in just one measurement?
Well as we can infer from the puzzle given above that assimilation of information and
then using the information to solve a problem are of utmost importance. Similarly,
information retrieval from the World Wide Web is also of prime importance and this
information retrieval is based on protocols.
191
WEB APPLICATIONS
Introduction
Internet is such a wonder box that whenever we need some information on any topic, we
refer to internet. Information is available on almost all the topics - from Ayurveda to
Advaced Medical Surgeries, from basic colors to advanced designs, from fundamentals of
computers to latest developments in the field of supercomputers - you name it and
internet has it. This information is actually stored on some computers on the net. These
computers are called the servers. The information is stored in the form of some
documents called hyper text documents. All the related documents on a server are linked
together using hyperlinks. Therefore using hyperlinks we can move from one document to
another. This is formally called navigation. There are a number of ways to create hyper
text documents. There are many specialized software packages like Dreamweaver,
CoffeCup etc. which are used to create web documents. The simplest way to create a
web document is to use a text editor like notepad, notepad2 etc. and write code in HTML.
A hyper text document on the web is also called a web page.
The information over the web is shared using a protocol called Hyper Text Transfer
Protocol (HTTP)
192
WEB APPLICATIONS
For example:
http://www.openoffice.org/dev_docs/features/3.2/rc2.html
When the URL of a web page is given to the web browser, the browser sends a request for
this page to the relevant web server. The web server, upon getting this request, sends the
requested web-page to the browser and then the browser displays this page. A web
browser knows how to display web pages.
193
WEB APPLICATIONS
Know More!
Semantic Web
The concept of Semantic Web occurred to Tim Berners-Lee, inventor of the WWW. The
Semantic Web provides a common format that allows data to be shared and reused
from diverse sources. Semantic Web is an effort to make reuse and republishing of
data easier. Semantic web is based on concept based navigation of the web as opposed
to fixed term navigation undertaken earlier.
Semantic Web provides technologies that can merge information from two sources.
The component that helps in this is the Resource Description Framework (RDF). When
information from two sources in RDF needs to be merged, we can concatenate the
files into one big file - joining on those terms which are defined to correspond to the
indicators in both the files.
More information on this is available on http://www.w3.org/RDF
Let us now start on our web page designing journey. We will use the tools that are already
available on our system.
1 2 3
194
WEB APPLICATIONS
195
WEB APPLICATIONS
Chrome in this example) using the HTML document given in Figure 7.3. Simply put,
Figure 7.2 shows a web page defined by the HTML document shown in Figure 7.3. To
define web pages HTML provides various markup elements. Using these elements we can
specify various parts of a web page and also formatting of the contents of the web page.
For example, some of the HTML elements used in Figure 7.3 are <HTML> . . . </HTML>,
<P> . . . </P>, <BR> etc. HTML elements are used to specify headings, paragraphs, lists,
tables, images and much more. When an HTML document is opened in a web browser, the
browser interprets these elements and displays the HTML document as a web-page. Here
we should understand the difference and relationship between an HTML document and a
web page. An HTML document is a text file that contains HTML elements. An HTML
document shown by a web browser is called a web page.
HTML is a subset of Standard Generalized Markup Language (SGML) and is specified by the
World Wide Web Consortium (W3C).
Any HTML document, in general, contains at least three elements - HTML, HEAD, and
BODY. These elements are specified by the following respective tags:
1. <HTML> . . .</HTML>
2. <HEAD> . . .</HEAD>
3. <BODY> . . .</BODY>
<HTML>
196
WEB APPLICATIONS
Each document consists of head and body text. The head contains the title and the body
contains the actual text that is made up of paragraphs, lists, and other elements. Let us
first learn to implement these examples on the system. We can do this easily by following
the steps given below:
• Type the code in any text editor, e.g. gedit, Notepad2, Notepad etc.
(b) formatting information that tells the web-browser about lay-out of this
information when it is displyed.
In an HTML document, the formatting information is given in the form of HTML elements.
An HTML element is specified by the corresponding tags. For example BODY element is
specified by the pair of tags <BODY> and </BODY>, B (Bold) element is specified by the
pair of tags <B> and </B>. A tag may also contain attribute(s). An attribute defines a
property of an element and is specified in the format attribute = "value" in the start tag
of the element.
An example: BODY element is specified by the pair of tags <BODY> and </BODY>. Here
<BODY> is the start tag and </BODY> is the end tag. By default, the background colour of
a web page is white, but we can change it to yellow (or to any other colour) by specifying
the BGCOLOR attribute in the <BODY> tag as <BODY BGCOLOR = "YELLOW">. The
complete thing starting from the <BODY> (with or without attributes) tag till the
</BODY> tag including the contents between these two tags is the BODY element.
HTML elements are of two types- Container elements and Empty elements. These are
discussed below.
197
WEB APPLICATIONS
Container Elements :
A container element is specified by a pair of tags - Start tag and End tag. These tags also
called ON tags and OFF tags. Start tag consists of the tag name enclosed in left and right
angular brackets. The end tag is identical to the start tag, except for a slash (/) that
precedes the text within angular brackets of the end tag. e.g.,
<BODY> . . . </Body>
Container elements contain parameters and the parameters of an element are given
between the start tag and end tags.
<BODY> . . . </BODY>
$
Parameters
Elements in HTML may also contain attributes that can be given along with the tag name
in the angular brackets of the start tag. E.g.,
<BODY BGCOLOR="BLUE" TEXT="RED">
Attributes
Empty Elements
Empty elements have only a start tag and no end tag. Hence, an empty element has no
parameters, but can take attributes, which are given within angular brackets of the start
tag.
HTML is not case sensitive, i.e., tags and attributes can be written in small or capital
alphabets. They can also be written using a mix of capital and small alphabets.
HTML element
It is a container element started by <HTML> tag and ended by </HTML> tag. It identifies
the document as an HTML document. It does not have any effect on the appearance of the
document, but tells the browser that the current document is an HTML document.
198
WEB APPLICATIONS
HTML element further contains HEAD and the BODY elements, which can further contain a
number of other elements.
HEAD element - It is a container element started by <HEAD> tag and ended by </HEAD>
tag. It defines the HTML document header and does not affect the appearance of the
document in the browser window. The header contains information about the document.
Syntax: <HEAD> . . .</HEAD>
TITLE element - It is a container element started by <TITLE> tag and ended by </TITLE>
tag. Every HTML document should contain the title to be displayed in the title bar of the
browser window. If an HTML document does not contain a title, then the file name of the
HTML document is displayed in the title bar. We can see in Figure 7.3 System Security is
written in the TITLE element and thus it is displayed in the browser's title window as
observed in figure 7.2. The TITLE element is placed in HEAD element.
BODY element - It is a container element started by <BODY> tag and ended by </BODY>
tag. It contains the main contents of the document as parameter.
199
WEB APPLICATIONS
BODY tag contains many attributes. Some of the important attributes are discussed
below.
1. Attribute: Background
Use: It is used to specify the path and filename of an image that has
to be used as the background of the document. If the
referenced image is smaller than the browser window, it will
be tiled to fit and will scroll with the text on the page. The
filename extension has to be specified along with the
filename.
2. Attribute: BGCOLOR
Use: It sets the background colour of the web page. Most of the
browsers recognize the popular colour names like RED, GREEN,
YELLOW, GREY, AQUA ETC. If we want to specify a colour which
does not have a specific name but we know its RRGGBB
composition, then we can specify this RRGGBB composition in
the BGCOLOR attribute to get the background color. E.g., in
Figure 7.3, instead of writing BGCOLOR = "GREY", we could
have written BGCOLOR = "#999999" and would have got the
same effect. If a background image is also present, the
BGCOLOR specified shines through regions where the
background image is transparent.
3. Attribute: Text
Use: It sets the colour of the normal text in the document. Colour
values can be given in the same way as that of the BGCOLOR
attribute. The default is black (hexadecimal code #000000).
200
WEB APPLICATIONS
4. Attribute: Link
Use: This sets the colour of all of the non-visited links on the page.
We can set this to any color of our choice. The default setting
for a non-visited link is usually blue.
5. Attribute: Alink
Use: This sets the colour of active links on the page. An active link is
a link that has just been keypressed by the user. Here
'keypressed' does not mean 'clicked'. 'Keypressed' means that
the mouse has been taken over the link and the left mouse
button is pressed but not released. 'Clicked' means the button
has been pressed and then released so that the browser opens
the corresponding link. We can set active link colour to any
colour. The default Alink colour is red.
6. Attribute: Vlink
Use: This changes the colour of a visited link on the page. We can set
this to any color. The default setting for a visited link is usually
violet.
NOTE:
1. The BACKGROUND attribute when used, overrides the BGCOLOR attribute. Thus if an
HTML document contains both of these tags, then the specified image will be
displayed in the background of the page and the background color will be ignored. If
however, the image is not found, the specified background colour will be used as
background.
201
WEB APPLICATIONS
2. The World Wide Web Consortium (W3C) has listed 16 valid color names for HTML:
aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red,
silver, teal, white, and yellow. Majority of browsers understand the names of many
other colors also. Any color is composed of 3 basic colors: RED, GREEN, BLUE. If a
color does not have a specific name (or if we don't know its name), its RGB (Red,
Green, Blue) composition may be specified. This composition is specified in
hexadecimal notation in the format "#rrggbb". The value of each of the composition
colors is specified as a hexadecimal number and may vary from 00 to FF. For
example, the color code "#00FF00" specifies pure green color and "#969696"
specifies a color which contains a mix equal parts of Red, Green, and Blue. Just try
and find out which color it displays.
3. Following this, whenever we say "colorname" in this chapter, it shall mean color
name as well as "rrggbb" composition of the color.
Tells the web browser to display the web page in Hindi (Devnagari script).
Instead of "hi" we can use "ks", "kok", "ne", "mr", "sa" for Kashmiri, Konkani, Nepali,
Marathi and Sanskrit respectively. If we want to use multiple languages on the same page,
we can write this attribute with the <p> tag also.
<p lang="hi">
The steps to install and use Hindi font are given in the appendix at the end of this book.
202
WEB APPLICATIONS
Know More!
You can get more information about UTF-8 and Unicode from the net. There you
can also find the information about how to use regional languages in the HTML
documents.
P (Paragraph) element - It is a container element started by <P> tag and ended by </P>
tag. This element is used to start a new paragraph. HTML does not recognize the
return/enter key we enter in text editor; therefore we use <P> tag to start a new
paragraph. <P> starts a new paragraph with extra space before the first line.
The end tag </P> of Paragraph element is optional and may be skipped. But it is highly
recommended to put this end tag. Skipping it may produce unexpected results or errors in
some browsers. Future versions of HTML will not allow you to skip end tags.
ALIGN attribute specifies the horizontal alignment of paragraph. Any of the alignments -
Center, Left, Right - can be specified.
Horizontal Rule (HR) element - This is an empty element specified by <HR> tag. The
<HR> tag draws a horizontal line across the document frame or window. We can use a
horizontal line to visually divide the information into sections.
Syntax:
<HR ALIGN = "alignment" NOSHADE SIZE = "thickness"
203
WEB APPLICATIONS
1. Attribute: ALIGN
Use: Specifies how the horizontal rule should be aligned. The
alignment can be left, right, or center. Default is center
alignment.
Syntax: ALIGN = "Alignment"
2. Attribute: NOSHADE
Use: produces a solid horizontal rule that has no shading.
Syntax: NOSHADE
3. Attribute: Size
Use: Size defines the thickness of the horizontal rule. This thickness
is specified in the number of pixels. Default is 2 pixels.
Syntax: SIZE = "n" - where n is a natural number
4. Attribute: Width
Use: "Width" defines the horizontal width of the line. The default is
the width of the page. The measurement value can be the
number of pixels, e.g., "50" , or a percentage of the page
width, e.g., "75%". Here 75% means that the horizontal rule will
cover 75% of the page width.
Syntax: WIDTH = "n/n%" - where n is a natural number
5. Attribute: Color
Use: Sets the colour of the horizontal line.
Syntax: COLOR= "colorname"
Line Break (BR) Element - This is an empty element specified by <BR> tag. <BR> tag
forces a line break which implies that the text/image following the tag will be moved to
the next line when displayed in the browser.
204
WEB APPLICATIONS
Syntax: <BR>
Well, now that we have designed our first html page we are familiar with the basic tags.
The tags learnt so far will help us in designing very basic web pages, but if we want our
web page to have different fonts, font sizes and headings we will have to delve further
and learn the usage of formatting elements. Look at the web page shown below in which
we have used formatting elements.
1 2
4
3
205
WEB APPLICATIONS
The text placed between <! and > or <COMMENT> and </COMMENT> is ignored by
the browser. This text is called a comment.
Let us now understand the use of each of the elements that have been used to write this
code.
206
WEB APPLICATIONS
Formatting Elements
Text Headings <Hn> Element - This is a container element specified by <Hn> tag, where
n is a natural number from 1 to 6. This element is used to give section headings. H1 gives
the most prominent heading, while H6 gives the least prominent heading. Heading
element introduces a blank line above and below the header text.
Syntax: <Hn>. . .<Hn>, where n is an integer in the range 1 to 6
BoldFace <B> element - This is a container element started by <B> and ended by </B>
tags. This element is used to display the text enclosed within the tags in bold form.
Syntax: <B>. . .</B>
Italics <I> element - This is a container element started by <I> and ended by </I> tags.
This element is used to display the text enclosed within the tags in italics form.
Syntax : <I>. . .</I>
Underline <U> element - This is a container element started by <U> and ended by </U>
tags. This element is used to underline the text enclosed within the tags.
Syntax: <U>. . .</U>
Until now, everything has been text based and we have designed some very nice text
based web pages. We know, of course, that the World Wide Web (WWW) is much more
than just plain text. It is the ability of the web to also provide images that makes it so
popular. Images are of different types like pictures, graphics, icons, clip art, etc. Browse
the web and you will see all kinds of images. Let us now look at another web page and see
how we can set font, font size, font color and images in a web page. When we combine all
the tags to design a web page, the web page can be made visually appealing.
207
WEB APPLICATIONS
Now we have designed a web page in which we have used different types of fonts,
changed colour of the font and used images with different borders and alignment. The
web page is looking nice, bright and colourful. Let us now look at the code of the above
created web page and try to understand the use of the tags used to create the web page.
<HTML>
<HEAD>
<TITLE>Trees: A Renewable Resource</TITLE></HEAD>
<BODY>
<H1 ALIGN="CENTER">Trees A Renewable Resource</H1><BASEFONT
SIZE="4" >
<P><IMG SRC="E:\CBSE Book\HTML\tree2.jpg" BORDER=15 ALIGN="RIGHT"
WIDTH=100 HEIGHT=120>
<COMMENT>Using different fonts and font sizes</COMMENT>
<FONT SIZE="6" FACE="Georgia, Arial" COLOR="MAROON" >T</FONT>rees
are our breathing partners.We need trees in order to live. People
and animals depend on trees and plants for oxygen. As we breathe in,
our body takes in oxygen. As we breathe out, we give out carbon
dioxide. Trees do just the opposite. They take in carbon dioxide and
then release oxygen.</FONT><P>
<P><IMG SRC="E:\CBSE Book\HTML\t2.jpg" BORDER=8 ALIGN="LEFT"
WIDTH=80 HEIGHT=100>
208
WEB APPLICATIONS
1. Attribute: SRC
Use: SRC tells the browser where the source for the image is, that
is, the path and name of the image to be inserted. If no path is
given, the source is assumed to be the current folder - the
folder of the web page. Most browsers only support a few
image formats or file types. They are GIF and JPEG.
Syntax: SRC = "path/filename"
209
WEB APPLICATIONS
2. Attribute: BORDER
Use: BORDER is used to place (or eliminate) a border of specified
width around the image. Border widths are measured in
pixels. The BORDER="0" means that we want no border.
Syntax: BORDER = "n" - where n is a natural number.
3. Attribute: ALIGN
Use: ALIGN specifies the alignment of the image according to
surrounding contents of the page. Alignment can be middle,
top, bottom, left, right. Bottom is the default alignment!
Syntax: ALIGN = "alignment"
4. Attribute: WIDTH
Use: WIDTH specifies the horizontal width of the image. Width is
specified in number of pixels or as the percentage of page
width.
Syntax: WIDTH = "n/n%" - where n is a natural number
5. Attribute: HEIGHT
Use: HEIGHT specifies the height of the image. Height is specified
in number of pixels or as the percentage of page height.
Syntax: HEIGHT = "n" - where n is a natural number
Know More!
Exactly how big is one pixel? Does it have a specific size? The answer is that a pixel
does not have a specific size. Its size depends on a number of things. One of them is
the resolution of the monitor being used. A high resolution monitor has a smaller
size pixel than a low resolution monitor because a high resolution monitor has more
pixels per inch (or centimetre). Therefore the size of your image will vary a little
from computer to computer. However, your images (and text) will always be in the
right proportion no matter which monitor they are viewed on - and so they will
always look good in any browser.
210
WEB APPLICATIONS
FONT element - It is a container element started by <FONT> tag and ended by </FONT>
tag. The FONT element is used to add style, size, and color to the text. We use the size,
color, and face attributes to customize our fonts.
Syntax: <FONT FACE="font name" SIZE = n COLOR = "color" > . .
.</FONT>
2. Attribute: SIZE
Use: The SIZE attribute is used to specify the font size between 1
and 7 (7 is the largest).
Syntax: SIZE = "n" (n is a natural number between 1 and 7)
3. Attribute: COLOR
Use: Sets th color of the text. The color can be set by giving the
name of the color or its hexadecimal value.
Syntax: COLOR = "color"
Given below is a list of common font faces which are supported by most browsers.
211
WEB APPLICATIONS
In the web pages designed so far the text was displayed in the form of a paragraph, but if
we want to communicate some information in the form of bulleted/numbered lists then
we have to use the LIST element. A page designed using list elements is shown below:
<BODY>
<FONT FACE = "Times New Roman" size = "4">
<CENTER>QUIZ ON COMPUTERS</CENTER>
<IMG BORDER="5" SRC="QUIZ.jpg" ALIGN="RIGHT">
<HR color="BLACK">
<COMMENT>Beginning of first ordered list</COMMENT>
<OL START=1>
<LI>A Cathode Ray Tube is found in what?
<COMMENT>Beginning of second ordered list</COMMENT>
<OL START=1 TYPE=a>
<LI>CPU
<LI>Printer
<LI>Monitor
<LI>All of above
212
WEB APPLICATIONS
</OL>
<HR>
<LI>The output quality of a printer is measured by
<OL START=1 TYPE=a>
<LI>Dot per inch.
<LI>Dot per sq. inch.
<LI>Dots printed per unit time.
<LI>All of above.
</OL>
<HR>
</OL>
<H5>HOW DO YOU RATE THE QUESTIONS</H5>
<UL TYPE=CIRCLE>
<LI>GOOD
<LI>AVERAGE
<LI>BAD
</UL>
</FONT>
</BODY>
</HTML>
Lists - Lists help us to organize the contents on the web page in an ordered and sequential
manner. HTML supports three types of lists:
• Unordered lists (bulleted lists)
• Ordered lists (numbered)
• Definition Lists
In this chapter we shall study Unordered Lists and Ordered Lists only.
Ordered List (OL) element - It is a container element started by <OL> tag and ended by
</OL> tag. It displays a numbered list. In a numbered list each item is preceded by a
number or a letter. This element is used where the items are to be placed in a specific
order.
213
WEB APPLICATIONS
1. Attribute: START
Use: START indicates the starting number (or the serial number of
the first element) of the list. This number must be a positive
integer.
Syntax: START = "n" - where n is a natural number.
2. Attribute: TYPE
Use: TYPE defines the type of numbering sequence used for the list
items.
"A" specifies a sequence of uppercase letters.
"a" specifies sequence of lowercase letters.
"I" specifies a sequence of uppercase Roman numerals.
"i" specifies a sequence of lowercase Roman numerals.
"1" specifies a sequence of numbers.
Syntax: TYPE = "A"/"a"/"I"/"i"/"1"
Unordered List (UL) element - It is a container element started by <UL> tag and ended by
</UL> tag. It displays a bulleted list. In a bulleted list each item is preceded by a small
symbol called a bullet. The shape of the bullet can be a Circle, a Disk, or a Square.
1. Attribute: TYPE
Use: TYPE defines the type of bullet used for each list item. The
value can be:
o CIRCLE specifies a hollow bullet.
" DISC specifies a solid round bullet.
" SQUARE specifies a square bullet.
Syntax: START = "value"
214
WEB APPLICATIONS
List Item (LI) element - The LI element is an empty element specified by <LI> tag. It is
used inside OL and UL elements to define list items. Each list item has to be preceded by
<LI> tag.
Syntax: <LI> Item Name
By itself (if used without <OL> or <UL>), <LI> displays items in a bulleted list form. It
means that we can use LI element without OL or UL element also. But it is advised not to
do so.
Nested Lists - Nested lists occur when we put one list inside another list. The nested list
would be a list item (marked by <LI>) of the parent list.
Can you write the code for the nested list as shown below:
1. Book Mathematics
a. Chapter 1 b. Chapter 2 c. Chapter 3
2. Book English
a. Chapter 1 b. Chapter 2 c. Chapter 3
3. Book Science
a. Chapter 1 b. Chapter 2 c. Chapter 3
Tables - Let us now design a web page where we will display data in an organized manner
with the use of tables. Tables are very useful in the communication of data in a
meaningful way. Two examples of tables are shown below:
Figure 7.11 Time Table Figure 7.12 Price List made using table
215
WEB APPLICATIONS
Let us now look at the code for designing these web pages using tables:
<HTML>
<BODY>
<TABLE BORDER="7" CELLPADDING="7" CELLSPACING="10">
<COMMENT>Beginning of table row</COMMENT>
<TR BGCOLOR="#C0C0C0">
<TD>Class X </TD>
<TD> A</TD>
<TD> B</TD>
<TD> C</TD>
</TR>
<COMMENT>Beginning of second table row</COMMENT>
<TR BGCOLOR="#00FFFF">
<TD> Block 1</TD>
<TD>English</TD>
<TD BGCOLOR="#FFFFFF">Maths</TD>
<TD>Science</TD>
<TR BGCOLOR="#FFFF00">
<TD> Block 2</TD>
<TD>Science</TD>
<TD>English</TD>
<TD ROWSPAN="2">P.E.</TD>
</TR>
<TR BGCOLOR="#FFFFFF">
<TD> Block 3</TD>
<TD colspan=2>Hindi</TD>
</TR>
</TABLE>
</BODY>
</HTML>
216
WEB APPLICATIONS
<HTML>
<BODY>
<TABLE BGCOLOR="#EEEEEE" BORDER="1">
<CAPTION> <u>Price List</u> </CAPTION>
<TR>
<TH>Item Code</TH>
<TH>Name</TH>
<TH>Price</TH>
</TR>
<TR>
<TD>1001</TD> <TD>Mouse</TD> <TD>125</TD>
</TR>
<TR>
<TD>1002</TD> <TD>Keyboard</TD> <TD>300</TD>
</TR>
<TR>
<TD>1003</TD> <TD>DVD</TD> <TD>40</TD>
</TR>
<TR>
<TD>1001</TD> <TD>WebCam</TD> <TD>600</TD>
</TR>
</TABLE>
</BODY>
</HTML>
TABLE element - It is a container element started by <TABLE> tag and ended by </TABLE>
tag. It is the basic element for creating a table.
Syntax:
<TABLE ALIGN="Alignment" BGCOLOR="colorname" BORDER="n"
>. . .</TABLE>
217
WEB APPLICATIONS
1. Attribute: ALIGN
2. Attribute: BGCOLOR
3. Attribute: BORDER
Use: Sets the border size (width of the boundaries) of the table.
TABLE ROW (TR) element - It is a container element started by <TR> tag and ended by
</TR> tag. It is used to define table rows. The TR element is used inside the TABLE
element. The number of rows in a table corresponds to the instances of the TR element
within the table element. The contents of a row are given as a parameter to the TR
element. The contents of a table row may contain TH tags, which indicate table headings,
and TD tags, which indicate table data.
Syntax:
<TR ALIGN ="Alignment" VALIGN="VAlignment"
BGCOLOR="colorname"> . . . < / TR >
218
WEB APPLICATIONS
1. Attribute: ALIGN
Use: This controls whether the text in a row is aligned to the left,
right, or centre of a cell. Default alignment is Left.
2. Attribute: VALIGN
Use: This controls whether the text in a row is aligned to the top,
bottom, or middle of a cell. BOTTOM aligns the content with
the cell's bottom. MIDDLE centres the content within the cell
(the default). TOP aligns the content with the cell's top.
3. Attribute: BGCOLOR
TABLE DATA (TD) element - It is a container element started by <TD> tag and ended by
</TD> tag. It is used to specify the text in a cell of the table. The TD tag is used inside the
TR tag, which is inside the table tag. The number of columns in a table depends on the
number of TD elements within the TR element.
Syntax:
<TD ALIGN="Alignment" VALIGN="VAlignment"
BGCOLOR="colorname" > . . . </TD>
The attributes ALIGN, VALIGN, and BGCOLOR have their usual meaning as defined in <TR>
element.
If used the attributes of the <TD> tag will replace the attributes of the <TR> tag.
219
WEB APPLICATIONS
TABLE HEADING (TH) element - It is a container element started by <TH> tag and ended
by </TH> tag. It is used to create header values. The header values are displayed in a
bold font and centre aligned. The TH element is used to create column or row headings.
Syntax:
<TH ALIGN ="Alignment" VALIGN = "VAlignment"
• The attributes ALIGN, VALIGN, and BGCOLOR have their usual meaning as
defined in <TR> element.
• NOWRAP - Specifies that the contents of a cell cannot be broken, i.e., they do
not wrap onto the next line.
So far we have studied about the usual HTML commands like <HTML>, <HEAD> and
<BODY>. We have also learnt how to create lists and tables. But there is a limitation in all
the web pages that we have created, they are not interactive. When we view our
document in a web browser, we can merely view the information, we cannot interact with
the web page.
220
WEB APPLICATIONS
<HTML>
<HEAD> <TITLE> USING FORMS </TITLE> </HEAD>
<BODY>
<CENTER>
<FONT face="Courier New" size=5 color=red>FREE MAIL
INDIA.COM</FONT>
<br>
<FONT size=3>
<I>Get a FREE MAIL INDIA! ID and connect to people</I>
</FONT>
<COMMENT>Beginning of form tag</COMMENT>
<FORM NAME="FORM1" ACTION = "validate.html" METHOD = "GET">
<B> Personal Details </B> </CENTER>
Enter your name:
<INPUT TYPE="TEXT" SIZE=30 NAME="t1"> <br>
Gender. . . . . . .:
<INPUT TYPE="RADIO" NAME="r1"> MALE
<INPUT TYPE="RADIO" NAME="r1"> FEMALE <br>
Country . . . . . .:
<INPUT TYPE="TEXT" SIZE=30 NAME="t2"> <br><br>
<B><CENTER>Select an ID and password:</CENTER></B>
Desired Email ID . :
<INPUT TYPE="TEXT" SIZE=30 NAME="t3"> <BR>
Password . . . . . . .:
<INPUT TYPE="PASSWORD" SIZE=20 NAME="t4">
<FONT size=2><I> minimum 5 characters</I></FONT> <br>
Re-type password :
<INPUT TYPE="PASSWORD" SIZE=18 NAME="t5"> <br><br>
<CENTER><INPUT TYPE="SUBMIT" value="Create MyAccount"
name="s1"></CENTER>
</FORM>
</BODY>
</HTML>
We have used a FORM element to create the form. We have used interface element INPUT
with different values of TYPE attribute such as TEXT, RADIO, PASSWORD, and SUBMIT, to
get the user input. All the elements in the form must be defined between the <FORM> and
</FORM> tags. Other elements, such as heading, paragraph, and tables, etc., can also be
used in the <FORM> and </FORM> tags.
Thus, when the form is displayed in a web browser, the user can make choices and text
can be entered by using the interface elements defined with <INPUT> tag. The form made
221
WEB APPLICATIONS
can finally be submitted to a destination point whenever required. All these things will be
discussed one by one as we progress.
FORM element - It is a container element started by <FORM> tag and ended by </FORM>
tag. It is used to create a form on a web page.
1. Attribute: NAME
Use: This specifies the name of the form. But this name will not be
displayed on the form. As there can be more than one FORMs
in an HTML document, a name is required to differentiate one
form from another. The NAME attribute is optional if there is
only one FORM on the web page.
Syntax: NAME = "FormName"
2. Attribute: ACTION
Use: This specifies the URL where the form-data is sent when the
form is submitted. This URL is also called the destination of
the form.
Syntax: ACTION = "URL"
3. Attribute: METHOD
Use: This specifies how the form-data is submitted. Form-data can
be submitted using the methods get or post. With METHOD =
"get", the form-data is submitted as URL variables, and with
METHOD = "post", the form-data is submitted as HTTP post.
Syntax: METHOD = "method"
222
WEB APPLICATIONS
1. Attribute: TYPE
Use: The TYPE attribute determines the field type of input field to
be provided in the form. Field type can be one of the
following:
2. Attribute: NAME
Use: Specifies the name of the field. This name does not appear on
the FORM. It is required for the identification/ differentiation
as there can be more than one fields in a single FORM.
3. Attribute: VALUE
223
WEB APPLICATIONS
We will now discuss different field types (values of TYPE attribute) relevant to our
syllabus.
1. FieldType: TEXT
Use: It provides a single line text input field where the user can enter text.
Additional Attributes:
SIZE = "n" - Sets the visible size of the text field to n characters.
2. FieldType: PASSWORD
Use: It provides a single line text input field where the user can enter
password. A password field is different from a text field because a text field
displays whatever characters are entered by the user whereas a password
field shows one dot for each character input by the user. This is to prevent
others from seeing the password.
3. FieldType: RADIO
Use: It provides a radio button on the form. More than one radio buttons can
have (and in general have) the same name. All the radio buttons that have
the same name constitute a radio group. Only one radio button of a group
can be selected at one time. That is, from a group of radio buttons, if the
user selects a button, all the other buttons in the set are deselected. When
a form is submitted, selected radio button's value (specified by the VALUE
attribute) is submitted to the destination.
Additional Attributes:
224
WEB APPLICATIONS
4. FieldType: CHECKBOX
Use: It provides a check box on the form. With checkboxes, we can give the
users a list of items to choose from. The user can choose more than one
items from the list. We can make a group of checkboxes, by giving them the
same name. When a form is submitted, selected cheboxes' values (specified
by the VALUE attribute) are submitted to the destination.
Additional Attributes:
5. FieldType: SUBMIT
Use: This provides a button on the form. When this button is clicked, the
form is submitted to the destination.
Additional Attributes:
None -
6. FieldType: RESET
Use: This provides a button on the form. When this button is clicked, the
input fields on the form are reset to their default state.
Additional Attributes:
None -
XML
XML (eXtensible Markup Language) is also a markup language like HTML. But XML is
different from HTML in the sense that HTML describes how to display and format the data,
text and images in the browser whereas XML is used to describe the data. XML has nothing
to do with presentation of data in the browser. The XML standard was created by W3C to
provide an easy to use and standardized way to store self-describing data (Self-describing
data is data that describes both its content and its structure).
225
WEB APPLICATIONS
The main benefit of XML is that it can be used to share data between two entirely
different platforms. For example, we can take data from a database like MySQL, convert
it into XML, and then share it with any other platform like MS Excel, HTML etc. Each of
these receiving platforms can then convert the XML into a structure the platform uses
normally. This way communication between two potentially different platforms is
achieved using XML.
To store self-describing data, XML allows us to create our own tags. Once an XML file is
created with the help of user-defined tags, it needs to be transformed into the target
platform format. We shall take an example in which data in an XML file is transformed into
HTML format. The file used for this purpose is an XSLT (eXtensible Stylesheet Language
Transformations) file.
Example
Following is an XML code to store the data of a class - names of three students and one
teacher. You can type this code in any text editor and save the file with any name and
extension XML.
The first line in the code is the XML declaration which should always be
226
WEB APPLICATIONS
included. This is called the 'XML prolog'. The prolog in this example specifies
that the XML code confirms to version 1.0 of XML standard, and the encoding
scheme used is "UTF-8".
This statement links this xml file to the file class.xsl. It means that the file
class.xsl (shown later) will use this xml file and apply its rules to transform this
XML document.
• <class> . . . </class>
Each XML document contains one and only one root element (or parent
element) which encapsulates the data described in the XML file. In this
example <class> . . . </class> is the root element. The root element further
contains sub-elements (or child elements) which describe the actual data
values. In this example <student> . . . </student> and <teacher> . . .
</teacher> are the sub-elements of <class> . . . </class>.
So, the above XML file stores the data of a class which has:
This XML file data will be transformed and represented in HTML format by the file
class.xsl. This file name was specified in the XML code itself.The code of class.xsl is given
below. You can type this code in a text editor and save the file as class.xsl. class.xsl
becomes an XSLT (Extensible Stylesheet Language Transformations) file.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="teacher">
<p><u><xsl:value-of select="."/></u></p>
</xsl:template>
227
WEB APPLICATIONS
<xsl:template match="student">
<p><b><xsl:value-of select="."/></b></p>
</xsl:template>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Don't worry if this code is not clear to you. At this stage our aim is to understand the
concept of data storage in an XML file and not to understand the syntax of XSLT files.
Now if you open the above XML file in a browser, you will see the data in the following
format:
228
WEB APPLICATIONS
229
WEB APPLICATIONS
So the same data in an XML file can be represented in different ways. It all depends on
how the data is transformed and presented.
• HTML is used to display data and to focus on formatting of data, whereas XML is
used to describe data and focus on what data is.
• HTML tags are predefined, whereas XML tags are not predefined. We create our
own tags.
• HTML tags are not case sensitive, whereas XML tags are case sensitive.
Features of XML
• XML is extensible. XML allows the user to create his own tags and document
structure.
• XML can be used to store data. Applications can be written to store and retrieve
information.
• XML can be used to exchange data. In the real world, databases contain data in
different formats. It is difficult to exchange data between such systems over
the Internet. Converting the data to XML can help in solving this problem and
create data that can be read by different types of applications.
• XML is free. It can be written with a simple text editor or one of the many freely
available XML authoring tools, such as XML Notepad.
230
WEB APPLICATIONS
Future Trends
In the last fifteen years internet has reinvented itself. Nowadays we shop, bank,
work, meet people online and at times share what we are doing at any given
moment of time. Technology is always evolving - and none quite as fast as the
Internet. Let us try to visualize the future trends of internet.
In future we might see people traveling with headphones attached to their mobile
devices while a Text-to-Speech application reads them the latest articles from
their favorite sites. Browser will be able to comprehend the spoken command and
open the particular website which the user has requested for. Audio surfing could
be useful for commuters, children learning to read, tutors etc. For web
developers, there may be new accessibility opportunities especially for multi-
lingual sites.
In future with the help of development in semantic web technologies we will click
on the web page for the meeting, and our computer, will be able to comprehend it
as a form of appointment, will pick up all the right information, and understand it
and send it to all the right applications. Further, it will evoke those applications
directly (using web services) needing little or no human intervention.
The W3C Web Accessibility Initiative (WAI) brings together people from industry,
disability organizations, government, and research labs from around the world to
develop guidelines and resources to help make the Web accessible to people with
disabilities like auditory, cognitive, neurological, physical, speech, and visual
disabilities.In future hardware might be adaptable for people with motoric
disabilities. Software accessibility solutions for the future might include physical
modelling. For instance in case of sight disabled there are no or little audio
feedback from the games where concepts of physics are involved.In the future
such games might be connected with a sound engine or realtime audio.
231
WEB APPLICATIONS
Summary
• Web server delivers (serves) content, such as web pages, using the Hypertext
Transfer Protocol (HTTP), over the World Wide Web.
Structure Elements
Comment <! . . .> Your comments go between <! and >. </Comment>
<Comment>
232
WEB APPLICATIONS
List Elements
Element Start Tag Attributes End Tag
Unordered List <ul> type </ul>
Ordered List <ol> type, start </ol>
List Item <li> none
Image Element
Element Start Tag Attributes End Tag
Image <img> src, align, width, height </img>
Table Elements
Element Start Tag Attributes End Tag
Table <table> Align, bgcolor, border </table>
Table Row <tr> Align, valign, bgcolor </tr>
Table Data <td> Align, valign, bgcolor </td>
Table Header <th> Align, valign, bgcolor </th>
Caption <caption> Align, valign, bgcolor </caption>
233
WEB APPLICATIONS
Form Elements
• XML stands for eXtensible Markup Language. It is a markup language like HTML
but its is used to store the data and not to describe the presentation of data.
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. The address of a resource on the net is known as:
(c) [] (d) ()
234
WEB APPLICATIONS
6. The IMAGE tag uses the _______ attribute to specify the URL of the image to be
displayed.
7. The align attribute of <Table> tag refers to _________ placement of the table in
relation to the window screen.
8. Choose the best suitable input type to input gender from the user:
9. Elements, such as heading, paragraph and tables etc can be contained in the FORM
element.
235
WEB APPLICATIONS
13. Input type="________" will send the form to its destination place.
15. Radio buttons can be grouped together so that only one is selected at a time by using
the attribute:
236
WEB APPLICATIONS
2. Explain with an example the difference between container and empty elements.
3. What is the importance of the BODY element? List the commonly used attributes
within the <BODY> tag.
8. How can we create an HTML page that allows the user to enter his details on that
webpage? Explain with the help of suitable HTML code/example.
9. Mention the tags that are required to be used to create the given table.
Student Details
Nishi 14 Female
Rajat 16 Male
237
WEB APPLICATIONS
LAB EXERCISES
1. Write HTML code to display the following web pages:
a)
b)
Fresh Fruits
Qy lsgr ds fy,
ykHknk;d gS
238
WEB APPLICATIONS
d)
a) ONE 1 2 3
b) TWO
ii. ONE
iii. TWO
iv. THREE
1. share
2. play fair
239
WEB APPLICATIONS
• landmarks
• mountains
• lakes
• roads
• trails and
• waterways
<UL type="disc">
<LI> Sodium
<LI> Sulphur
</BODY>
</HTML>
240
WEB APPLICATIONS
b) <HTML>
<HEAD><TITLE>SCHEDULE</TITLE></HEAD>
<BODY>
<TABLE BORDER="3">
<CAPTION>VOLUNTEER SCHEDULE</CAPTION>
<TR BGCOLOR="#AAFFCC">
</TR>
<TR>
</TR>
<TR>
</TR>
<TR>
</TR>
</TABLE>
</BODY>
</HTML>
1. Students should perform search on a topic, such as: "nuclear armageddon" , "global
warming" etc. and ask the team to give a presentation of about 3 minutes each.
241
WEB APPLICATIONS
2. The team should use this Checklist to try to evaluate systematically some of the
search results.
Personal / Oraganisational / o
Personal o
Personal
Anonymous o
Organisational o
Organisational
o
Anonymous o
Anonymous
o
edu o
gov/mil/us o
edu o
gov/mil/us
o
in o
other o
in o
other
Navigation o
Simple o
Simple
o
Complex o
Complex
Contact details o
Available o
Available
o
Not Available o
Not Available
242
WEB APPLICATIONS
• Situation: You have just acquired stocks of an IT firm. Find out how the stock is
doing and find a copy of the annual report.
243
A PTE
H
8
R
C
• Recall and effectively use the SQL commands and clauses learnt in class XI.
In the previous class, you have learnt some database concepts and SQL commands.
You have also learnt how to access data from a table using various clauses of
SELECT command. In this lesson we are going to revise the database concepts and
SQL studied in class XI. That will make the base for further reading of the concepts
and some more SQL commands which are really very useful in practical
applications.
Database Concepts
You have already studied the following database concepts in class XI:
Software used to manage databases is called Data Base Management System (DBMS).
2. Relational Database: A database in which the data is stored in the form of relations
(also called tables) is called a Relational Database. In other words a Relational
Database is a collection of one or more tables.
244
MySQL - REVISION TOUR
Let us now revise MySQL concepts studied in class XI with the help of a Library database.
Note: As this is a revision lesson, all variations of SQL commands are not covered
here. It is suggested that they are revised through practical assignments.
In a school library, there are books which are issued to the students and the staff. These
books are also returned after a certain period of time. For proper functioning of this
system the librarian maintains a database (an organised collection of data) which
contains the relevant data of books, students, and staff. In a relational database, this
data may be organised as a collection of the following tables:
245
MySQL - REVISION TOUR
BOOKS
STUDENTS
STAFF
Using the data stored in these tables the librarian can find out any type of relevant
information regarding the books at any time. For example, she can find out:
• The list of books in the library which are published by any specific publisher or
author.
• The list of books with price in a specified range.
246
MySQL - REVISION TOUR
• Admission numbers of the students who have not returned the books issued to
them.
• The names of books issued to a particular staff member or student.
For the above tables the primary keys may be set as follows:
In the STUDENTS table LibCardNo can also be the primary key (Why?). It means that there
are two columns in the table STUDENTS that are unique for each row and can be set as the
primary key of the table. These two columns are candidate keys as they are the
candidates for primary key. Out of these two candidate keys we have chosen AdmNo as
the primary key. The other candidate key, i.e., LibCardNo, becomes the Alternate Key of
the table. Had we chosen LibCardNo as the primary key, AdmNo would have been called
the alternate key of the table.
In class XI we have studied that degree of a table is the number of columns in the table,
and the number of rows in a table is called its cardinality.
Can you tell what are the degrees and cardinalities of tables of Library database?
Libraries function without computers also. Is there any advantage of setting up a
computerised Library Database using an RDBMS? Discuss it with your teacher.
We shall be using MySQL for Library database.
Once MySQL is procured (downloaded from net, or copied from somewhere, or received
free with some book), it can be installed and the process of creating Library database can
be started.
247
MySQL - REVISION TOUR
248
MySQL - REVISION TOUR
DROP <columnname>;
249
MySQL - REVISION TOUR
[WHERE <condition>]
[WHERE <condn>];
250
MySQL - REVISION TOUR
Following are the clauses which can be used with SELECT command:
b. WHERE Used to specify the condition based on which rows of a table are
displayed.
c. BETWEEN Used to define the range of values within which the column
values must fall to make a condition true. Range includes both
the upper and the lower values.
f. IS NULL / Used to select rows in which the specified column is NULL (or is
NOT NULL NOT NULL)
Now, let us revise these commands with the help of Library database discussed above.
• After starting MySQL, our first job is to create a database in which all the tables
will be stored. For this we give the statement:
CREATE DATABASE Library;
This statement will create a database with the name Library using the
command CREATE DATABASE.
• Now we have to open this database so that we can create tables and do other
tasks in it. For this we give the following statement
USE Library;
After creating the database and opening it, we have to create tables. Before we create a
table, we should very carefully plan columns that we want to have in the table and type of
data to be stored in each column. The type of data decides what data types should be
251
MySQL - REVISION TOUR
specified for different columns of a table. There are many data types available in MySQL,
but a few which are used most often are:
Text CHAR(size)
VARCHAR(size)
NUMERIC DECIMAL(p,s)
INT(size) or INTEGER(size)
date DATE
After planning, we arrive at the following data types for columns of our tables in the
Library database. Here the column sizes are based on our assumption. These may be
different for different library databases.
BOOKS
Price DECIMAL(7, 2) We assume that the price of a book will not exceed
Rs. 99999.99
252
MySQL - REVISION TOUR
STUDENTS
STAFF
After deciding the columns to be kept in each table and their data types, we are ready to
create the tables.
253
MySQL - REVISION TOUR
(AccNo INTEGER(5),
Title VARCHAR(30),
Author VARCHAR(30),
Publisher VARCHAR(10),
Edition INTEGER(4),
Price DECIMAL(7,2));
(AdmNo VARCHAR(7),
LibCardNo INTEGER(4),
AccNo INTEGER(5),
IssueDate DATE,
ReturnDate DATE);
(EmpNo INTEGER(3),
AccNo INTEGER(5),
IssueDate DATE,
ReturnDate DATE);
254
MySQL - REVISION TOUR
• To further verify that the tables have been created as per the required
specifications, we view the structure of each table by giving the statements:
DESC Books;
DESC Students;
DESC Staff;
(i) Suppose we decide to categorise the books into categories 'A', 'B' and 'C'
based on some criteria. Then a new column Category of type CHAR(1) can
be added to the table by the statement:
ALTER TABLE Books ADD Category CHAR(1);
(ii) Suppose we wish to change the size of column 'publisher' of Books table
from 10 characters to 20 characters, then we can give the statement:
ALTER TABLE Books MODIFY Publisher VARCHAR(20);
(iii) Suppose we decide to remove the ReturnDate column from the table
STAFF. We can do so by the statement:
ALTER TABLE Staff DROP ReturnDate;
• Once the tables are created as per the required specifications, we can
populate these tables with the given sample data as follows:
à
For Books table:
INSERT INTO Books VALUES
255
MySQL - REVISION TOUR
à
For Students table:
INSERT INTO Students VALUES
à
For Staff table:
INSERT INTO Staff VALUES
• Now we can check whether the data has been entered into the tables correctly
or not by entering the statements:
SELECT * FROM Books;
We can use various clauses with SELECT command to display the data. Examples are
shown below:
• To check the names (without repetition) of various publishers whose books are
present in the library, we enter the statement:
SELECT DISTINCT Publisher FROM Books;
• To check the books of publisher 'APH' present in the library, we enter the
statement:
SELECT * from Books WHERE Publisher = 'APH';
• To display the books list for which the price is between ` 250 and ` 500, we
enter the statement:
SELECT * FROM Books WHERE Price > 250 and Price < 500;
256
MySQL - REVISION TOUR
• To display the books list for which the price is from ` 250 to ` 500, we enter the
statement:
SELECT * FROM Books WHERE Price >= 250 and Price <= 500;
OR
SELECT * FROM Books WHERE Price BETWEEN 250 and 500;
• To display the details of books from the publishers 'APH' 'JPH', or 'ABD', we enter
the statement:
SELECT * from Books
OR Publisher = 'JPH'
OR Publisher = 'ABD';
OR
SELECT * from Books
• To list the AccNo, Title, and Price of all the books whose Title contains the word
'History', we can enter the statement:
SELECT AccNo, Title, Price from Books
• To display the AccNo of all the books which have been issued to students but not
returned by them, we enter the statement:
SELECT AccNo FROM Students
• To Display a List of all the Books in the alphabetical ascending order of Titles,
we enter the statement:
SELECT * FROM Books ORDER BY Title;
257
MySQL - REVISION TOUR
• To get the same list in descending order of Titles, we enter the statement:
SELECT * FROM Books ORDER BY Title DESC;
• Now suppose a student returns a Book with AccNo 1245 on 12 August 2010, then
this information can be recorded in the Students table as follows:
UPDATE Students
SET ReturnDate = '2010-08-12'
WHERE AccNo = 1245;
• If we want to delete the records of all the books by the Publisher 'PPP' with
edition year earlier than 1990, we can enter the statement:
DELETE FROM Books
WHERE Publisher = 'PPP' AND Edition < 1990;
Suppose for some analysis we decide to keep track of how many times each book is issued.
This can be done if there is an extra column 'IssueFreq' in the table Books to keep this
count. Every time a book is issued, the corresponding value in this column is incremented
by 1. To add this extra column in the table, we enter the statement:
ALTER TABLE Books ADD IssueFreq INTEGER(3);
Functions in MySQL
Let us now revise the following single-row SQL functions which are available in MySQL:
Numeric Functions:
OR
POW(x,y)
258
MySQL - REVISION TOUR
String Functions:
259
MySQL - REVISION TOUR
10 DAYOFYEAR(date) Return the day of the year for the given date in
numeric format in the range 1 to 366.
260
MySQL - REVISION TOUR
2. Suppose we want to create another table and one column in that table will be
'Author'. In order to optimally utilize the storage space, we wish to find out what is
the maximum length of 'Author' in the table 'Books'. This value will guide us in
deciding the field width of 'Author' in the new table. So we enter the statement:
SELECT Author, LENGTH(Author)
FROM Books ORDER BY LENGTH(Author);
3. In order to produce a report we wish to display the book titles in upper case letters of
the alphabet. So we enter the statement:
SELECT AccNo, UCASE(Title) FROM Books;
4. Suppose a book with accession number 1050 is returned and we wish to enter the
current date as the ReturnDate in the table Students. We can give the statement:
UPDATE Students
SET ReturnDate = CURDATE()
WHERE AccNo = 1050;
5. Suppose we wish to find out which staff members got the books issued in the
previous calender year, then we can give the statement:
SELECT * FROM Staff WHERE YEAR(IssueDate) =
YEAR(CURDATE())-1;
What Next?
So far you have learnt how to work with single table at a time. None of the operations
discussed in class XI or in this lesson required us to access data simultaneously from
multiple tables. But in real life database implementations we have to access data from
multiple tables simultaneously, as will be clear from the following examples.
261
MySQL - REVISION TOUR
262
MySQL - REVISION TOUR
EXERCISES
Complete the following cross-word puzzle using SQL commands and clauses:
1 2 3
4 5 6
7 8
10
263
MySQL - REVISION TOUR
Clues:
Across Down
10. To add another column to the table 5. I don't want data in this table
6. It contains tables
1. MySQL is a /an
c. RDBMS d. Table
a. Power b. Degree
c. Cardinality d. Design
4. A database
264
MySQL - REVISION TOUR
a. Power b. Degree
c. Cardinality d. Design
9. DDL is
c. For inserting similar data in a table d. For deleting data from a table
265
MySQL - REVISION TOUR
LAB EXERCISES
Table: Loan_Accounts
Write SQL commands for the tasks 1 to 35 and write the output for the SQL commands 36
to 40:
Create Database and use it
1. Create the database LOANS.
2. Use the database LOANS.
Create Table / Insert Into
3. Create the table Loan_Accounts and insert tuples in it.
Simple Select
4. Display the details of all the loans.
5. Display the AccNo, Cust_Name, and Loan_Amount of all the loans.
Conditional Select using Where Clause
6. Display the details of all the loans with less than 40 instalments.
7. Display the AccNo and Loan_Amount of all the loans started before 01-04-2009.
266
MySQL - REVISION TOUR
Using NULL
9. Display the details of all the loans whose rate of interest is NULL.
10. Display the details of all the loans whose rate of interest is not NULL.
11. Display the amounts of various loans from the table Loan_Accounts. A loan amount
should appear only once.
12. Display the number of instalments of various loans from the table Loan_Accounts. An
instalment should appear only once..
13. Display the details of all the loans started after 31-12-2008 for which the number of
instalments are more than 36.
14. Display the Cust_Name and Loan_Amount for all the loans which do not have number
of instalments 36.
15. Display the Cust_Name and Loan_Amount for all the loans for which the loan amount
is less than 500000 or int_rate is more than 12.
16. Display the details of all the loans which started in the year 2009.
17. Display the details of all the loans whose Loan_Amount is in the range 400000 to
500000.
18. Display the details of all the loans whose rate of interest is in the range 11% to 12%.
Using IN Operator
19. Display the Cust_Name and Loan_Amount for all the loans for which the number of
instalments are 24, 36, or 48. (Using IN operator)
20. Display the details of all the loans whose Loan_Amount is in the range 400000 to
500000. (Using BETWEEN operator)
21. Display the details of all the loans whose rate of interest is in the range 11% to 12%.
267
MySQL - REVISION TOUR
22. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name ends with 'Sharma'.
23. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name ends with 'a'.
24. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name contains 'a'
25. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name does not contain 'P'.
26. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name contains 'a' as the second last character.
27. Display the details of all the loans in the ascending order of their Loan_Amount.
28. Display the details of all the loans in the descending order of their Start_Date.
29. Display the details of all the loans in the ascending order of their Loan_Amount and
within Loan_Amount in the descending order of their Start_Date.
30. Put the interest rate 11.50% for all the loans for which interest rate is NULL.
31. Increase the interest rate by 0.5% for all the loans for which the loan amount is more
than 400000.
33. Delete the records of all the loans whose start date is before 2007.
35. Add another column Category of type CHAR(1) in the Loan table.
268
MySQL - REVISION TOUR
269
A PTE
H
9
R
C
In the previous class, you have learnt some database concepts and SQL commands.
You have also learnt how to create databases and tables within databases and how
to access data from a table using various clauses of SELECT command. In this
chapter you shall learn some more clauses and functions in SQL to access data
from a table and how to access data from multiple tables of a database.
Puzzle 8
It was Iftar party in Lucknow that Mr. David met Mr. Naqvi. They became friends and
exchanged their phone numbers. After a few days, Mr. David rang up and invited Mr. Naqvi
for New Year party at his house and gave him his house number as follows:
"I live in a long street. Numbered on the side of my house are the houses one, two, three
and so on. All the numbers on one side of my house add up to exactly the same as all the
270
MORE ON DATABASES AND SQL
numbers on the other side of my house. I know there are more than thirty houses on that
side of the street, but not so many as 50."
With this information, Mr. Naqvi was able to find Mr. David's house number. Can you also
find?
Such situations are faced by the developers of RDBMS software where they have to think
of retrieval of data from multiple tables satisfying some specified conditions.
Let us now move ahead with SQL and more database concepts.
Ms. Shabana Akhtar is in-charge of computer department in a Shoe factory. She has
created a database 'Shoes' with the following tables:
SHOES
(To store the information about various types of shoes made in the factory)
+--------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| code | char(4) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| type | varchar(10) | YES | | NULL | |
| size | int(2) | YES | | NULL | |
| cost | decimal(6,2) | YES | | NULL | |
| margin | decimal(4,2) | YES | | NULL | |
| Qty | int(4) | YES | | NULL | |
+--------+--------------+------+-----+---------+-------+
CUSTOMERS
(To store the data of customers)
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| cust_Code | char(4) | NO | PRI | NULL | |
| name | varchar(30) | YES | | NULL | |
| address | varchar(50) | YES | | NULL | |
| phone | varchar(30) | YES | | NULL | |
| category | char(1) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
271
MORE ON DATABASES AND SQL
ORDERS
(To store the data of orders placed by customers)
+-------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| order_no | int(5) | NO | PRI | NULL | |
| cust_code | char(4) | YES | | NULL | |
| Shoe_Code | char(4) | YES | | NULL | |
| order_qty | int(4) | YES | | NULL | |
| order_date | date | YES | | NULL | |
| target_date | date | YES | | NULL | |
+-------------+---------+------+-----+---------+-------+
SHOES
+------+----------------+--------+------+--------+--------+------+
| Code | Name | type | size | cost | margin | Qty |
+------+----------------+--------+------+--------+--------+------+
| 1001 | School Canvas | School | 6 | 132.50 | 2.00 | 1200 |
| 1002 | School Canvas | School | 7 | 135.50 | 2.00 | 800 |
| 1003 | School Canvas | School | 8 | 140.75 | 2.00 | 600 |
| 1011 | School Leather | School | 6 | 232.50 | 2.00 | 2200 |
| 1012 | School Leather | School | 7 | 270.00 | 2.00 | 1280 |
| 1013 | School Leather | School | 8 | 320.75 | NULL | 1100 |
| 1101 | Galaxy | Office | 7 | 640.00 | 3.00 | 200 |
| 1102 | Galaxy | Office | 8 | 712.00 | 3.00 | 500 |
| 1103 | Galaxy | Office | 9 | 720.00 | 3.00 | 400 |
| 1201 | Tracker | Sports | 6 | 700.00 | NULL | 280 |
| 1202 | Tracker | Sports | 7 | 745.25 | 3.50 | NULL |
| 1203 | Tracker | Sports | 8 | 800.50 | 3.50 | 600 |
| 1204 | Tracker | Sports | 9 | 843.00 | NULL | 860 |
+------+----------------+--------+------+--------+--------+------+
272
MORE ON DATABASES AND SQL
CUSTOMERS
+-----------+----------------+------------------------+--------------------+----------+
|Cust_Code |name |address |Phone |Category |
+-----------+----------------+------------------------+--------------------+----------+
|C001 |NoveltyShoes |RajaNagar,Bhopal |4543556,97878989 |A |
|C002 |AaramFootwear |31,MangalBazar,Agra |NULL |B |
|C003 |FootComfort |NewMarket,Saharanpur |51917142,76877888 |B |
|C004 |PoojaShoes |JanakPuri,NewDelhi |61345432,98178989 |A |
|C005 |DevShoes |MohanNagar,Ghaziabad |NULL |C |
+-----------+----------------+------------------------+--------------------+----------+
ORDERS
+----------+-----------+-----------+-----------+------------+-------------+
| order_no | cust_code | Shoe_Code | order_qty | order_date | target_date |
+----------+-----------+-----------+-----------+------------+-------------+
| 1 | C001 | 1001 | 200 | 2008-12-10 | 2008-12-15 |
| 2 | C001 | 1002 | 200 | 2008-12-10 | 2008-12-15 |
| 3 | C003 | 1011 | 150 | 2009-01-08 | 2009-01-13 |
| 4 | C002 | 1012 | 250 | 2009-01-08 | 2009-01-13 |
| 5 | C001 | 1011 | 400 | 2009-01-10 | 2009-01-15 |
| 6 | C002 | 1101 | 300 | 2009-01-10 | 2009-01-15 |
| 7 | C004 | 1201 | 200 | 2009-01-10 | 2009-01-15 |
| 8 | C005 | 1102 | 350 | 2009-01-10 | 2009-01-15 |
| 9 | C001 | 1103 | 225 | 2009-01-13 | 2009-01-18 |
| 10 | C002 | 1203 | 200 | 2009-01-14 | 2009-01-19 |
+----------+-----------+-----------+-----------+------------+-------------+
Let us now see how this database helps Ms. Akhtar in generating various reports quickly.
Aggregate Functions
In class XI we studied about single row functions available in SQL. A single row function
works on a single value. SQL also provides us multiple row functions. A multiple row
function works on multiple values. These functions are called aggregate functions or
group functions. These functions are:
273
MORE ON DATABASES AND SQL
MAX() :
MAX() function is used to find the highest value of any column or any expression based on
a column. MAX() takes one argument which can be any column name or a valid expression
involving a column name. e.g.,
274
MORE ON DATABASES AND SQL
MIN() :
MIN() function is used to find the lowest value of any column or an expression based on a
column. MIN() takes one argument which can be any column name or a valid expression
involving a column name. e.g.,
275
MORE ON DATABASES AND SQL
AVG() :
AVG() function is used to find the average value of any column or an expression based on a
column. AVG() takes one argument which can be any column name or a valid expression
involving a column name. Here we have a limitation: the argument of AVG() function can
be of numeric (int/decimal) type only. Averages of String and Date type data are not
defined. E.g.,
276
MORE ON DATABASES AND SQL
SUM() :
SUM() function is used to find the total value of any column or an expression based on a
column. SUM() also takes one argument which can be any column name or a valid
expression involving a column name. Like AVG(), the argument of SUM() function can be
of numeric (int/decimal) type only. Sums of String and Date type data are not defined.
e.g.,
277
MORE ON DATABASES AND SQL
COUNT() :
COUNT() function is used to count the number of values in a column. COUNT() takes one
argument which can be any column name, an expression based on a column, or an asterisk
(*). When the argument is a column name or an expression based on a column, COUNT()
returns the number of non-NULL values in that column. If the argument is a *, then
COUNT() counts the total number of rows satisfying the condition, if any, in the table.
e.g.,
278
MORE ON DATABASES AND SQL
None of the aggregate functions takes NULL into consideration. NULL is simply ignored by
all the aggregate functions. For example, the statement:
SELECT COUNT(*) FROM shoes;
Indicating that there are 13 records in the Shoes table. Whereas the query:
SELECT COUNT(margin) FROM shoes;
This output indicates that there are 10 values in the margin column of Shoes table. This
means there are 3 (13-10) NULLs in the margin column.
This feature of aggregate functions ensures that NULLs don't play any role in actual
calculations. For example, the following statement:
SELECT AVG(margin) FROM shoes;
The average margin has been calculated by adding all the 10 non NULL values from the
margin column and dividing the sum by 10 and not by 13.
279
MORE ON DATABASES AND SQL
Know more!
There are some more aggregate functions available in MySQL. Try to find out what
are those. Also try to use them.
GROUP BY
In practical applications many times there arises a need to get reports based on some
groups of data. These groups are based on some column values. For example,
• The management of the shoe factory may want to know what is the total
quantity of shoes of various types. i.e., what is the total quantity of shoes of
type School, Office, and Sports each.
• The management may also want to know what is the maximum, minimum, and
average margin of each type of shoes.
• It may also be required to find the total number of customers in each category.
For the above three situations, the statements with GROUP BY clause are given below:
In the first situation we want MySQL to divide all the records of shoes table into different
groups based on their type (GROUP BY type) and for each group it should display the type
and the corresponding total quantity (SELECT type, SUM(qty)). So the complete
statement to do this is:
SELECT type, SUM(qty) FROM shoes
GROUP BY type; G1
280
MORE ON DATABASES AND SQL
In the third situation we want MySQL to divide all the records of Customers table into
different groups based on the their Category (GROUP BY Category) and for each group it
should display the Category and the corresponding number of records (SELECT Category,
COUNT(*)). So the complete statement to do this is:
SELECT category, COUNT(*) FROM customers GROUP BY category; G3
+----------+----------+
| category | COUNT(*) |
+----------+----------+
|A | 2 |
|B | 2 |
|C | 1 |
+----------+----------+
281
MORE ON DATABASES AND SQL
This statement produces the following output. Try to explain this this output.
+-----------+----------------+
| cust_code | SUM(order_qty) |
+-----------+----------------+
| C001 | 1025 |
| C002 | 750 |
| C003 | 150 |
| C004 | 200 |
| C005 | 350 |
+-----------+----------------+
+-----------+----------------+
| shoe_code | SUM(order_qty) |
+-----------+----------------+
| 1001 | 200 |
| 1002 | 200 |
| 1011 | 550 |
| 1012 | 250 |
| 1101 | 300 |
| 1102 | 350 |
| 1103 | 225 |
| 1201 | 200 |
| 1203 | 200 |
+-----------+----------------+
If you carefully observe these examples, you will find that GROUP BY is always used in
conjunction with some aggregate function(s). A SELECT command with GROUP BY clause
has a column name and one or more aggregate functions which are applied on that
column and grouping is also done on this column only.
HAVING :
Sometimes we do not want to see the whole output produced by a statement with GROUP
BY clause. We want to see the output only for those groups which satisfy some condition.
It means we want to put some condition on individual groups (and not on individual
records). A condition on groups is applied by HAVING clause. As an example reconsider the
282
MORE ON DATABASES AND SQL
statement G1 discussed above. The statement produced three records in the output - one
for each group. Suppose, we are interested in viewing only those groups' output for which
the total quantity is more than 1500 (SUM(Qty) > 1500). As this condition is applicable to
groups and not to individual rows, we use HAVING clause as shown below:
SELECT type, SUM(qty) FROM shoes
+--------+----------+
| type | SUM(qty) |
+--------+----------+
| School | 7180 |
| Sports | 1740 |
+--------+----------+
Now suppose for G2 we want the report only for those types for which the average margin
is more than 2. For this, following is the statement and the corresponding output:
SELECT type, SUM(qty) FROM shoes
+--------+----------+
| type | SUM(qty) |
+--------+----------+
| Office | 1100 |
| Sports | 1740 |
+--------+----------+
In these statements if we try to put the condition using WHERE instead of HAVING, we
shall get an error. Another way of remembering this is that whenever a condition involves
an aggregate function, then we use HAVING clause in conjunction with GROUP BY clause.
Situations may also arise when we want to put the conditions on individual records as well
as on groups. In such situations we use both WHERE (for individual records) and HAVING
(for groups) clauses. This can be explained with the help of the following examples:
• The management of the shoe factory may want to know what is the total
quantity of shoes, of sizes other than 6, of various types. i.e., what is the total
quantity of shoes (of sizes other than 6) of type School, Office, and Sports each.
283
MORE ON DATABASES AND SQL
Moreover, the report is required only for those groups for which the total
quantity is more than 1500.
• The management may also want to know what is the maximum, minimum, and
average margin of each type of shoes. But in this reports shoes of sizes 6 and 7
only should be included. Report is required only for those groups for which the
minimum margin is more than 2.
The statements and their outputs corresponding to above requirements are given below:
SELECT type, SUM(qty) FROM shoes
GROUP BY type HAVING sum (qty) > 1500; Checks individual group
+--------+----------+
| type | SUM(qty) |
+--------+----------+
| School | 3780 |
+--------+----------+
+--------+-------------+-------------+-------------+
| type | MIN(margin) | MAX(margin) | AVG(margin) |
+--------+-------------+-------------+-------------+
| Office | 3.00 | 3.00 | 3.000000 |
| Sports | 3.50 | 3.50 | 3.500000 |
+--------+-------------+-------------+-------------+
In each situation that we have faced so far, the data was extracted from a single table.
There was no need to refer to more than one tables in the same statement. But many
times, in real applications of databases, it is required to produce reports which need data
from more than one tables. To understand this consider the following situations:
284
MORE ON DATABASES AND SQL
• The management of the shoe factory wants a report of orders which lists three
columns: Order_No, corresponding customer name, and phone number.
- (MT-1)
In this case order number will be taken from Orders table and corresponding
customer name from Customers table.
• The management wants a four-column report containing order_no, order_qty,
name of the corresponding shoe and its cost. - (MT-2)
In this case order number and order quantity will be taken from Orders table
and corresponding shoe name and cost from Shoes table.
• The management wants the names of customers who have placed any order of
quantity more than 300. - (MT-3)
In this case Order quantity will be checked in Orders table and for each record
with quantity more than 300, corresponding Customer name will be taken
from Customers table.
• The management wants a report in which with each Order_No management
needs name of the corresponding customer and also the total cost (Order
quantity x Cost of the shoe) of the order are shown. - (MT-4)
In this case order number will be taken from Orders table and corresponding
customer name from Customers table. For the cost of each order the quantity
will be taken from Orders table and the Cost from Shoes table.
In all these cases, the data is to be retrieved from multiple tables. SQL allows us to write
statements which retrieve data from multiple tables.
Product
+------+-------------+
| Code | Name |
+------+-------------+
| P001 | Toothpaste |
| P002 | Shampoo |
| P003 | Conditioner |
+------+-------------+
285
MORE ON DATABASES AND SQL
Supplier
+----------+--------------+-------------+
| Sup_Code | Name | Address |
+----------+--------------+-------------+
| S001 | DC & Company | Uttam Nagar |
| S002 | SURY Traders | Model Town |
+----------+--------------+-------------+
Order_table
+----------+--------+----------+
| Order_No | P_Code | Sup_Code |
+----------+--------+----------+
| 1 | P001 | S002 |
| 2 | P002 | S002 |
+----------+--------+----------+
Cartesian product (also called Cross Join) of two tables is a table obtained by pairing up
each row of one table with each row of the other table. This way if two tables contain 3
rows and 2 rows respectively, then their Cartesian product will contain 6 (=3x2) rows. This
can be illustrated as follows:
(1,a)
1 a (2,a)
(3,a)
2
(1,b)
3 b (2,b)
(3,b)
286
MORE ON DATABASES AND SQL
The number of columns in the Cartesian product is the sum of the number of columns in
both the tables. In SQL, Cartesian product of two rows is obtained by giving the names of
both tables in FROM clause. An example of Cartesian product is shown below:
SELECT * FROM order_table, product;
To give the output of this query, MySQL will pair the rows of the mentioned tables as
follows:
Order_table Product
+----------+--------+----------+ +------+-------------+
+----------+--------+----------+ +------+-------------+
| | | |
+------+-------------+
+----------+--------+----------+------+-------------+
| Order_No | P_Code | Sup_Code | Code | Name | -(CP-1)
+----------+--------+----------+------+-------------+
| 1 | P001 | S002 | P001 | Toothpaste |
| 2 | P002 | S002 | P001 | Toothpaste |
| 1 | P001 | S002 | P002 | Shampoo |
| 2 | P002 | S002 | P002 | Shampoo |
| 1 | P001 | S002 | P003 | Conditioner |
| 2 | P002 | S002 | P003 | Conditioner |
+----------+--------+----------+------+-------------+
Here we observe that the Cartesian product contains all the columns from both tables.
Each row of the first table (Order_table) is paired with each row of the second table
(Product).
287
MORE ON DATABASES AND SQL
If we change the sequence of table names in the FROM clause, the result will remain the
same but the sequence of rows and columns will change. This can be observed in the
following statement and the corresponding output.
SELECT * FROM product, order_table;
+------+-------------+----------+--------+----------+
| Code | Name | Order_No | P_Code | Sup_Code | -(CP-2)
+------+-------------+----------+--------+----------+
| P001 | Toothpaste | 1 | P001 | S002 |
| P001 | Toothpaste | 2 | P002 | S002 |
| P002 | Shampoo | 1 | P001 | S002 |
| P002 | Shampoo | 2 | P002 | S002 |
| P003 | Conditioner | 1 | P001 | S002 |
| P003 | Conditioner | 2 | P002 | S002 |
+------+-------------+----------+--------+----------+
We can have Cartesian product of more than two tables also. Following is the Cartesian
Product of three tables:
SELECT * FROM order_table, supplier, product;
-(CP-3)
+----------+--------+----------+----------+--------------+-------------+------+-------------+
| Order_No | P_Code | Sup_Code | Sup_Code | Name | Address | Code |Name |
+----------+--------+----------+----------+--------------+-------------+------+-------------+
| 1 | P001 | S002 | S001 | DC & Company | Uttam Nagar | P001 |Toothpaste |
| 2 | P002 | S002 | S001 | DC & Company | Uttam Nagar | P001 |Toothpaste |
| 1 | P001 | S002 | S002 | SURY Traders | Model Town | P001 |Toothpaste |
| 2 | P002 | S002 | S002 | SURY Traders | Model Town | P001 |Toothpaste |
| 1 | P001 | S002 | S001 | DC & Company | Uttam Nagar | P002 |Shampoo |
| 2 | P002 | S002 | S001 | DC & Company | Uttam Nagar | P002 |Shampoo |
| 1 | P001 | S002 | S002 | SURY Traders | Model Town | P002 |Shampoo |
| 2 | P002 | S002 | S002 | SURY Traders | Model Town | P002 |Shampoo |
| 1 | P001 | S002 | S001 | DC & Company | Uttam Nagar | P003 |Conditioner |
| 2 | P002 | S002 | S001 | DC & Company | Uttam Nagar | P003 |Conditioner |
| 1 | P001 | S002 | S002 | SURY Traders | Model Town | P003 |Conditioner |
| 2 | P002 | S002 | S002 | SURY Traders | Model Town | P003 |Conditioner |
+----------+--------+----------+----------+--------------+-------------+------+-------------+
The complete Cartesian product of two or more tables is, generally, not used directly.
But, some times it is required. Suppose the company with the above database wants to
send information of each of its products to each of its suppliers. For follow-up, the
management wants a complete list in which each Supplier's detail is paired with each
Product's detail. For this, the computer department can produce a list which is the
Cartesian product of Product and Supplier tables, as follows:
SELECT *, ' ' AS Remarks FROM Product, Supplier;
288
MORE ON DATABASES AND SQL
But we can extract meaningful information from the Cartesian product by placing some
conditions in the statement. For example, to find out the product details corresponding
to each Order details, we can enter the following statement:
SELECT * FROM order_table, product WHERE p_code = code;
+----------+--------+----------+------+------------+
| Order_No | P_Code | Sup_Code | Code | Name |
+----------+--------+----------+------+------------+
| 1 | P001 | S002 | P001 | Toothpaste |
| 2 | P002 | S002 | P002 | Shampoo |
+----------+--------+----------+------+------------+
Two table names are specified in the FROM clause of this statement, therefore MySQL
creates a Cartesian product of the tables. From this Cartesian product MySQL selects only
those records for which P_Code (Product code specified in the Order_table table)
matches Code (Product code in the Product table). These selected records are then
displayed.
289
MORE ON DATABASES AND SQL
It always happens that whenever we have to get the data from more than one tables,
there is some common column based on which the meaningful data is extracted from the
tables. We specify table names in the FROM clause of SELECT command. We also give the
condition specifying the matching of common column. (When we say common column, it
does not mean that the column names have to be the same. It means that the columns
should represent the same data with the same data types.) Corresponding to this
statement, internally the Cartesian product of the tables is made. Then based on the
specified condition the meaningful data is extracted from this Cartesian product and
displayed.
Let us take another example of producing a report which displays the supplier name and
address corresponding to each order.
SELECT Order_No, Order_table.Sup_Code, Name, Address
+----------+----------+--------------+------------+
| Order_No | Sup_Code | Name | Address |
+----------+----------+--------------+------------+
| 1 | S002 | SURY Traders | Model Town |
| 2 | S002 | SURY Traders | Model Town |
+----------+----------+--------------+------------+
In this statement the tables referred are Order_table and Supplier. In these tables
sup_code is the common column. This column exists with same name in both the tables.
Therefore whenever we mention it, we have to specify the table from which we want to
extract this column. This is known as qualifying the column name. If we don't qualify the
common column name, the statement would result into an error due to the ambiguous
the column names.
290
MORE ON DATABASES AND SQL
Let us now get back to our original Shoe database and see how Ms. Akhtar uses the
concept of joins to extract data from multiple tables.
Following are the queries and corresponding outputs for the situations MT-2, MT-3, and
MT-4 respectively:
SELECT order_no , Order_Qty, name, cost
FROM orders, shoes WHERE Shoe_Code = code;
291
MORE ON DATABASES AND SQL
+----------+-----------+----------------+--------+
| order_no | Order_Qty | name | cost |
+----------+-----------+----------------+--------+
| 1 | 200 | School Canvas | 132.50 |
| 2 | 200 | School Canvas | 135.50 |
| 3 | 150 | School Leather | 232.50 |
| 4 | 250 | School Leather | 270.00 |
| 5 | 400 | School Leather | 232.50 |
| 6 | 300 | Galaxy | 640.00 |
| 7 | 200 | Tracker | 700.00 |
| 8 | 350 | Galaxy | 712.00 |
| 9 | 225 | Galaxy | 720.00 |
| 10 | 200 | Tracker | 800.50 |
+----------+-----------+----------------+--------+
SELECT name, address FROM orders, customers
WHERE orders.cust_code = customers.cust_code
and order_qty > 300;
+---------------+------------------------+
| name | address |
+---------------+------------------------+
| Novelty Shoes | Raja Nagar, Bhopal |
| Dev Shoes | Mohan Nagar, Ghaziabad |
+---------------+------------------------+
SELECT order_no, Order_Qty, customers.name,
cost*order_qty as 'Order Cost'
FROM orders, shoes, Customers
WHERE Shoe_Code = code
and Orders.Cust_Code = Customers.Cust_Code
order by order_no;
292
MORE ON DATABASES AND SQL
+----------+-----------+----------------+------------+
| order_no | Order_Qty | name | Order Cost |
+----------+-----------+----------------+------------+
| 1 | 200 | Novelty Shoes | 26500.00 |
| 2 | 200 | Novelty Shoes | 27100.00 |
| 3 | 150 | Foot Comfort | 34875.00 |
| 4 | 250 | Aaram Footwear | 67500.00 |
| 5 | 400 | Novelty Shoes | 93000.00 |
| 6 | 300 | Aaram Footwear | 192000.00 |
| 7 | 200 | Pooja Shoes | 140000.00 |
| 8 | 350 | Dev Shoes | 249200.00 |
| 9 | 225 | Novelty Shoes | 162000.00 |
| 10 | 200 | Aaram Footwear | 160100.00 |
+----------+-----------+----------------+------------+
Here is another statement extracting data from multiple tables. Try to find out what will
be its output and then try this statement on computer and check whether you thought of
the correct output.
SELECT order_no , Order_Qty, name, cost
FROM orders, shoes
WHERE Shoe_Code = code and order_qty > 200;
Foreign Key :
As we have just seen, in a join the data is retrieved from the Cartesian product of two
tables by giving a condition of equality of two corresponding columns - one from each
table. Generally, this column is the Primary Key of one table. In the other table this
column is the Foreign key. Such a join which is obtained by putting a condition of equality
on cross join is called an 'equi-join'. As an example, once again consider the Product,
Supplier, and Order tables referenced earlier. For quick reference these tables are shown
once again:
Product
+------+-------------+
| Code | Name |
+------+-------------+
| P001 | Toothpaste |
| P002 | Shampoo |
| P003 | Conditioner |
+------+-------------+
293
MORE ON DATABASES AND SQL
Supplier
+----------+--------------+-------------+
| Sup_Code | Name | Address |
+----------+--------------+-------------+
| S001 | DC & Company | Uttam Nagar |
| S002 | SURY Traders | Model Town |
+----------+--------------+-------------+
Order_table
+----------+--------+----------+
| Order_No | P_Code | Sup_Code |
+----------+--------+----------+
| 1 | P001 | S002 |
| 2 | P002 | S002 |
+----------+--------+----------+
In these tables there is a common column between Product and Order_table tables (Code
and P_Code respectively) which is used to get the Equi-Join of these two tables. Code is
the Primary Key of Product table and in Order_table table it is not so (we can place more
than one orders for the same product). In the order_table, P_Code is a Foreign Key.
Similarly, Sup_Code is the primary key in Supplier table whereas it is a Foreign Key is
Order_table table. A foreign key in a table is used to ensure referential integrity and to
get Equi-Join of two tables.
This property of a relational database which ensures that no entry in a foreign key column
of a table can be made unless it matches a primary key value in the corresponding related
table is called Referential Integrity.
294
MORE ON DATABASES AND SQL
Union
Union is an operation of combining the output of two SELECT statements. Union of two
SELECT statements can be performed only if their outputs contain same number of
columns and data types of corresponding columns are also the same. The syntax of UNION
in its simplest form is:
SELECT <select_list>
FROM <tablename>
[WHERE <condition> ]
UNION [ALL]
SELECT <select_list>
FROM <tablename>
[WHERE <condition> ];
Union does not display any duplicate rows unless ALL is specified with it.
Example:
Suppose a company deals in two different categories of items. Each category contains a
number of items and for each category there are different customers. In the database
there are two customer tables: Customer_Cat_1 and Customer_Cat_2. If it is required to
produce a combined list of all the customers, then it can be done as follows:
SELECT Cust_Code from Customer_Cat_1
UNION
SELECT Cust_Code from Customer_Cat_2;
If a customer exists with same customer code in both the tables, its code will be displayed
only once - because Union does display duplicate rows. If we explicitly want the duplicate
rows, then we can enter the statement:
SELECT Cust_Code from Customer_Cat_1
UNION ALL
SELECT Cust_Code from Customer_Cat_2;
295
MORE ON DATABASES AND SQL
Constraints
Many times it is not possible to keep a manual check on the data that is going into the
tables using INSERT or UPDATE commands. The data entered may be invalid. MySQL
provides some rules, called Constraints, which help us, to some extent, ensure validity of
the data. These constraints are:
2. NOT NULL Makes sure that NULLs are not accepted in the specified
column.
3. FOREIGN KEY Data will be accepted in this column, if same data value
exists in a column in another related table. This other
related table name and column name are specified while
creating the foreign key constraint.
We shall discuss only the PRIMARY KEY and NOT NULL constraints in this book. Other
constraints are beyond the scope of this book.
PRIMARY KEY:
Recall that primary key of a table is a column or a group of columns that uniquely
identifies a row of the table. Therefore no two rows of a table can have the same primary
key value. Now suppose that the table Shoes is created with the following statement:
296
MORE ON DATABASES AND SQL
Qty INT(4));
We know that in this table Code is the Primary key. But, MySQL does not know that!
Therefore it is possible to enter duplicate values in this column or to enter NULLs in this
column. Both these situations are unacceptable.
To make sure that such data is not accepted by MySQL, we can set Code as the primary key
of Shoes table. It can be done by using the PRIMARY KEY clause at the time of table
creation as follows:
CREATE TABLE Shoes
or as follows:
CREATE TABLE Shoes
To create a table Bills with the combination of columns Order_No and Cust_Code as the
primary key, we enter the statement:
CREATE TABLE bills
297
MORE ON DATABASES AND SQL
Contrary to our expectation, we get an error (Multiple primary key defined) with this
statement. The reason is that MySQL interprets this statement as if we are trying to
create two primary keys of the table - Order_Num, and Cust_code. But a table can have at
most one primary key. To set this combination of columns a primary key we have to enter
the statement as follows:
CREATE TABLE bills
Let us now check the table structure with the command: DESC bills;
NOT NULL:
Many times there are some columns of a table in which NULL values should not be
accepted. We always want some known valid data values in these columns. For example,
we cannot have an order for which the customer code is not known. It means whenever
we enter a row in the orders table, corresponding customer code cannot be NULL.
Similarly while entering records in the Shoes table, we have to mention the Shoe size, it
cannot be set NULL. There may be any number of such situations.
While creating a table we can specify in which columns NULLs should not be accepted as
follows:
298
MORE ON DATABASES AND SQL
Now if we try to enter a NULL in the specified column, MySQL will reject the entry and
give an error.
299
MORE ON DATABASES AND SQL
ALTER TABLE
In class XI, we have studied that a new column can be added to a table using ALTER TABLE
command. Now we shall study how ALTER TABLE can be used:
• to add a constraint
• to remove a constraint
This will set Code as the primary key of the table. But if the Code column already contains
some duplicate values, then this statement will give an error.
In MySQL, it is also possible to change the primary key column(s) of a table. Suppose, in
the Shoes table, istread of Code, we want to set the combination of 'Name' and 'Size' as
the primary key. For this first we have to DROP the already existing primary key (i.e.,
Code) and then add the new primary key (i.e., Name and Size). The corresponding
statements are as follows:
ALTER TABLE Shoes DROP PRIMARY KEY;
After this statement, there is no primary key of Shoe table. Now we can add the new
primary key as follows:
ALTER TABLE Shoe ADD PRIMARY KEY (Name, Size);
300
MORE ON DATABASES AND SQL
Now if we see the table structure by DESC Shoes; statement, it will be shown as follows:
+--------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| Code | CHAR(4) | NO | | NULL | |
| Name | VARCHAR(20) | NO | PRI | | |
| type | VARCHAR(10) | YES | | NULL | |
| size | INT(2) | NO | PRI | 0 | |
| cost | DECIMAL(6,2) | YES | | NULL | |
| margin | DECIMAL(4,2) | YES | | NULL | |
| Qty | INT(4) | YES | | NULL | |
+--------+--------------+------+-----+---------+-------+
In MySQL, it is not possible to add or drop NOT NULL constraint explicitly after the table
creation. But it can be done using MODIFY clause of ALTER TABLE command. As an
example, suppose we don't want to accept NULL values in bill_date column of bills table,
we can issue the statement:
ALTER TABLE bills MODIFY bill_date DATE NOT NULL;
Later on if we wish to change this status again, we can do so by entering the command:
ALTER TABLE bills MODIFY bill_date DATE NULL;
Following are some self explanatory examples of SQL statemenets to remove columns
from tables:
ALTER TABLE Shoes DROP Qty;
301
MORE ON DATABASES AND SQL
Although any column of a table can be removed, MySQL puts the restriction that a primary
key column can be removed only if the remaining, primary key columns, if any, do not
contain any duplicate entry. This can be understood more clearly with the help of
following example:
The Name and Size columns of the Shoe table constitute its primary key. Now if we drop
the Name column from the table, Size will be the remaining Primary Key column of the
table. Therefore, duplicate entries in the Size column should not be allowed. To ensure
this, before removing Name column from the table, MySQL checks that there are no
duplicate entries present in the Size column of the table. If there are any, then the
statement trying to remove Name column from the table will result in an error and the
Name column will not be removed. If there are no duplicate enteries in the Size column,
then Name column will be removed. Similar will be the case with the Name column, if we
try to remove Size column. But there won't be any problem if we try to remove both the
primary key columns simultaneously with one ALTER TABLE statement as follows:
ALTER TABLE Shoes DROP name, DROP size;
ALTER TABLE can also be used to change the data type of a table column. For this the
syntax is as follows:
ALTER TABLE <tablename> MODIFY <col_name> <new datatype>
[,MODIFY <col_name> <new datatype>
[,MODIFY <col_name> <new data type> [, . . . ]]];
changes the data type of column Code to CHAR(5) and that of type to VARCHAR(20).
When we give a statement to chage the data type of a column, MySQL executes that
statement correctly only if the change in data type does not lead to any data loss. E.g., if
we try to change the data type of order_date column of orders table from date to int,
we'll get an error. This is because the data already stored in this column cannot be
converted into int type. Similarly, if a column of VARCHAR(10) type conatins some data
value which is 10 characters long, then the data type of this column cannot be converted
to VARCHAR(n), where n is an integer less than 10.
302
MORE ON DATABASES AND SQL
DROP TABLE
Sometimes there is a requirement to remove a table from the database. In such cases we
don't want merely to delete the data from the table, but we want to delete the table
itself. DROP TABLE command is used for this purpose. The syntax of DROP TABLE command
is as follows:
DROP TABLE <tablename>;
e.g. to remove the table Orders from the database we enter the statement:
DROP TABLE Orders;
And after this statement orders table is no longer available in the database. It has been
removed.
Summary
• Aggregate or Group functions: MySQL provides Aggregate or Group functions
which work on a number of values of a column/expression and return a single
value as the result. Some of the most frequently used. Aggregate functions in
MySQL are : MIN(), MAX(), AVG(), SUM(), COUNT().
• Data Types in aggregate functions: MIN(), MAX(), and COUNT() work on any
type of values - Numeric, Date, or String. AVG(), and SUM() work on only
Numeric values (INT and DECIMAL).
303
MORE ON DATABASES AND SQL
• Cartesian Product (or Cross Join): Cartesian product of two tables is a table
obtained by pairing each row of one table with each row of the other. A
cartesian product of two tables contains all the columns of both the tables.
• Equi-Join: An equi join of two tables is obtained by putting an equality
condition on the Cartesian product of two tables. This equality condition is put
on the common column of the tables. This common column is, generally,
primary key of one table and foreign key of the other.
• Foreign Key: It is a column of a table which is the primary key of another table
in the same database. It is used to enforce referential integrity of the data.
• Referential Integrity: The property of a relational database which ensures
that no entry in a foreign key column of a table can be made unless it matches a
primary key value in the corresponding column of the related table.
• Union: Union is an operation of combining the output of two SELECT
statements.
• Constraints: These are the rules which are applied on the columns of tables to
ensure data integrity and consistency.
• ALTER TABLE: ALTER TABLE command can be used to Add, Remove, and Modify
columns of a table. It can also be used to Add and Remove constraints.
• DROP TABLE: DROP TABLE command is used to delete tables.
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. Which of the following will give the same answer irrespective of the NULL values in
the specified column:
a. MIN() b. MAX()
c. SUM() d. None of the above
2. An aggregate function:
a. Takes a column name as its arguments
b. May take an expression as its argument
304
MORE ON DATABASES AND SQL
a. Foreign key with Primary key b. Each row with all other rows
7. Referential integrity
a. Must be maintained
b. Cannot be maintained
305
MORE ON DATABASES AND SQL
1. Why are aggregate functions called so? Name some aggregate functions.
2. Why is it not allowed to give String and Date type arguments for SUM() and AVG()
functions? Can we give these type of arguments for other functions?
6. What is the difference between HAVING and WHERE clauses? Explain with the help of
an example.
8. There are two table T1 and T2 in a database. Cardinality and degree of T1 are 3 and 8
respectively. Cardinality and degree of T2 are 4 and 5 respectively. What will be the
degree and Cardinality of their Cartesian product?
306
MORE ON DATABASES AND SQL
10. What are constraints? Are constraints useful or are they hinderance to effective
management of databases?
11. In a database there is a table Cabinet. The data entry operator is not able to put
NULL in a column of Cabinet? What may be the possible reason(s)?
12. In a database there is a table Cabinet. The data entry operator is not able to put
duplicate values in a column of Cabinet? What may be the possible reason(s)?
14. There is a table T1 with combination of columns C1, C2, and C3 as its primary key? Is
it possible to enter:
15. At the time of creation of table X, the data base administrator specified Y as the
Primary key. Later on he realized that instead of Y, the combination of column P and
Q should have been the primary key of the table. Based on this scenario, answer the
following questions:
b. What statement(s) should be entered to change the primary key as per the
requirement.
16. Does MySQL allow to change the primary key in all cases? If there is some special
case, please mention.
17. What are the differences between DELETE and DROP commands of SQL?
307
MORE ON DATABASES AND SQL
LAB EXERCISES
STUDENTS
+-------+----------------+-------+------+------+------------------------+------------------+
| AdmNo | Name | Class | Sec | RNo | Address | Phone |
+-------+----------------+-------+------+------+------------------------+------------------+
| 1271 | Utkarsh Madaan | 12 | C | 1 | C-32, Punjabi Bagh | 4356154 |
| 1324 | Naresh Sharma | 10 | A | 1 | 31, Mohan Nagar | 435654 |
| 1325 | Md. Yusuf | 10 | A | 2 | 12/21, Chand Nagar | 145654 |
| 1328 | Sumedha | 10 | B | 23 | 59, Moti Nagar | 4135654 |
| 1364 | Subya Akhtar | 11 | B | 13 | 12, Janak Puri | NULL |
| 1434 | Varuna | 12 | B | 21 | 69, Rohini | NULL |
| 1461 | David DSouza | 11 | B | 1 | D-34, Model Town | 243554, 98787665 |
| 2324 | Satinder Singh | 12 | C | 1 | 1/2, Gulmohar Park | 143654 |
| 2328 | Peter Jones | 10 | A | 18 | 21/32B, Vishal Enclave | 24356154 |
| 2371 | Mohini Mehta | 11 | C | 12 | 37, Raja Garden | 435654, 6765787 |
+-------+----------------+-------+------+------+------------------------+------------------+
SPORTS
+-------+-------------+-------------+-------+
| AdmNo | Game | CoachName | Grade |
+-------+-------------+-------------+-------+
| 1324 | Cricket | Narendra |A |
| 1364 | Volleball | M.P. Singh |A |
| 1271 | Volleball | M.P. Singh |B |
| 1434 | Basket Ball | I. Malhotra | B |
| 1461 | Cricket | Narendra |B |
| 2328 | Basket Ball | I. Malhotra | A |
| 2371 | Basket Ball | I. Malhotra | A |
| 1271 | Basket Ball | I. Malhotra | A |
| 1434 | Cricket | Narendra |A |
| 2328 | Cricket | Narendra |B |
| 1364 | Basket Ball | I. Malhotra | B |
+-------+-------------+-------------+-------+
a) Based on these tables write SQL statements for the following queries:
i. Display the lowest and the highest classes from the table STUDENTS.
ii. Display the number of students in each class from the table STUDENTS.
308
MORE ON DATABASES AND SQL
v. Display the Admission number, name, class, section, and roll number of the
students whose grade in Sports table is 'A'.
vi. Display the name and phone number of the students of class 12 who are play
some game.
viii. Display the names and phone numbers of the students whose grade is 'A' and
whose coach is Narendra.
b) Identify the Foreign Keys (if any) of these tables. Justify your choices.
c) Predict the the output of each of the following SQL statements, and then verify the
output by actually entering these statements:
ITEMS
+--------+--------------+--------------+------+
| I_Code | Name | Category | Rate |
+--------+--------------+--------------+------+
| 1001 | Masala Dosa | South Indian | 60 |
| 1002 | Vada Sambhar | South Indian | 40 |
| 1003 | Idli Sambhar | South Indian | 40 |
| 2001 | Chow Mein | Chinese | 80 |
| 2002 | Dimsum | Chinese | 60 |
| 2003 | Soup | Chinese | 50 |
| 3001 | Pizza | Italian | 240 |
| 3002 | Pasta | Italian | 125 |
+--------+--------------+--------------+------+
309
MORE ON DATABASES AND SQL
BILLS
+--------+------------+--------+-----+
| BillNo | Date | I_Code | qty |
+--------+------------+--------+-----+
| 1 | 2010-04-01 | 1002 | 2 |
| 1 | 2010-04-01 | 3001 | 1 |
| 2 | 2010-04-01 | 1001 | 3 |
| 2 | 2010-04-01 | 1002 | 1 |
| 2 | 2010-04-01 | 2003 | 2 |
| 3 | 2010-04-02 | 2002 | 1 |
| 4 | 2010-04-02 | 2002 | 4 |
| 4 | 2010-04-02 | 2003 | 2 |
| 5 | 2010-04-03 | 2003 | 2 |
| 5 | 2010-04-03 | 3001 | 1 |
| 5 | 2010-04-03 | 3002 | 3 |
+--------+------------+--------+-----+
a) Based on these tables write SQL statements for the following queries:
i. Display the average rate of a South Indian item.
ii. Display the number of items in each category.
iii. Display the total quantity sold for each item.
iv. Display total quanity of each item sold but don't display this data for the
items whose total quantity sold is less than 3.
v. Display the details of bill records along with Name of each corresponding
item.
vi. Display the details of the bill records for which the item is 'Dosa'.
vii. Display the bill records for each Italian item sold.
viii. Display the total value of items sold for each bill.
b) Identify the Foreign Keys (if any) of these tables. Justify your answer.
c) Answer with justification (Think independently. More than one answers may be
correct. It all depends on your logical thinking):
i. Is it easy to remember the Category of item with a given item code? Do you
find any kind of pattern in the items code? What could be the item code of
another South Indian item?
310
MORE ON DATABASES AND SQL
ii. What can be the possible uses of Bills table? Can it be used for some
analysis purpose?
iii. Do you find any columns in these tables which can be NULL? Is there any
column which must not be NULL?
3. In a database create the following tables with suitable constraints :
VEHICLE
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| RegNo | char(10) | NO | PRI | | |
| RegDate | date | YES | | NULL | |
| Owner | varchar(30) | YES | | NULL | |
| Address | varchar(50) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
CHALLAN
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| Challan_No | int(11) | NO | PRI | 0 | |
| Ch_Date | date | YES | | NULL | |
| RegNo | char(10) | YES | | NULL | |
| Offence | int(3) | YES | | NULL | |
+------------+----------+------+-----+---------+-------+
OFFENCE
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| Offence_Code | int(3) | NO | PRI | 0 | |
| Off_desc | varchar(30) | YES | | NULL | |
| Challan_Amt | int(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
a) Based on these tables write SQL statements for the following queries:
i. Display the dates of first registration and last registration from the table
Vehicle.
311
MORE ON DATABASES AND SQL
iii. Display the total number of challans issued for each offence.
iv. Display the total number of vehicles for which the 3rd and 4th characters
of RegNo are '6C'.
v. Display the total value of challans issued for which the Off_Desc is 'Driving
without License'.
vi. Display details of the challans issued on '2010-04-03' along with Off_Desc
for each challan.
vii. Display the RegNo of all vehicles which have been challaned more than
once.
viii. Display details of each challan alongwith vehicle details, Off_desc, and
Challan_Amt.
b) Identify the Foreign Keys (if any) of these tables. Justify your choices.
c) Should any of these tables have some more column(s)? Think, discuss in peer
groups, and discuss with your teacher.
Table: Employee
312
MORE ON DATABASES AND SQL
Table: Department
a) Based on these tables write SQL statements for the following queries:
i. Display the details of all the employees who work in Sales department.
ii. Display the Salary, Zone, and Grade of all the employees whose HOD is
Nupur.
iii. Display the Name and Department Name of all the employees.
iv. Display the names of all the employees whose salary is not within the
specified range for the corresponding department.
v. Display the name of the department and the name of the corresponding
HOD for all the departments.
b) Identify the Foreign Keys (if any) of these tables. Justify your choices.
• The total sale amount of any specific time period (a specific day, or month, or
any period between two specific dates)
313
MORE ON DATABASES AND SQL
There may be a number of other reports which the shop owner may like to have.
The job of each team is to design a database for this purpose. Each team has to
specify:
2. To expand its business, XYZ Mall plans to go online. Anyone who shops at the Mall will
be given a membership number and Password which can be used for online shopping.
With this membership number and password, customers can place their orders
online. The mall will maintain the customers' data and orders' data. A person is put
on duty to keep constantly checking the Orders data. Whenever an order is received,
its processing has to start at the earliest possible.
The job of each team is to design a database for this purpose. Each team has to
specify:
314
A PTE
H
10
R
C
• Define a Transaction
• Describe reason why all the tasks in a transaction should be executed fully
or not at all.
• Commit a transaction.
Till now we have studied about various SQL statements manipulating data stored
in a MySQL database. We executed SQL statements without concern about
inconsistencies arising due to group of statements not being executed in entirety.
In this lesson, we will study the basic concepts of Transaction processing and how
MySQL ensures consistency of data when a group of statements is executed.
Puzzle 9
Vijaya has to withdraw ` 2500.00 from her account in the bank. She asked for m notes of
` 50.00 and n notes of ` 100.00. The cashier made a mistake and handed her m notes of
` 100.00 and n notes of ` 50.00. When she returned back home she realized that she got
` 500.00 less. How many notes of ` 50.00 and ` 100.00 did she ask for?
315
ADVANCED RDBMS CONCEPTS
Introduction
Raunak studies in Class XII. He is very helpful. During summer vacations, he helped his
aunt's son in his studies. His aunt was very pleased with him and gave him a cheque of
` 2000.00. Raunak knows that after presentation of the cheque to the bank, his aunt's
account will be reduced by ` 2000.00 and his account will be increased by ` 2000.00.
Raunak walked up to the bank to present the cheque.
Are Raunak's fears valid? Can you recollect something like this happening with you or with
your friends or relatives?
Raunak should not fear at all as the Bank's DBMS looks after these eventualities. DBMSs
ensure consistency (correctness) of data by managing Transactions.
Suppose Raunak's account number is 3246 and his aunt's account number is 5135. In order
to process the cheque presented by Raunak, the following two SQL commands need to be
executed on the database maintained by the bank:
316
ADVANCED RDBMS CONCEPTS
UPDATE Savings
UPDATE Savings
The above two Updates should both take place. If the first Update takes place and there is
a system failure, the first updation should be undone. Either both the updations should be
done and if it is not possible for both the updations to be done, then no updation should be
done.
What is a Transaction?
A Transaction is a unit of work that must be done in logical order and successfully as a
group or not done at all. Unit of work means that a Transaction consists of different tasks -
but together they are considered as one unit. Each transaction has a beginning and an
end. If anything goes wrong in between the execution of transaction, the entire
transaction (No matter to what extent has been done) should be cancelled. If it is
successful, then the entire transaction should be saved to the database.
A transaction is a unit of work that must be done in logical order and successfully as
a group or not done at all.
In Raunak's case, both the updation statements constitute a transaction. Both are
together treated as a single unit.
To understand how transactions are managed, let us study the following 3 statements of
SQL:
• COMMIT statement
• ROLLBACK statement
317
ADVANCED RDBMS CONCEPTS
COMMIT Statement :
The COMMIT statement is used to save all changes made to the database during the
transaction to the database.Commit statement is issued at a time when the transaction is
complete- all the changes have been successful and the changes should be saved to the
database. COMMIT ends the current transaction.
Or
COMMIT WORK;
In the following example, the table named savings has 2 rows. A transaction is started and
balance in Siddharth's account (with account number 1004) is increased by Rs. 2000.00
and the balance in Akriti's account (with account number 1006) is decreased by Rs.
2000.00. COMMIT statement makes the changes made by the transaction permanent.
318
ADVANCED RDBMS CONCEPTS
Example 1:
+------------+------------------+----------+
+------------+------------------+----------+
+------------+------------------+----------+
+------------+------------------+----------+
+------------+------------------+----------+
+------------+------------------+----------+
mysql> COMMIT;
319
ADVANCED RDBMS CONCEPTS
ROLLBACK Statement :
When a transaction is being executed, some type of error checking is usually performed
to check whether it is executing successfully or not. If not, the entire transaction is
undone using the ROLLBACK statement. The ROLLBACK statement cancels the entire
transaction i.e. It rolls the transaction to the beginning. It aborts any changes made
during the transaction and the state of database is returned to what it was before the
transaction began to execute and does not save any of the changes made to the database
during the transaction.
Or
ROLLBACK WORK;
If in Example 1 shown above ROLLBACK was used instead of COMMIT, the updation of
incrementing Siddharth's account by ` 2000.00 and decrementing Akriti's account by
` 2000 wouldn't have taken place. Let us now initiate a transaction, increase Akriti's
account by ` 3000.00, then Rollback the transaction and see what happens to the
updation done on Akriti's account.
320
ADVANCED RDBMS CONCEPTS
+------------+------------------+----------+
• After the ROLLBACK command is issued to the database, the database itself
starts a new transaction; though no explicit command of starting a transaction
like START TRANSACTION is issued.
Example 2:
Let us try out some more SQL statements on Savings table to understand transactions
well.
mysql> SELECT * FROM savings;
+------------+------------------+----------+
| account_no | name | balance |
+------------+------------------+----------+
| 1004 | Siddharth Sehgal | 84000.00 |
| 1006 | Akriti Malik | 92000.00 |
| 1008 | Chavi Mehra | 67000.00 |
| 1009 | Raunak Singh | 56000.00 |
+------------+------------------+----------+
321
ADVANCED RDBMS CONCEPTS
+------------+------------------+----------+
+------------+------------------+----------+
Inserting SavePoints :
The SAVEPOINT statement defines a marker in a transaction. These markers are useful in
rolling back a transaction till the marker.
We can add a savepoint anywhere in a transaction. When you roll back to that savepoint,
any changes made to the database after the savepoint are discarded, and any changes
made prior to the savepoint are saved. It is like semicomitting a transaction.
322
ADVANCED RDBMS CONCEPTS
Example :
SAVEPOINT Mark1;
In the above statement a marker (savepoint) with the name Mark1 is defined. It becomes
a bookmark in the transaction. Now we can write the following statement:
ROLLBACK TO SAVEPOINT Mark1;
Setting Autocommit :
By default, Autocommit mode is on in MySQL. It means that MySQL does a COMMIT after
every SQL statement that does not return an error. If it returns an error then either
Rollback or Commit happens depending on the type of error. If we do not want individual
statements of SQL to be automatically committed, we should set the autocommit mode
to off.
When Autocommit is off then we have to issue COMMIT statement explicitly to save
changes made to the database.
The following statement sets the autocommit mode to off. It also starts a new transaction
SET AUTOCOMMIT=0;
The following statement sets the autocommit mode to ON. It also commits and
terminates the current transaction.
SET AUTOCOMMIT=1;
323
ADVANCED RDBMS CONCEPTS
Example
+------------+------------------+----------+
+------------+------------------+----------+
+------------+------------------+----------+
+------------+------------------+----------+
Table does not
| 1004 | Siddharth Sehgal | 84000.00 | show Raunak
Singh's row.
| 1006 | Akriti Malik | 92000.00 |
+------------+------------------+----------+
324
ADVANCED RDBMS CONCEPTS
mysql> ROLLBACK;
Rollback cannot undo insertion of
mysql> SELECT * FROM Savings; Raunak's row.
+------------+------------------+----------+
+------------+------------------+----------+
+------------+------------------+----------+
If the autocommit mode has been set to off in a session and you end that session,
the autocommit mode is automatically set to on when you start a new session.
Example
325
ADVANCED RDBMS CONCEPTS
An implicit COMMIT takes place, even if AUTOCOMMIT is set OFF, on the database
when the user issues a Data Definition language command like CREATE TABLE,
ALTER TABLE etc .
Future Trends
Cloud Computing
A major shift is predicted in the IT industry in the way that software and services
are going to be delivered in future. In this regard, cloud computing is an emerging
area these days. It is the computing model where the infrastructure and the
applications are offered as a service over the Internet. Cloud computing takes
place out on someone else's network. Since the details of how it is set up or how it
works is hidden from the user, the term cloud is used. Cloud means a large network
that is away and is not in our control. Just about any database can be run in a cloud-
based infrastructure. Search the web and find out how RDBMSs like MySQL will be
significant in such a computing model.
Summary
326
ADVANCED RDBMS CONCEPTS
• When Auto Commit is Off then changes made to database are not committed
unless explicitly requested.
EXERCISES
MULTIPLE CHOICE QUESTIONS
a) Primary key
b) Database
c) Transaction
d) none of these
a) Equal to "-"
b) on
c) off
d) Equal to "%"
a) ROLLBACK
b) COMMIT
c) SAVEPOINT
d) ROLLBACK TO SAVEPOINT
a) disabled
b) enabled
327
ADVANCED RDBMS CONCEPTS
c) inactive
a) INSERT INTO
b) COMMIT
c) DELETE
d) SELECT
6. If Feroze deposits a cheque of Rs. 1200.00 in his account, which was given to him by
Ali, two tasks: decreasing of Rs. 1200.00 from Ali's account and increment of Rs.
1200.00 in Feroze's account are done. ________________ constitute(s) a
transaction.
a) First task
d) Second task.
8. ROLLBACK statement
d) Rolls back all the insertions of rows made during the current transaction.
328
ADVANCED RDBMS CONCEPTS
LAB EXERCISES
329
ADVANCED RDBMS CONCEPTS
+-------+--------------+----------+
+-------+--------------+----------+
Write the output that will be displayed by each SELECT statement as the SQL
statements given below are executed:
mysql> SELECT * FROM ITEM;
mysql> ROLLBACK;
Now verify the output by creating the table using MySQL and executing the above
statements.
330
ADVANCED RDBMS CONCEPTS
331
ADVANCED RDBMS CONCEPTS
present with each citizen. The card will hold a limited amount of information but will be
backed up by further information held in a database with the Government. Some
information will be visible on the card, some encoded on chip in the card and other
detailed information about each citizen will be present in tables in a database.
Think about the information that Government should have about each citizen and fill in
the blanks. To give you track, some blanks are already filled up.
• Name
• Date of Birth
• Photograph
• _____________
• _____________
• _____________
• _____________
• _______________
• Facial image
• Fingerprints
• _____________
• _____________
• _____________
• _____________
• _____________
332
ADVANCED RDBMS CONCEPTS
• Signature
• biometric information
• _____________
• _____________
• _____________
• _____________
• _____________
These days some people feel that everyone's DNA numeric profiles should also be
available in database. It would really help to combat crime. However, a lot of people are
worried about this idea; they think that it would have disadvantages.
Brainstorm and discuss the advantages and disadvantages of storing DNA profiles also
in the database.
333
A PTE
H
11
R
C
IT APPLICATIONS
Learning Objectives
In class 11, you have already learnt about broad categories of IT application as e-Gaming,
e-Business, e-Governance, e-Learning etc. e-Business involves applications dealing with
buying and selling of products and services. e-Governance involves applications which
are used by government agencies/organizations to provide better governance. e-
Learning involves applications which are developed to help learning of any concept/skill.
Similar applications are also possible in other sectors of economy and social service.
You must have used or seen others using many such applications several times. Whenever
you perform an activity online, like register for a new email account, apply for a Visa
while going abroad, reserve a seat on a flight/train, buy a book online - you are actually
using IT applications only. So, you can see how these applications save us time and efforts
in getting various jobs done. These applications have become an integral part of our
modern society.
334
IT APPLICATIONS
In this chapter let us learn about what goes into developing such applications. We shall
also take up a few examples for better understanding.
Front-End Interface
All IT applications process some data entered by the user. For example, when an
examinee has to see his result on the net, he has to enter his roll number. When a person
has to deposit his house tax online, he has to enter information about his house and his
credit/debit card using which the house tax has to be deposited. To place an order online
for some purchase, the buyer has to enter some information about himself and the item
to be purchased. Similarly for any IT application the user has to enter some data which
may be just a number or a lot of data like buyer's details. Every IT application provides
some sort of form using which users enter the data. This form is called the Front End
Interface (or just Front-End or Interface or user-interface) of the application.
To create a front-end various components, like those studied in Java GUI application
development, are used. Some of the most commonly used components are discussed
below.
TextField: TextField is used to get small textual information like Name, RollNo, email
address, quantity, etc. Disabled/Uneditable TextFields are also used to
display such information.
TextArea: TextArea is used to get long textual information which may span multiple
lines of text. E.g. to get Address, Complaint, Suggestion etc. Disabled/
Uneditable TextAreas are also used to display such information.
Radio Button: Radio buttons are used to get an option out of several mutually exclusive
(out of which only one can be selected) options. Examples of such options
are Gender (Male or Female or Other), Type of Credit Card (Master or Visa
or Other), Type of internet connection (DialUp or Braodband), etc.
CheckBox: Check boxes are used to get one or more options out of several given
options which are not mutually exclusive. These are the cases where
multiple options are given to the user and the user can select zero or more
out of the given options. Examples of such options are Hobbies (a user
may have zero or more hobbies), Magazines to subscribe for (a user may
subscribe to zero or more of the given magazines) etc.
335
IT APPLICATIONS
List: A list is used to get one or more options out of several given options
which may or may not be mutually exclusive. This may seem to be the
case where CheckBoxes are to be used, but the difference is in the
number of options available. If the number of options is small, then
CheckBoxes can be used. In case of large number of options, using
CheckBoxes may take up a lot of space on the form and it may also be
inconvenient for the user to select the desired options. In such cases
Lists are preferred over checkboxes. Examples of such cases are: To
select cities out of a given list of cities, to select magazines out of a
given list of magazines, etc.
ComboBox: A ComboBox is used to get an option out of several given options which
are mutually exclusive. This may seem to be the case where
RadioButtons are to be used, but the difference is in the number of
options available. If the number of options is small, then RadioButtons
can be used. In case of large number of options, using RadioButtons may
take up a lot of space on the form and it may also be inconvenient for the
user to select the desired option. In such cases ComboBoxes are
preferred over radio buttons. Examples of such cases are: To select a
city out of a given list of cities, to select a train out of a given list of
trains, etc.
When the options are mutually exclusive, then a List can also be used
instead of a ComboBox. It all depends on the space available on the form
(a ComboBox consumes less space as compared to a List) and the look of
the form (which the form designer has to decide).
Front-end interface is the face of any application. In most of the cases, the front-end
decides whether the application will be easily accepted or not. If the front-end is
convenient and unambiguous for the user, then the user will like to use it and hence the
application will be given positive reviews. If the front-end interface is inconvenient for
the user, then the user will not like to use the application. Therefore, front-end of an
336
IT APPLICATIONS
application must be user-friendly. Following are a few tips to make the front-end more
and more user friendly:
1. Consistency: Consistency in looks and operations plays a major role in front-end
design. If in one window the buttons are placed at the bottom, then in all the other
windows also they should be placed at the bottom. If double-clicking an item pops-
up a short-cut menu, then double-clicking any other item should pop-up the
relevant short-cut menu. Labels, color-scheme etc. should also be consistent
through-out the application. Consistency enables users to make an idea of how the
application works, and this idea leads to fast acceptance of the application.
2. Make it convenient for the user:
a) Place the most important items at the top-left position of the form. When a
user looks at a window, top-left is the first position where user attention goes.
So an item placed at top-left position has least chances of getting skipped.
b) Don't use such bright colors which put pressure on users' eyes. The colors which
look very fantastic are not necessarily convenient for the user when it comes to
entering data or viewing reports.
3. Help the user enter correct data in the first go: Ask for minimum textual data to be
entered by the user. If you have to ask for class and section, provide a list to choose
the class, provide radio buttons to choose the section. This way user has the options
only to enter the valid data. If you ask the user to enter the class and section in a
text box, then the user has all the options to enter the data and hence more chances
of entering invalid data.
4. Listen to all: Before creating the user interface, you should speak to the potential
users and get their ideas to decide the design of user interface. You should put a
limit there only. You must get the ideas but you are not bound to use these ideas. Use
your skill and commonsense to decide which of these should be incorporated and
which one should not be. The aim is to create a consistent, convenient, and logically
correct user interface.
5. Smooth shifting from one window to the next (or the previous): Make the
sequence of moving from one window to another exactly same as the flow of work
the application is made to do.
337
IT APPLICATIONS
Back-End Database
Front-End is just one part of an IT application. Any IT application usually stores a lot of
data in the form of a database which is not visible to the user. This database is used by the
application to give suitable responses to the user. This database is called Back-End
Database (or just Back-End or Database). For Example, the database of train reservation
system stores all the data about trains and passengers, the database of an online
shopping system stores the data of all the items available in the store, and so on. If the
front-end interface makes the user like or dislike the application in the first go, then the
back-end decides whether the user will keep liking the application or not. A good back-
end improves the speed of the application. A good back-end also ensures easy
modification of the application whenever required. Following are the features of a good
back-end database:
• It should use multiple tables for storing data to avoid data redundancy.
• Tables in the database should be created using constraints wherever
applicable.
• Keys (Primary and Foreign) of tables must be defined.
To make the application efficient and effective, you should also follow the guidelines
given below:
1. It should meet all the requirements of the problem, for which the application was
created.
2. It should have user-friendly interface to make the user comfortable while using.
3. Code should have sufficient number of comments to help the programmer/yourself
to modify/update the code in future.
4. Keep the navigation of input in a standard order as much as possible. Most significant
information should be entered first.
5. There should not be any ambiguity in data and information and it should avoid
inputting duplicate information anywhere in any form.
338
IT APPLICATIONS
and whatever relevant data is extracted from the database is to be shown to the user
through the Front-End. Therefore, the Front-End and the Database of an IT application
must be connected. This connectivity is achieved as learnt in Chapter 6 (Database
Connectivity). If the application is web based then the connectivity is achieved using
some scripting language (like vbScript or JavaScript).
Examples of IT Applications
There are numerous IT applications. We consider herein IT applications for
e-Governance, e-Business, and e-Learning. Web addresses of a few of these are given
below:
e-Governance:
To reach the citizens in an effective and transparent manner ICT enabled counters have
been setup by government where several services like Birth/Death certificate
registration, Railway enquiry and ticket booking, submission of RTI application etc. are
provided. These centres are accessible to anyone and people can use these to get
guidance, information, and services without paying any money to touts or middle men.
1. india.gov.in ( The National Portal of India) - This portal not only gives the
information about Government of India, but also allows the users to apply online for
various services provided by the government.
339
IT APPLICATIONS
a) mcchandigarh.gov.in:
b) Jammukashnir.nic.in:
Know More!
Bhoomi (meaning land) is the project of on-line delivery and management of land
records in Karnataka. It provides transparency in land records management with
better citizen services and takes discretion away from civil servants at operating
levels.
Know More!
340
IT APPLICATIONS
e-Business:
To reach the customers and business associates in an effective and fast manner business
houses (now a days many small shops like snacks corners and paan shops also) provide
their services on the net. These ICT enabled counters are used to get orders and
feedbacks from the customers and also for inter-business transactions. This helps the
businesses to widen their customer base.
1. nafed-india.com/ebusiness.asp (e-business site of NAFED) - Through this URL
NAFD (National Agricultural Cooperative Marketing Federation of India Ltd.) offers
its e-business services to various corporates and customers.
2. Amazon.com ( e-Business site of Amazon.com) - Amazon is the world's largest
online store. Through this URL Amazon does its online business
341
IT APPLICATIONS
e-Learning :
e-Learning has multiple goals. It is much more than having a net connection and/or CDs
through which people learn. E-Learning is about giving freedom to people to learn
whatever they want to learn and whenever they want to learn. This is irrespective of
(except in exceptional cases) age, caste, gender, economical background, or
qualification of the learner. The only requirement is the will to learn. E-learning is
available on almost all the topics imaginable.
342
IT APPLICATIONS
343
IT APPLICATIONS
344
IT APPLICATIONS
Know More!
NIC has developed guidelines for Indian Government websites. These guidelines are
accessible at http://www.pon.nic.in/homeinfo/govt-website-guidelines.pdf.
Article 5.7 of this document lays guidelines for Multilingual versions of Government
websites. The main points of this article are:
a) Ideally all the pages on the website should be translated in Hindi and other
regional languages. In case it becomes difficult to do so, corresponding
Departments should identify the content which is widely accessed by the
public and put up such content in regional languages.
Development of IT applications
After going through these various IT Application sites, you must have realied that all these
applications simplify the processes. Now, let us find out how these applications are
created.
For developing such application, one needs to follow the following steps:
Step 1: Identify the problem for which the application is to be developed and discuss
about its feasibility. If the applications is technically and economically
feasible (possible and profitable to carry out), then steps are taken for its
development, otherwise the project is scrapped.
345
IT APPLICATIONS
Step 2: Identify and decide, which database tables and table structures will be
required in the application. Make sure that the data types and sizes of the
columns in the tables are carefully planned and used. Create database and
tables as per the requirement of the application.
Step 3: Identify and decide, which all inputs are required to be taken from the user in
the Front-End of the application. Find out, where you can minimize the typing
efforts of user by introducing known options using RadioButton/CheckBox/
List/ComboBox etc. Develop the front-end of the application as per the
requirement and ease of use.
Step 4: Establish the data connectivity between the Front-End interface and Back-End
Database.
Step 5: Test the full application (Front-End and Back-End) with multiple sample sets of
data. It is always better if the sample data are collected from potential users of
the application randomly.
Examples: We shall take 3 examples, one from each of the categories: e-Business, e-
Governance, and e-Learning, to better understand the process of IT application
development.
Example 1 - e-Business :
Let us see how can we develop the application which we described as 2nd Team based
exercise in chapter 9. To recall it, it is reproduced below:
To expand its business, XYZ Mall plans to go online. Anyone who shops at the Mall will be
given a membership number and Password which can be used for online shopping. With
this membership number and password, customers can place their orders online. The
mall will maintain the customers' data and orders' data. A person is put on duty to keep
constantly checking the Orders data. Whenever an order is received, its processing has to
start at the earliest possible.
The Orders' data will be analysed periodically (monthly, quarterly, annually - whatever
is suitable) to further improve business and customer satisfaction.
346
IT APPLICATIONS
Step 1: The problem is identified. Its economic and technical feasibility are discussed.
It is found that the application development and implementation are
technically and economically feasible. So the management gives a green signal
for application development.
Step 2: After discussing with the management and the potential users of the
application, it is decided to create the following tables in the database:
Table: Customers
2. Password Varchar(15) -
Table: Items
347
IT APPLICATIONS
Table: Orders
S.No. Field Datatype Remarks
1. Ord_number Int(5) Order Number.
2. membership_number Int(9) Membership number of the customer
who has placed this order.
3. Ord_date Date Date of order placement.
4. Item_Code Int(5) Code of the item ordered.
5. Qty Decimal(5,1) Quantity of the item ordered.
6. Status Varchar(10) Current status of this item. Status
can be:
Waiting/Completed/Cancelled.
Step 3: After careful analysis, it is found that the inputs required from the user are as
follows:
• Membership_number
• Password
• Item_codes of the items to be ordered
• Quantities of the items ordered
All the other fields like order_number, item_name, Order_date, Discount etc.
will be auto-generated/calculated by the application.
To get input from customers, following front-end interface can be designed:
Text Box
Labels
Password Field
Command Buttons
348
IT APPLICATIONS
Table
Step 4: Data connectivity between the Front-end interface and back-end database is
established using some scripting language like Javascript or VBScript etc.
If any discrepancies are found during test, the corresponding corrections are
made in the application. After complete testing, the application is
implemented and the customers are given membership numbers and
passwords.
Example 2 - e-Governance :
The state administration wants to make vehicles' data (RegNo, RegDate, Owner,
OwnerShipNumber, Address, HP) easily available to citizens. Each registration authority
in-charge will regularly update the data. Citizens will be given read only access to this
data.
349
IT APPLICATIONS
Step 1: The problem is identified. Its economic and technical feasibility are discussed.
It is found that the application development and implementation are
technically and economically feasible. So the corresponding authority (may be
the State Transport Authority) gives a green signal for application
development.
Step 2: After discussion with the management and the potential users of the
application, it is decided to keep the following tables in the database:
Table: Vehicle
Table: Owner
350
IT APPLICATIONS
Step 3: After careful analysis, it is found that the inputs required from the user are as
follows:
• Registration Number
All the other fields like Owner's Name and Address, HP etc. will be provided by
the application from the database.
To get input from the users, following front-end interface can be designed:
Once the registration number is input, database can be searched for it and the
corresponding details of the vehicle and the owner can be shown to the user in the
following format:
351
IT APPLICATIONS
Step 4: Data connectivity between the Front-end interface and back-end database can
be established using some scripting language like Javascript or VBScript etc.
If any discrepancies are found during test, the corresponding corrections can
be made in the application. After complete testing, the application can be
implemented.
Example 3 - e-Learning :
An organization of dedicated teachers, 'Meticulous Teachers Consortium', decides to
invite computer aided teaching modules from individuals and organizations so that these
can be put on the internet for students' use free of cost. No money will be charged from
users and no money will be paid to the developers. Once the modules start pouring in, a
front-end is created for the students where the students can select any of the available
modules to learn any topic.
352
IT APPLICATIONS
Step 1: The aim is identified. Its economic and technical feasibility are discussed. It is
found that the application development and implementation are technically
and economically feasible. So it is decided to go ahead with the application
development.
Step 2: To keep track of various modules contributed and used, the following database
is created:
Table: Modules
Step 3: After careful analysis, it is found that the inputs required from the user are as
follows:
If a user has already viewed a module and he again wants to view the same
module which he remembers by its module number, then the only input
required is:
353
IT APPLICATIONS
• Module Number
If a user wants to see a module for the first time or he does not remember the
module number, then the input required is as follows:
Step 5: After development the application can be tested by selecting various modules
and running them.
If any discrepancies are found during test, the corresponding corrections can
be made in the application. After complete testing, the application can be
implemented.
354
IT APPLICATIONS
• Social networking sites help like minded people come together and work for
some cause.
• Due to e-Banking and use of plastic money more money is put in circulation
leading to faster growth of GDP.
• e-Learning sites make quality study material available even to the students
staying at remote places.
Infomania:
Infomania is the condition of reduced concentration caused by continually responding to
electronic communications such as e-mail, SMSs, MMSs etc. ICT is making more and more
people infomaniac. This is making some people waste their productive time in the office,
neglect their families and duties. Some people are also in a habit of frequently checking
their e-mails even when they are on vacation with their families. We have to be careful in
the use of ICT so that we use it constructively and not get obsessed with it and become
infomaniacs.
355
IT APPLICATIONS
Summary
• An IT application has two major parts: Front-end (The user interface) and
back-end (The database)
• Use of ICT has its social and economic impacts. Society is impacted as due to
ICT people change their way of conducting the transactions and thus save their
time, money, and energy. Economy is impacted as ICT leads to fast completion
of data transfer and data processing jobs. ICT also brings transparency in the
administration.
356
IT APPLICATIONS
EXERCISES
MULTIPLE CHOICE QUESTIONS
1. A web site to provide online information and services to the citizens is an example of
a. e-Business b. e-Mail
c. e-Governance d. e-Learning
2. The web-site of an electricity supply company which allows its customers to pay bills
online is an example of
a. e-Business b. e-Mail
c. e-Governance d. e-Learning
3. The web-site of a school which allows the students to go through various lessons in
their subjects is an example of
a. e-Business b. e-Mail
c. e-Governance d. e-Learning
a. India.gov.in b. GOI.gov.in
a. database b. front-end
c. back-end d. Javascript
6. A good front-end is
a. consistent b. user-friendly
357
IT APPLICATIONS
8. Javascript is a
a. e-Governance
b. e-Business
c. e-Learning
3. Give some examples of input values, where Radio Button and Check Boxes should be
used for efficiency in the application.
4. What are the important guidelines we should keep in mind while developing an
efficient application?
5. Is it a good practice to take in the inputs using TextFields only? Justify your answer.
Application forms for new water connection will be made available online. These
forms can be downloaded from the net, filled in, and submitted online only.
358
IT APPLICATIONS
It is responsibility of the zonal head to ensure that an application from his/her zone
is processed within a stipulated time period. Whenever a new connection is granted
or rejected, the ResponseDate, and Remarks columns of corresponding row are
updated by the respective zonal head. For this purpose, one of the tables of the
database is given below:
359
IT APPLICATIONS
The job of each team is to describe the remaining tables of the database and to suggest
the design of front-end.
2. Birth Certificate: Babu Lal lives in a small village. He is blessed with a girl at home
only. The village teacher visits his house and congratulates him. She tells him to
register the birth of his daughter with the government, and shares the benefits of
having the Birth Certificate. Birth certificate will help Babu Lal's daughter name
inclusion in ration card, at the time of admission to school, to avail facilities like
Ladli etc. The information base is used for forecasting and planning activities
related to healthcare, Welfare measures etc. in an effective way. Babu Lal is happy
and immediately goes to the centre for his daughter's Birth certificate generation.
3. DateOfBirth Date
5. PlaceOfBirth Varchar(30)
6. FatherName Varchar(30)
7. MotherName Varchar(30)
8. ResAddress Varchar(30)
9. IssuingAuthority Varchar(30)
360
IT APPLICATIONS
Name / u
k
e%
Gender / f
yax
%
Date of Birth / t
U
edh
rk
jh
[k
%
Time of Birth / t
U
edk
le;
%
Place of Birth/ t
U
eL
Fk
k
u%
Hospital Name/ v
L
i
rk
ydk
uk
e%
Delivery Type / i
zl
wf
rdk
izd
k
j%
Father's Name / f
i
rkd
ku
k
e%
Mother's Name / e
k
rk
dku
k
e%
Residential Address / ?
k
jdk
irk
%
Issuing Authority / t
k
j
hdj
u
so
k
ykv
f/
dk
j
h%
3. Sales Agency (B2B): A sales agency gets FMCG from manufacturers and sells these to
Whole sellers. For this the agency has a Suppliers table, a Goods table, and a
Customers table.
Customers can place their orders online. The details of orders accepted are placed
in an Orders table.
The Goods table is regularly updated. Orders table is checked twice a day for any
new orders.
The job of each team is to describe the attributes with data-types to be placed in
each table and and to suggest the design of front-end.
361
APPENDIX - I
The teacher should divide the class in teams of 3-4 students each and challenge teams to
solve the given puzzle. The teams that solve the puzzle within 3 minutes, 4 minutes, and
5 minutes are awarded the title of 'Fasttrack', 'Achiever', and 'Able' respectively.
Solution1
There are two different ways to place ten coins satisfying the given conditions.
Solution 2
We are giving you one possible solution but there are many other solutions
possible. So keep trying…..
2
6 8 5
4 1 3
362
APPENDIX-I
Solution3
Solution 4
As per the first two conditions that she has 3 children and the product of their
ages is 36(6 runs each in 6 balls = 6 x 6) the probable ages are:
The student knows her berth number but he is not able to reach the answer. That
means the sum must be same for two of the pairs. This reduces the chances to
two: { (2,2,9),(1,6,6) }.
From the third option, we get a constraint that, there is only one elder child. And
we reach the correct answer of (2,2,9)
Solution 5
First rounding (down) yields: 473816950 (as 2 rounds down to zero, 5 stays the
same)
2nd rounding (up) yields : 473817000 (5 rounds up to zero, add the carried
over one to 9 to get 0, add the carried
over one to 6 to get 7)
363
APPENDIX-I
At this point sum of all the not rounded digits is 2+8+3+7+4 =24
Solution 6
200X + 2Y = 100Y + X - 20
199X + 20 = 98Y
(199X + 20)/98 = Y
Now put this in the Y= function of a graphing calculator, set the table to start at 1
and go up by increments of 1 and then scroll down the table until you see an
integer pair.
Therefore, X = 26 and Y = 53
364
APPENDIX-I
Solution 7
2. Take 1 pill from jar 1, take 2 pills from jar 2, take 3 pills from jar 3, take 4
pills from jar 4 and take 5 pills from jar 5.
3. Put all of them on the scale at once and take the measurement.
4. Now, subtract the measurement from 150 ( 1*10 + 2*10 + 3*10 + 4*10 +
5*10)
5. The result will give you the jar number which has contaminated pill.
Solution 8
The numbers of the houses on each side will add up alike if the number of houses
be 1 and there are no other houses except David's house, or if David's house
number be 6 with 8 houses in all, or if David's house number be 35 with 49
houses, or if David's house number be 204 with 288 houses, and so on. But we
know that there are more than 30 and less than 50 houses, so we are limited to a
single case.
365
APPENDIX-I
Solution 9
Adding 1 and 2
150n = 3000
n = 20 ------------------------------------------------ 3
50 x 20 -50 m = 500
1000-50m = 500
-50m = -500
m = 10
Therefore Vijaya asked for 10 notes of Rs.50.00 and 20 notes of Rs. 100.00
366
APPENDIX - II
Indic Language Support
Mac OS 10.5 supports Devanagari, Gujarati, Gurmukhi and Tamil
Linux based desktops support Bengali, Devnagari, Gujarati, Kannada, Malayalam, Oriya,
Tamil, Telugu and Gurmukhi,
There are various Input Methods available in BOSS, GNU/Linux. In these operating
systems you can select the language of your choice in which you want to create your
document. For example to choose Hindi:
Within each language there are multiple keyboard layout options are available. You can
choose keyboard layout of your choice.
367
APPENDIX-II
For Windows XP, some additional setup may be required to support Indic languages.
Therefore you first follow the steps given under Enabling International Language Support
in Windows and then proceed with the steps given under the Enable a keyboard layout
section.
Step 2: Click on Date, Time, Language, and Regional Options and choose Add Other
Languages from the task list.
Step 3: In the Regional and Language Options dialog box Highlight the Languages tab.
Step 4: In the Regional and Language Options dialog box, under Supplemental
Language Support, select the Install files for complex script and right-to-left
languages check box. Click OK or Apply.
368
APPENDIX-II
369
APPENDIX-II
Step 6: Click the Regional Options tab. Click the Standards and formats list, and then
select your region.
Step 7: Click the Location list, and then select your location.
Step 8: Once done, click OK to exit. On the Text Services and Input Languages page,
click OK again to close Regional Options. You should now see a language
indicator in the System Tray (located at bottom right hand corner of the
desktop by default)
Turning on the language bar :
If you do not see the language bar in the task bar (at the bottom of the desktop) or floating
on the desktop please do the following:
Step 1: Click Start, click Control Panel, and then double-click Regional and Language
Options.
Step 2: On the Languages tab, under Text services and input languages, click Details as
shown in Figure 8.
Step 3: Under Preferences, click Language Bar.
370
APPENDIX-II
Step 4: Select the Show the Language bar on the desktop check box.
Note: You can switch between different languages by clicking on the language bar and
changing the language or by pressing the left ALT+SHIFT keys.
Step 1: Open the application in which you would like to enter Indic text.
Step 2: Change the language using the language bar, which typically appears in the
taskbar as follows.
371
APPENDIX-II
Step 3: The language bar will now show the current language.
Step 4: You can now start typing in English and whatever you type automatically gets
transliterated after a word-breaking character like a space, comma, etc. is
entered. Note that this language setting is per application. You may have to
repeat the steps above for each application you want to use Microsoft ILIT in.
The Microsoft indic input tool comes with a virtual keyboard that can be used to
type in notepad.
Note: You can switch between different languages by clicking on the language bar and
changing the language or by pressing the left ALT+SHIFT keys.
372
APPENDIX-II
Step 1: Go to Windows Fonts folder e.g. C:\Windows\Fonts. (The path may differ on
some computers.)
Step 2: Copy-paste the font file into this folder. Windows will now install the font file.
Step 3: Once installed the font will be available in your text-based applications.
Source:
1. http://www.microsoft.com/windowsxp/using/setup/winxp/
yourlanguage.mspx
2. http://office.microsoft.com/en-us/support/enable-keyboard-layouts-for-
different-languages-HA010354267.aspx
373