Xi It Part-B
Xi It Part-B
Introduction
In today’s world we can see that almost all our work is being done with the help of computers.
Applications of computers can be seen in every electrical device nowadays whether it is
television, washing machine, watches, mobile phones and the list is endless. With the
advancement in use and technology, use of electronic devices has increased manifold. All this is
possible because of the ease and accuracy we get with these devices. Life has taken a fast pace
and distances make hardly any difference with the help of these machines. Let us have an
insight to the basics of computers in this chapter.
Evolution of Computers
Growth of the computer industry started with the need for performing fast calculations. The
manual method of computing was slow and prone to errors. So attempts were made to develop
faster calculating devices. The journey that started from the first calculating device i.e. Abacus
has led us today to extremely high speed calculating devices.
Computer is a term derived from the term ‘compute’ which means to calculate. Computer takes
input from the user, processes it and displays output. It is a device that works on a set of
instructions. It takes input from the user, processes the input according to the set of
instructions and gives the output.
Computer is an electronic device and works on electronic signals. The on and off signals denote
1 and 0 respectively. The binary language, also called machine language, works on two digits 0
and 1. Earlier computer experts used to work and give instruction in binary language only. Over
the years, many user friendly languages similar to simple English terms have developed and
every computer programmer need not learn and give instructions in binary language. Many
user friendly languages have been developed like C, C++, Java, JavaScript, Python and many
more. These languages are known as high level languages. Commands given in high level
languages need to be converted into binary language with the help of translators.
All this is achieved by an effective coordination of the components of the computer; broadly
categorized as hardware and the software. The term hardware refers to the tangible
components of a computer that we can touch and feel like the keyboard, mouse, monitor.
However, the term software refers to a set of instructions and is intangible. Some examples of
software are operating systems, word processors, spreadsheets, online calculators etc.
The data and/or instructions given by the user to the machine are termed as Input and the
result generated by the machine after processing the data is the Output.
Characteristics of a Computer
Computer has become an inseparable part of our lives today because of following
characteristics:
Speed : A remarkable quality of computers is their ability to process data and instructions at a
very high speed. A typical high-speed computer can perform about 3-4 mips (million
instructions per second). Note that this is different from the speed with which information can
be sent to and from a computer, which is normally measured in baud.
Versatility: is the ability of a computer to do a variety of jobs with ease. One moment you can
type a letter using any of the available word processing packages, and the other moment you
can use the same machine to do calculations yielding the salaries of employees of an
organization.
Accuracy: Not only does the machine perform varied jobs with high speed, but also does them
with high precision and accuracy. Note that the errors that one may see in output produced by
the computer is not because of the machine, but because of either wrong entry of data or
wrong instructions given to compute. In computer terminology, this phenomena is often
referred to as GIGO (Garbage In Garbage Out)
Diligence: Another noteworthy feature of computers is its ability to perform the same task
repeatedly over and over again without getting bored! For example a task of adding 1000
numbers repeatedly for 10000 times if given to a computer, it would be able to do the task with
the same accuracy every time without complaining that it is being asked to do this job over and
over again!!!
Memory: One of the notable features of a computer is its memory. However, the computer’s
main memory is volatile, i.e., it is lost when we switch off the computer.
Therefore, computers are provided another form of memory that does not fade away when it is
switched off. It is called secondary memory and is available in the form of floppy disks, pen
drives, portable hard disks.
Storage: Huge amounts of data and information can be stored in a computer for future
retrieval. The human memory is limited and fades away with time, which is not true for a
computer.
Intelligence: In the early days, although computers possessed striking characteristics yet a
prominent drawback was that they are merely dumb machines which were programmed to
perform certain tasks. With the advent of artificial intelligence techniques, we now have
machines which can drive a car without a human driver or play chess against the best players.
Thus to summarize, this electronic device is capable of storing, processing huge amounts of
data and/or instructions with accuracy, diligence and high speed in an untiring manner.
Having seen the characteristics of a computer, now let us understand the way a computer
works.
Components of a Computer
The computer is the combination of hardware and software. Hardware are the physical
components of a computer like motherboard, memory devices, monitor, keyboard etc. while
software is the set of programs or instructions. Both hardware and software together make the
computer system function. Let us first have a look at the functional components of a computer.
Every task given to a computer follows an Input- Process- Output Cycle (IPO cycle). It needs
certain input, processes that input and produces the desired output. The input unit takes the
input, the central processing unit does the processing of data and the output unit produces the
output. The memory unit holds the data and instructions during the processing.
Let us discuss each component and its functionality :-
Input: To initiate the process, the computer needs to be told of the problem to be solved. For
this purpose, a set of instructions and data is provided through the input devices such as
keyboard and mouse. A set of instructions provided to the computer for doing a task is called a
program.
Storage: There are basically two types of computer storage devices:
Primary Memory : Data stored in Primary Memory is directly accessible by the CPU. The inputs
received in the above steps are stored in the computer memory, called random access memory
(RAM). This storage is relatively fast and expensive as compared to the secondary storage.
Primary memory is directly connected to the CPU.
It is also called main memory, primary memory, or working memory of the machine.
Primary memory is of two types :
1. RAM ( Random Access Memory) : It is a primary volatile memory i.e. its data gets lost
once the power supply is stopped.
RAM is of two types : DRAM (Dynamic Random Access Memory) and SRAM ( Static Random
Access Memory.
DRAM SRAM
Used in main memory It is used in cache
Inexpensive Expensive
Uses less power Uses more power
Slower than SRAM Faster than DRAM
All the inputs, the intermediate results of computation carried out, and the final result are
stored in the memory of the computer. The computer also has another form of memory called
secondary memory. The programs and data not currently required are stored in secondary
memory. It comes in the forms such as a hard disk, pen drive, and CDROM. When required, for
processing, these can be retrieved and transferred to the main memory of the computer,
Processing: The inputs provided by the user are processed by the central processing unit as per
the specified instructions. The result of the processing is then either directed to the output
devices or to a memory location for storage.
Control Unit: is responsible for coordination between the different units of a computer. It
controls the input, processing and output operations. For example, it coordinates with the
peripheral devices to accept the input or display the output. It is like a manager of all
operations.
The manner in which the program is to be executed is managed by the control unit of the
computer. This entails deciding the address from which the instructions to be executed is to be
picked up, the memory location where the data or intermediate result is to be stored, etc.
Arithmetic Logic Unit (ALU): is responsible for actual processing of data. It retrieves the data
from the storage unit and performs the arithmetic calculations and/or comparisons on them
and the processed data is then sent back to the storage.
Output: The result of processing carried out by the computer is often directed to the display
device such as the monitor or printer. Other forms of devices are not uncommon, for example,
the computer may output music or video.
We have seen above that the input unit receives data, which is stored in the main memory,
from where it gets transferred to the Central Processing Unit and subsequently to the output
device. The Central Processing Unit has two modules; the Arithmetic Logic Unit and the Control
Unit.
It also coordinates between memory and ALU by issuing timely signals. As mentioned above,
the storage unit has primary storage and secondary storage.
Random Access Memory (RAM): This memory storage plays an important role in the
functioning of a computer system. Every time you start up the computer, the operating system
(the system software that manages the device’s interaction with the peripherals and the
internal resources) is loaded in the RAM. The program that needs to be executed at any point of
time also needs to be brought in the RAM. These days the PCs have around 8-32 GB RAM. More
the RAM, more will be the space for the programs leading to faster execution. Of course,
everything in computers is subject to some limits.
It is usually characterized by the performance and its capacity. Memory capacity is specified in
terms of bytes. These days the capacity of a hard disk is expressed in terms of Gigabytes,
Terabytes.
Pen drive/Flash drives : it is a small pen-like storage device of and can be accessed by directly
inserting in the USB(Universal Serial Bus) Port. It is very popular these days because of its small
size and easy accessibility.
Let us look into the hierarchy of the terms used to specify the capacity.
Every bit of information in computer is stored in terms of Bits (Binary Digits) i.e. 0s and 1s
1 nibble = 4 bits
1 byte = 8 bits
1024 bytes = 1 Kilobyte (KB)
1024 KB = 1 Megabyte (MB)
1024 MB = 1 Gigabyte (GB)
1024 GB = 1 Terabyte (TB)
1024 TB = 1 Petabyte (PB)
1024 PB= 1 Exabyte(EB)
1024 EB = 1 Zettabyte(ZB)
1024 ZB = 1 Yottabyte (YB)
Optical Storage devices : Compact disc (CD) and Digital Video Disc(DVD) are examples of optical
storage devices. Capacity of a DVD is higher than that of a CD. Data in a Cd/DVD may be
accessed by inserting the disc in a Disc Drive. Following is the image of a CD/ DVD drive:
All these components need to work in coordination and this is accomplished by the operating
system. It initializes the system for our use. In the next section, we study the basics of operating
systems.
Self Assessment Exercises
1. Explain storage devices of a computer.
2. Describe secondary and primary storage devices of a computer
3. Write a short note on Optical storage devices
4. Explain the role of Power Supply Unit.
5. Explain various units to measure storage capacity of a device. Give the smallest unit.
6. Do the following conversions :
a. 2 GB = ___________KB
b. 210 MB = __________B
Operating System :
Operating system is the software that acts as an interface between user and computer
hardware. A computer needs to communicate with both the hardware and software; to do this;
it utilizes the services of an Operating system. Examples of some popular operating system are
Windows, Linux, Unix, MS-DOS, SOLARIS, MAC OS, Gary Arlen Kildall is known as the father of
operating system.
It also acts like a government which lays down policies for efficient utilization of the resources
and provides for effective coordination amongst the various components of a computer. Every
computer system whether it is an independent system like a desktop or a cell phone must have
an operating system for performing the core functionalities like accepting input from various
input devices, directing the output to the display, managing the files and directories,
communicating with hardware, and installing /uninstalling of peripheral devices.
Introduction
While working with a computer you are sure to come across some hardware, software and
networking problems. The objective of this chapter is to help you find a solution to some
commonly encountered problems. Having gone through this chapter you will be able to
diagnose and fix minor issues. You may need expert advice for advanced problems not covered
here. As you gain experience, you would be more confident to handle problems.
Some of these problems would not occur if you work carefully and ensure that connections are
in place and proper settings are done. There could be many reasons/ causes for a problem on a
computer. It is sometimes difficult to judge if it is a hardware-related or software-related
problem. Troubleshooting is generally a trial and error process, requiring persistence and
patience. Starting with the simplest possible cause, we use the process of elimination to
diagnose the problem. One needs to figure out the cause of the problem, i.e., identify the part
of the computer system that is not functioning well.
Always take a backup of your important files to another source, like a pen drive or an external
hard disk. In case the problem is not solved, this ensures that a copy of your data is available.
Common Troubleshooting Steps
When you switch on the system, the power supply detects the CPU and the peripherals (the
other connected devices). The system boots, and if all peripheral devices have been successfully
detected, most systems will produce a beep. If any connected device (such as monitor,
keyboard, mouse, and printer) does not switch on, try the following:
Close running programs that are not being currently used
Check the Cables: Check the cable of the specific computer hardware which is not working.
Ensure that all connections are tight, correctly plugged in, and the Power button of these
devices is ON. For wireless devices, make sure it is turned on and the batteries are charged.
For example, a laptop’s battery may not be charged. Plug the AC adapter into the electric
socket, wait a few minutes, and then try to turn on the laptop.
Repeat the Steps to See if the Problem Recurs: Repeat the sequence of steps that you performed
before the problem occurred. Observe if it causes the same response from your computer.
Use Help: Access the Help window by pressing the F1 key. This window helps to find a solution
to the problem.
Record Error Messages: Record the full error message for future reference.
Restart the Computer: Restart the peripheral device. If the device still does not switch on, shut
down the computer and start it again.
Step 3: Run the HP Print Assistant (as shown in Figure 1.11). This program manages the printer
and gives access to the Help information. The HP Print Assistant program may take some time
to open, as your PC/ laptop would try to establish a connection with the printer.
Suppose you wish to change the default printer to say, HP Laserjet 1020 (Printer B). Right click
on the icon for this printer, a pop-up menu is displayed (as shown in screen in Figure 1.15).
Select, Set as default printer from this pop-up menu. The screen will now look like the one
below (Figure 1.16). The tick next to the HP Laserjet 1020 icon shows that it is now the default
printer.
Figure 1.16: Default Printer Changed
Note: Changing the default printer to Printer B, as described above, is possible even if Printer B
is not connected to your network. Give a print job only if your system and Printer B are
connected via a network. You must ensure that Printer B is on your network and that your
system can establish a connection with it.
Choose an Alternate Printer for the Current Print Job.
When you give a print job, a Print screen opens, as shown in Figure 1.17. The Default Printer
(here HP Deskjet 3540) is automatically selected for the print job.
If you wish to change to an alternate printer for the current print job, click on one of the
available printer icons in the list. The next screen (Figure 1.18) shows HP Laserjet 1020 as the
printer selected for the current job. As you can see, printer HP Laserjet 1020 is offline (not
connected to your system via a network/ cable). The Print program allows you to select the
printer even when the printer is offline. Ensure that this printer is online (connected to your
system via a network/cable), before you click on the Print button and start the print job.
Printer is Slow
The printing speed can be improved by reducing the printing quality and using Fast Draft/ Fast
Printing. This works well for everyday printing. Change the default printer quality setting from
Normal to Fast Draft.
To do this, click the Preferences button (as seen on the screen in Figure 1.17 and 1.18).This will
open the Printing Preferences screen (Figure 1.19). Under the Printing Shortcuts Tab choose
Fast/ Economical Printing.
Sound Troubleshooting
When you are not getting sound from the speakers, troubleshoot using the suggestions given
below:
Check Speaker Volume
Check the volume level of the speakers. Click the Audio button in Task Bar to make sure the
sound is turned on and that the volume is up (Figure 1.20).
If you are still unable to connect to the internet, the troubleshooting application would report
the Problem in network connectivity. Figure 1.35 shows ‘Problem with wireless adapter or
access point’. Try Switching Off and then Switching On the adapter. If that still does not work,
repeat the whole process again after some time. Your network connectivity issue would
probably be solved after a few attempts.
Alternatively, in the bottom left corner of your Windows screen click Start. In the Search box
type Run and press Enter. This will open the Run application, which opens a program or
document that you request it to. Type CMD in the Open textbox and press Enter (Figure 1.36b).
The COMMAND PROMPT (an MS-DOS window) will open. Type IPCONFIG and press Enter. The
results should show the Connection-specific DNS Suffix, IP Address, etc., as seen in Figure 1.37.
This information will only show if your system is connected to the internet, else, it will show
Media State: Media disconnected.
Figure 1.37: IPCONFIG showing the system’s IP address in the COMMAND PROMPT WINDOW
- Computer is an electronic device that takes input from the user, processes it and
displays output.
- The on and off signals denote 1 and 0 respectively. The binary language, also called
machine language,
- Commands given in high level languages need to be converted into binary language with
the help of translators.
- Speed, accuracy, memory, diligence, versatility are some of the features of computer.
- Hardware are the physical components of a computer like motherboard, memory
devices, monitor, keyboard etc.
- Software is the set of programs or instructions.
- It is sometimes difficult to judge if the problem is hardware-related or software related.
Identify the part of the computer system that is not functioning properly.
- Before handing over your machine to an engineer, take a backup of important files to
another source, like a pen drive or an external hard disk. This would ensure a copy of
your data is available, in case something unforeseen happens while your computer is
being repaired.
- Most systems produce a beep when a system boots successfully (i.e. all peripheral
devices have been successfully detected). If any connected device does not switch on,
try the common troubleshooting tips: close running programs that are not being
currently used; check the cables; repeat to see if the problem recurs; use help; record
error messages and restart the computer.
- If the monitor is not showing any display or the screen is blank: the system could be in
sleep mode; check all the connections; the laptop’s battery may be low. If the keyboard
is not responding: check connections; check for any damage; try changing batteries in a
wireless keyboard; the keys may be stuck, replacing the keyboard.
- In case the mouse is not working: check connections; check for any damage and replace
the mouse if required; restart the cordless mouse; clean the mouse.
- The printer may not be responding because: it may not be connected properly or not
switched on; the printer could be out of paper; there could be a paper caught in the
printer; printer’s ink cartridge could be empty; an incorrect printer driver may be
configured.
- The printer and computer may not be communicating properly when a wireless
connection is being used to connect a PC/ laptop to a printer. The IP address configured
on your computer should match the Dynamic IP address allocated to the printer.
- When the print jobs are being sent to the wrong printer: change the default printer or
choose an alternate printer for the current print job.
- To improve the printing speed, reduce the printing quality by using Fast Draft/ Fast
Printing.
- When there is no sound from the speakers: check speaker volume; check audio player
controls; check the cables; check the sound using headphones.
- When an application is running slow, check for available updates.
- Sometimes an application may freeze. Forcefully end the application or restart the
computer.
- When all programs on the computer run slowly, check for viruses or try freeing space on
the hard disk.
- To free space on the hard drive: check minimum free disk space required; run a disk
cleanup application; delete unused files and programs; empty the recycle bin; remove
temporary files; run the disk defragmentation program; remove unused shortcuts and
program services.
- Force System Restart when the computer freezes.
- When the computer is unable to connect to the network: check the network
connectivity; check the validity of IP address; the network fly lead or network card may
not be working properly.
Exercises
1. List some common troubleshooting steps that you should keep in mind.
2. What steps would you take if the monitor is not showing any display, or the screen is blank?
3. What would you do when your keyboard or mouse is not responding/ working properly?
4. What troubleshooting step will you take when the printer is not responding?
5. How can you check the IP address of a printer connected through a wireless connection?
6. What steps do you need to take to change the default printer?
7. What could be the reasons for the print jobs being sent to the wrong printer?
8. What checks would you undertake when the speaker is not working?
9. What are the troubleshooting steps taken when an application freezes?
10. What could be the possible cause for all the applications to be running slow?
11. How can one free disk space on the computer?
12. How do we remove temporary files?
13. Why is disk defragmentation required? How can we achieve disk defragmentation?
14. What steps do we take to remove unused shortcuts and program services?
15. How can we check the network connectivity of your system?
16. Explain how you would check the validity of the IP address.
17. How will you check whether the network fly lead is working properly?
18. Describe the procedure to check whether the network card is working properly
Unit-2 Networking and Internet
In 1876 Bell came forward with the concept of communication through telephone lines leading to
development of Public Switched Telephone Network (PSTN) in 1877. It opened the new
frontiers allowing several homes to connect through telephone lines. From that time,
communication was mainly through telephone lines.
In the late 1950s, all the military communications started using telephone networks setting up
dedicated connections between the two parties. This dedicated connection made use of
technology called circuit switching. The connection consisted of several intermediary lines and
switching offices enroute. They were vulnerable to danger of damage to the switching offices
which may disrupt the entire network. At the peak of the cold war, the US Department of
Defense (DoD) realized the need to establish fault-tolerant networks that would not fail at the
time of nuclear war and could survive a single point failure in the network. Paul Baran along with
Donald Davies and Len Kleinrock came forward with the idea of digital packet switching in which
the message to be transmitted is divided into small chunks called packets. Unlike circuit
switching in which resources are reserved along the dedicated path of communication, packet
switching is based on link sharing.
The US Department of Defense realized the need to connect geographically separated research
computers together to form a network. This led to the development of Advanced Research
Projects Agency Network (ARPANET) in 1969. ARPANET made use of technology called digital
packet switching. Initially its use was restricted to non-commercial purposes such as military
and research. Subsequently, its use extended to education by supporting various educational
institutes.
Need for communication between various heterogeneous networks led to the development of
TCP/IP (Transmission Control Protocol/Internet Protocol) in 1970. Along with several smaller
networks, another large network called NSFNET was developed in 1984 by NSF, U.S. National
Science Foundation for research and education purposes. When ARPANET and NSFNET were
interconnected, the network growth increased tremendously. TCP/ IP protocol (rules for
communication) acted as a glue to connect various heterogeneous networks together into a
single network. This wide network is an Internet (network of networks).
The Internet is a global network that comprises many voluntarily interconnected networks. It
operates without a central governing body. The standardization of the core protocols (IPv4 and IPv6)
lis an activity of the Internet Engineering Task Force (IETF), To maintain interoperability, the
principal name spaces of the Internet are administered by the Internet Corporation for Assigned
Names and Numbers (ICANN). ICANN coordinates the assignment of unique identifiers for use on
the Internet, including domain names, Internet Protocol (IP) addresses and many other parameters.
Several government and private organizations, collectively called Internet Service Providers
(ISPs) joined hands to
Fig 2.1 one way communication channel
provide connectivity for the Internet. The Internet made it possible to exchange information and
communicate with remote nodes. Bandwidth describes the maximum data transfer rate of
a network or Internet connection.
Nodes or stations are electronic devices such as computers, printers, Fax machines, and
telephones which communicate with each other by sending and receiving data/message. Figure
2.1 depicts a one-way simple communication system that comprises the following components:
A transmission medium refers to the channel of transmission through which data can be
transmitted from one node to another in the form of signal. A signal encodes the data in a form
suitable for transmission on the medium. A medium is characterized by its bandwidth defining
the information carrying capacity of the medium. Common methods of Internet access by users
include dial-up with a computer modem via telephone circuits, broadband over coaxial cable,
fiber optics or copper wires, Wi-Fi, satellite, and cellular telephone technology (e.g. 3G, 4G).A
transmission medium may belong to one of the following two categories:
● Guided Medium: The term refers to physical conductors such as twisted pairs, coaxial
cable, and fiber optics. In twisted pair and coaxial cable, the signal travels as voltage
and current signal whereas in optical fibre, the signal is in the form of light.
● Unguided Medium: The unguided medium uses electro-magnetic waves that do not
require a physical conductor. Examples of unguided medium include microwave, radio
wave, infrared.
Creation of a network requires various network devices, each of which plays a specific role
in the network.
Repeater
With increase in distance, a signal may become weak and distorted. A repeater is used
to restore the input signal to its original form, so that it can travel a larger distance. Thus,
it is placed between two cable segments as shown in Figure 2.1.3 It is also known as
digital generator which reshapes and amplifies the digital signal.
.
Fig-Repeater 2.4
● Hub
Unlike a repeater which connects two cables, a hub connects several lines, also called, cable
segments. A hub comprises several input/output (I/O) ports, each of which connects to a
single cable as shown in Figure 2.4. Data arriving on an incoming line is output to all lines
except the line on which the hub receives the data.
● Bridge
A bridge is a multiport device used for connecting two or more local area networks (LAN),
possibly operating at different speeds as shown in Figure 2.5. Thus, a bridge may be used
to produce bigger LAN by combining smaller LANs. A bridge enables devices on one LAN
segment to communicate with the devices on another LAN segment. Unlike hubs, they
are intelligent devices which exercise discretion while forwarding data to the outgoing line
leading to the destination
Fig. 2.6 Bridge
● Switch
Unlike bridges which connect two or more LAN segments, switches are used to connect
individual nodes in the network with each other. Each node within network is connected to
a unique port in the switch as shown in Figure 2.6. On receiving the incoming data frame,
it forwards it to only a single line connecting to the destination node. All the nodes connected
through switch forms only one LAN.
● Router
Routers are used for connecting various networks (LAN or WAN) with each other as shown
in Figure 2.7. A router transmits data from incoming network to another network. A router
maintains a routing table of various networks. Based on the destination address, the router
determines to which network the incoming packet should be transmitted.
Fig 2.8 Router
● Gateway
A gateway connects networks based on different protocol technologies to communicate with
each other as shown in figure 2.8. Data coming from one network operating on one protocol is
converted according
to the protocol of the outgoing network, and then forwarded. Thus a gateway may be thought of
as a router equipped with software for protocol conversion.
On the basis of geographical span, network can be broadly categorized as PAN, LAN, MAN,
and WAN.
gateway
● MAN stands for Metropolitan Area Network. It may be owned by a single organization
or by many individuals or organizations. These networks are used to establish links within a city,
and span an area of radius up to 50 Km. MANs facilitate sharing of resources by connecting
various local area networks (Figure 2.10). For example, a cable television network within a city.
● WAN stands for Wide Area Network. Typically a WAN spans a segment of about
1000 Km. They are used for long distance communication and are well suited for connecting
remote areas. They establish links within a country or continent. A WAN may be owned and
manag ed by several organizations. It connects various local and metropolitan area networks.
Fig 2.13 WAN
2.1.6 Topology The arrangement (also called layout) of nodes in a network is called network
topology. There are broadly two types of topologies – broadcast and point to point.
In broadcast topology, all nodes share the same physical link. When one node transmits, all
nodes receive. collision may occur when more than one node simultaneously transmits, and
there is a collision resolution mechanism for handling it. Broadcast topologies are mainly bus
and ring. In point to point topology, every pair of nodes has a dedicated link. Popular point to
point topologies are star and mesh.
● Bus Topology
In bus topology, there is a long cable, called backbone cable (or simply backbone), that
connects various nodes through a connector called tap as shown in Figure 2.14. In this, a
message sent by one is received by all devices connected to backbone cable. This topology
requires less cabling and is easy to install and extend the network laid using it. however, fault
detection and isolation is difficult.
● Ring Topology
In ring topology, all the devices are attached through a cable in the form of ring as shown in
Figure 2.15.The message to be communicated is transmitted in one direction, thereby, relaying
the message to the intended recipient. addition and deletion of devices, and fault detection and
isolation is easy. However, the topology suffers from the limitation of single point failure leading
to disruption of the entire network. sending a message from one node to another node may take
more time (four steps while sending message from device a to e)
● Star Topology
In star topology, all the devices are connected to the central controller called hub as shown in
Figure 2.16. communication between any two devices takes place through the hub responsible
for relaying messages. star network can be easily installed and configured. Also, fault detection
and isolation is easy. However, it requires more cabling as compared to bus and ring topology.
also, hub failure will lead to network failure
● Mesh Topology
In mesh topology, every node is connected with every other node in the network as shown in
Figure 2.17 Because of dedicated point to point connection between every possible pair of
nodes, the topology provides secure data transfer without any traffic problem. it requires a large
number of connections to establish the topology. This leads to difficulty in installation as the
number of nodes grow as the network grows.
● MAC Address
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. 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. The MAC address of an NIC is permanent and does not
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
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.
For example, in the following MAC address,
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
To make it easier for us to remember, IP addresses are normally expressed in decimal format
as a "dotted decimal number" like the one above.
On a network, the 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!
An IP (Internet Protocol) address is a unique 4 digit hexadecimal number assigned to each node
on a network. IP address settings of a node can be changed by the user 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 whereas 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.
● Domain Name
So, whenever we have to communicate with a computer on internet, we can do so by using its
IP address. But it is practically impossible for a person to remember the IP addresses of all the
computers one may have to communicate with. Therefore, a system has been developed which
assigns names to some computers (web servers) and maintains a database of these names
and corresponding IP addresses. These names are called Domain Names. Examples of some
domain names are cbse.nic.in, sikkimipr.org, indianrailway.gov.in etc. Domain names are used
in URLs to identify particular Web servers. For example, in the URL
http://www.cbse.nic.in/welcome.htm, the domain name is www.cbse.nic.in.
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 , 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
Generic Domain Names:
·com - commercial business
·edu - Educational institutions
·gov - Government agencies
·mil - Military
·net - Network organizations
·org - Organizations (nonprofit)
.in - India
·au - Australia
·ca - Canada
.ch - China
.nz - New Zealand
.pk - Pakistan
.jp - Japan
.us - United States of America
● Domain Name Resolution is the process of getting the corresponding IP address from
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.
Digital literacy refers to raising knowledge and awareness about technology such as desktop
computers, smartphones, tablets, and other electronic gadgets. It also includes familiarity with
software tools and the Internet. This knowledge facilitates people to acquire, analyze, share, create,
and deliver information in an efficient and constructive way. Digital literacy also aids people in
several arenas such as education, social networking, e-commerce, healthcare, and tourism.
Especially in education, it provides learners with digitally enhanced learning through use of
technology. They can use technology to access Massive Open Online Courses (MOOCs) which are
providing opportunities to study irrespective of the boundaries of time and space. Moreover, Prime
Minister Narendra Modi has taken an initiative to makeIndia, a Digital India to use technology
proficiently and ethically. The campaign promotes building up of India-wide digital infrastructure to
provide government services digitally to people even in remote.
2.2.2 Internet Services
Network services are applications hosted by servers on a computer network, to provide some
functionality for users of the network. There are several applications of Internet such as e-mail, file
transfer, remote login, and World Wide Web (WWW).
The Internet protocol suite is a set of communications protocols used in the Internet and computer
networks. It is commonly known as TCP/IP because the foundational protocols in the suite are the
Transmission Control Protocol (TCP) and the Internet Protocol (IP).The simple task of sending the
data from one place to another through network requires several sub-tasks such as specifying
sender and receiver’s network and physical address, dividing the message into smaller fragments so
that they can be easily transmitted over Internet, taking appropriate measures for error and flow
control, and taking necessary action on receiving the message. These sub-tasks or functions are
Application layer:-Data/message is created at the sender’s end and at the receiving end
it is examined and processed . This layer is also responsible for enveloping the message to be
sent with the header. Several protocols such as HTTP(HyperText Transfer Protocol), POP3
(Post Office Protocol version 3)operate on this layer. POP3 allows you to download email
messages on your local computer and read them even when you are offline.
Transport layer:-Application layer passes the message to the Transport layer which appends
the information about the source and destination ports of the processes at two ends. Two end-
to-end protocols operate at this layer, namely TCP and UDP. TCP (Transmission Control
Protocol) is a reliable connection-oriented protocol needed when timely and error free delivery
of data is important. UDP (User Datagram Protocol) is an unreliable connectionless protocol for
short messages and client server request-reply messages, where immediate response is more
important rather than assured delivery. Transport protocol is used for streaming video. Further,
the transport layer divides the message into a number of fragments, called segments, each
segment will carry the sequence number denoting its relative position in the message, so that
the message can be assembled at the receiver end.
Internet Layer:-Transport layer hands over the segments to the Internet layer which adds
source and destination machine network address (also termed IP address). In the Internet layer,
Internet Protocol (IP) is used. IP defines the format of packets exchanged over the Internet.
Link layer is also called Host to Internet layer. This layer is responsible for adding the header
containing the sender and receiver physical address to the packet received from the Internet
layer.
2.3 CYBER THREATS AND CYBER SECURITY
2.3.1.1Malwares
The term malware refers to malicious software (programs) designed with the intention to affect the
normal functionality by causing harm to the system, or with the intention of getting unauthorized
access to the system or denying access to legitimate users of computing resources. A malware may
be a virus, worm, Trojan horse.
● Virus
A virus is a software code that may harm your system by overwriting or corrupting the system files. A
computer virus is similar in action to viruses in our body which replicate themselves and affect body
cells. The affected part is called the infected area. A computer virus may make several copies of it
by inserting its code onto the system programs, files or boot sector of hard drives and thereby may
corrupt them. This causes the system to slow down or even stop functioning like boot sector virus,
file infector virus, and macro virus.
● Worm
A worm is often received via network, and it automatically keeps on creating several copies of itself
on the hard disk thereby flooding the hard disk. When a worm is received as an email attachment, it
is automatically forwarded to the recipients leading to network congestion. Thus, a worm may crash
the system and entire network. No host application is required for worms to replicate themselves e.g.
Code Red Worm which makes more than 2,50,000 copies of itself in approximately 9 hours.
● Trojan Horse
Trojan Horse is a code that appears to be desirable and useful but ends up harming the system.
Trojan horse can attach itself with a safe application. For example, it may be attached to any game
downloaded over the Internet. Such an application when executed creates a backdoor in the system
through which a hacker can access the system. The hacker can monitor all the activity performed on
the system. He can also control the infected system by harming the data on the system. For
example, in the late 1990s, Trojan Horse named Sub7 was created which took advantage of security
flaws of earlier version browsers such as Internet Explorer and Chrome to illegally access the host
computer.
2.3.1.2 Eavesdropping
Eavesdropping is the act of secretly or stealthily listening to the private conversation or
communications of others without their consent. Eavesdropping is done through telephone lines,
cellular networks, email, and instant messaging.
A denial-of-service attack (DoS attack) is a cyber-attack in which the machine or network resource
becomes unavailable to its users by temporarily or indefinitely disrupting services. Denial of service
is typically accomplished by flooding the targeted machine or resource with superfluous requests to
overload systems and prevent requests from being fulfilled. ADoS attack is like a group of people
crowding the entry door of a shop, making it hard for legitimate customers to enter.
2.3.1.4Phishing
Phishing refers to the act of stealing a user's personal information through fraud mails. These emails
eit4er entail personal information through embedded forms or contain links to the web page that may
prompt you to provide this information. Information attempted to be stolen may include bank account
number, debit/credit card number, passwords or any other valuable data
Cybercrimes are the crimes related to the misuse of computers or the Internet such as theft, fraud,
and forgery. The IT act defines cybercrime as an unlawful act where in the computer is either a tool
or a target or both. Some of these crimes are mentioned below
Cyber bullying
Harassment or bullying inflicted through the use of electronic or communication devices such as
computer, mobile phone, laptop, etc.
Cyber stalking
Use of electronic communication by a person to follow a person or attempts to contact a person
to foster personal interaction repeatedly despite a clear indication of disinterest by such person.
Online Job Fraud
An attempt to defraud people who need employment by giving them a false hope/ promise of
better employment with higher wages.
Vishing
To seek personal information like Customer ID, Net Banking password, ATM PIN, OTP, Card
expiry date, CVV etc. through a phone call.
SMSing
Use of mobile phone text messages to lure victims into calling back on a fraudulent phone
number, visiting fraudulent websites or downloading malicious content via phone or web.
SIM Swap Scam
Getting a new SIM card against a registered mobile number
Credit card (or debit card) fraud
An unauthorized use of another's credit or debit card information for the purpose of purchases
or withdrawing funds from it.
Identity theft
Dishonestly making use of the electronic signature, password or any other unique identification
feature of any other person.
Spamming
Persuading a recipient to buy a product or service, or visit a website via email, SMS, MMS
where he can make purchases.
Ransomware
The victim is asked to pay the demanded ransom to get his device decrypts.
TCP/IP protocols may be secured with cryptographic methods and security protocol like Secure
Sockets Layer (SSL)
● Firewalls
A firewall aims at protecting the internal network of an organization, home, or individual from
malicious traffic from external networks. A router or a computer (often dedicated to serve as a
firewall) may be installed between external network and internal network for this purpose. Firewall
inspects the network traffic and allows only that data to pass through the network that does not
violate the security constraint. Hardware firewalls in the form of a router prevents malicious software
from entering your network from outside the network. However, software firewalls installed on
personal computers prevent unauthorized access or malwares from gaining access to personal
computers. Network firewalls may also encrypt the incoming data by converting it to non-readable
format, thus, adding further protection.
● Antivirus
Anti-virus is software that aims to protect your system against malicious and potentially unwanted
programs. It is responsible for detecting these malicious programs by searching for them, and removing
them to keep the system protected. The software operates by maintaining a database of malware
definitions, which are automatically updated. It searches for any malicious program by scanning the files
against the stored malware definitions for a match. In case of a match, they are declared as potentially
harmful, and are disabled and removed depending upon anti-virus software settings.
● Password managers
A password manager is a software application that helps a user store and organize passwords. Password
managers usually store passwords encrypted, requiring the user to create a master password; a single,
ideally very strong password which grants the user access to their entire password database from top to
bottom
● Cyber Law
Cyber laws are the laws for systematic use of e-resources, for example, e-business, and serve as a
measure against illegal cyber-crime. Various cyber laws have also been enacted to prevent cyber-
crimes and take action against those involved in such crimes. These laws define the action that
would be taken against people committing the offences. For cyber security, an amendment in IT Act
2000 named Information Technology Amendment Act,2008 was also introduced. The act also
defines offences and penalties for cyber-crime. Cyber police are responsible for detecting such
crimes and taking the necessary measure against it according to the IT Act.
● Never click on a suspicious link specified on a web page or send through a mail for which
you are not sure about its authenticity.
● Make sure that passwords are strong and are changed frequently. Passwords are the means
for authenticating users, thereby allowing access to networked systems. Weak passwords
have smaller length and use a small subset of possible characters, and thus, are subjected
to be cracked easily. One should also avoid setting obvious passwords such as names,
mobile numbers, or date of birth. Passwords should be strong, having long length and
including characters such as numbers and punctuation signs.
● Never disclose personal information such as date of birth, home address, personal phone
number, account details, passwords, credit and debit card details, work history details.
● Report phishing issues to the concerned authorities or at cybercrime.gov.in. In case of
unsolicited mails, mark them as spam mails.
● Security of the communication made over the Internet can be indicated by the security of
protocol being used. Secure Hypertext Transfer Protocol (HTTPs) is a secure version used
for communication between client and host on the Internet. So, ensure that all
communications are secure, especially online transactions. The security of the website can
be ensured if there is a padlock on the left side of the address bar. It indicates that the
website has a SSL (Secure Socket Layer) digital certificate issued by a trusted party which
ensures and proves the identity of the remote host.
● Ensure that the web browser being used for accessing the web is updated and is secure. For
example, chrome browser is up to date, if the security patch indicated by three dots on top
right corner are grey in color. Green, orange and red color security patches indicate that
browser update is available for two, four and seven days Respectively.
● Be selective while making friends on the social networking site. Do not send or accept
friendship requests from any unknown user. Also, trust the authenticity of a message only if
you are sure about its origin (sender).
● Do not post any offensive content on social networking site as it may lead to a criminalaction
against you.
● Beware before spreading any kind of a rumor as it may be treated as a cyber-crime.
● If someone is harassing or threatening you, take snapshot of it as a proof, and blockthe
person. Also, report the incident to the site administrator.
● Use updated antivirus and firewall, secure browsing, and password management techniques.
● Make sure that the website address is properly spelled. Because there may be two
websites with almost the same name, one being a phishing website.
● Delete cookies periodically. A cookie is a small piece of information about the client browsing
a website. On receiving a request from a client, the server records the client information such
as domain name and registration id on the server site in the form of a file or a string. The
server sends this cookie along with the response requested by the client. At the client side,
the browser stores this cookie received from the server in a directory called cookie directory.
By obtaining access to these cookies, hackers may gain unauthorized access to these
websites. Thus, cookies should be deleted occasionally along with the temporary files stored
on our system during web browsing.
Points to remember
7. Differentiate between firewall and antivirus. How both contribute to the security of
the system?
8. Define protocol.
12. List the various security issues concerned with using the Internet. Explain each of them
by giving proper examples.
13. List various protective measures that can be taken for network security.
Word Processing
3.1 Introduction
A word processing software is required for the creation of documents that are
text-based. It has tools that allow the user to edit, format and print document.
A word document may also contain pictures and tables. It may be a report,
letter, drawing, webpage etc.
OpenOffice Writer is popular open source software for word processing. It can
be downloaded from Internet and installed for free, on Linux-based machines
as well as Windows-based machines. In this chapter we discuss the usage of
OpenOffice Writer software in detail.
To start using the OpenOffice Writer software, any one of the following steps
needs to be performed -
<Start><Programs><OpenOffice>
If the OpenOffice icon (Figure 3.1) is on the desktop, double click the icon
shown in Figure 3.1.
Figure 3.1:
Tabs: (File, Edit, View, Insert, etc.) contain drop down menu which have
commands provided by the tab.
RulerBar: There are two rulers – Horizontal and Vertical. The Ruler Bar
allows us to adjust the indentation and margins.
StatusBar: It displays information about the current open document. It
displays the current page number, total pages in the document, zoom slider
etc.
ScrollBar: There are two scroll bars – horizontal and vertical. They help to
scroll the content or the body of document.
Workarea: It is the working area where the text of the document is typed.
The OpenOffice Writer has the following tabs: File, Edit, View, Insert, Format,
Tools, Modify and Window. There is also a help tab. On clicking any of the tabs, a
drop down menu appears which has several commands and options. Select the
command that you want to execute.
The key tasks that can be performed using the tabs are as follows
File: To apply commands to current document, to open or close document
Edit: For editing the current document, for example, cut, paste
View: For controlling display of document on the screen
Insert: For inserting new elements in document, like, comments, special
characters, graphics, and objects
Format: For formatting the layout and content of document
Tools: For spelling check, gallery of object art to add to document, to
configure menus
Table: To insert, edit, delete a table in a text document
Windows: For manipulating and displaying document windows
Some operations performed using the commands of the File tab are described as
follows –
(a)To create a new file. When you click <File><New>, a drop down
menu appears as shown in Figure 3.3.
(b) To create a document, select <Text Document>.
When you click <File Tab><Save As>, a Save As dialog box appears Figure 3.4.
You can –
Select folder (directory) where the file is to be saved,
Type the File name for the document,
Select ―save as type‖ of document (.odt etc.)
Click ―Save‖ button to save the file.
Figure 3.4: SaveAs option
To preview your document before printing: File -> Page Preview. You
can see how the printed page will look like after printing. You can see
multiple pages, full pages (use magnifying glass to zoom in and out). Click -
> Close Preview to go back to the document.
To Make Printer Setting: <File Printer Setting>. Make settings for the
printer.
To Print:<File><Print>: Print the document to the connected printer. You
can select the size of the paper, print multiple pages on a single sheet etc.
The Edit tab consists of commands required to perform editing on the current
document. It contains several commands as shown in Figure 3.5. The commands
which are required to be known at this stage are described in the figure. The
commonly used commands allow the user to – cut, copy, paste, find & replace,
undo and redo changes in the current document.
Figure 3.5: The Edit Tab
Some operations performed using the commands of the Edit tab are described as
follows:
Move Text: Remove the text to be moved by selecting the text and then
applying File -> Edit -> Cut. Then take the cursor to the place in document
where you want to move the text. Then do File -> Edit -> Paste.
Copy Text: Select the text to be copied and then apply the commands File -
> Edit -> Copy. Then take the cursor to the place in document where you
want the copied text. Then do File -> Edit ->Paste.
Find and Replace: This is used to find words and then replace it with the
new one (Figure 3.6). This option is useful to find word at multiple places in
the document and replace all of them with the new one.
Figure 3.6: Find and Replace dialog box
Some operations performed using the commands of the Edit tab are described as
follows -
Toolbars: Select <View><Toolbars>. A drop down menu appears, as shown
in Figure 3.8. Select the toolbars that you want to be displayed on the screen.
A displayed toolbar shows the icons for the commands, as shown in Figure
3.8.
Generally, Standard and Formatting options of toolbars are always selected.
When using an Insert tab to insert an element, the insertion of element in the
document happens at the location where the cursor is present on the screen. So,
you must place the cursor at the right location on the screen before inserting the
element. Also, when using insert, a dialog box may open for further settings and
selection. Please choose the options in the dialog box and proceed further. The
dialog box is self-explanatory.
Some operations performed using the commands of the Insert tab are described as
follows -
InsertHeader: <Insert><Header><Default> : A Header box opens in the
upper part of the document. Enter the content you want to write in the
header.
InsertFooter: <Insert><Footer><Default>: A Footer box opens in the lower
part of the document. Enter the content you want to write in the header.
InsertFields: <Insert><Fields>: A pop-up menu appears (Figure 3.10).
Select the element to be inserted. The selected element will insert at the
location of the cursor. If you want to insert the field in the header or footer,
then first select header/footer.
Place the cursor in the correct position and then insert page number, time, date,
author name, etc.
InsertHyperlink: <Insert><Hyperlink>: A dialog box opens. On the left
side of the dialog box, select where you want to link – a webpage, document,
mail or to a new document. Then fill the details path, Form (text, button),
etc. The Text is the name that appears in your document as hyperlink. Figure
3.11 shows an example.
InsertTableofContent: <Insert><Indexes & Tables><Indexes & Tables>: A
dialog box appears. In Type, select Table of Content. Click OK. A table of
content will be inserted in your document.
InsertTable: <Insert><Table>: A dialog box appears. Enter the table name,
number of rows and columns. Click OK. A table is inserted in the document.
A table toolbar appears which allows you to format the table.
InsertFormula: <Insert><Object><Formula>: A pop up menu of elements
appears (Figure 1.12a). Select the element and write the formula. Figure
1.12b shows an example.
The Format tab consist of commands required for formatting the document. It
contains several commands as shown in Figure 3.13. The commands which are
required to be known at this stage are described in the figure. The commonly used
commands allow the user to format a page, paragraph, insert bullets, styles,
formatting, etc. in the current document.
Figure 3.13: Format Tab
When using the Format tab, the formatting happens on the text that has been
selected. So you must select the text on which the formatting has to be applied and
then use the relevant command from the Format tab.
Some operations performed using commands of the Format tab are described as
follows:
FormatCharacter: <Format><Character>: A dialog box opens (Figure
3.14). Select the font type, typeface, and size. Select font effects,
background etc. The changes happen to the text selected.
FormatParagraph: <Format><Paragraph>: A dialog box opens (Figure
3.15). You can change the indentation and spacing, borders, alignment, etc.
FormatBulletsand Numbering: <Format><Bullets and Numbering>: A
dialog box opens (Figure 3.16). You can select from bullets of different
kinds or numbering. In the document the bullets are inserted at the location
at which the cursor is present.
FormatPage: <Format><Page>: A dialog box opens (Figure 3.17). This
allows to format the whole page – borders, color, alignment, number of
columns etc.
To Change case of Text:<Format><Change Case>: A dialog box opens
(Figure 3.18a).
To Change Number of Columns: <Format><Columns>: A dialog box
opens. You can select 2-column page, three column page etc.
To Change Alignment of Text: <Format><Alignment>: A dialog box
opens (Figure 3.18b). Select from left, right, centered, and justified.
Figure 3.14: Format Character
The Table tab consists of commands that operate on a table. It contains several
commands as shown in Figure 3.19. The commands which are required to be
known at this stage are described in the figure. The commonly used commands
allow the user to insert a table, insert or delete rows, or columns in a table, etc. in
the current document.
When using the Tabletab, a new table is inserted at the location of the cursor on
the screen. For merge or split, select the cells on which the operation has to be
applied. When a table is inserted, a Table toolbar appears for the formatting of the
table (Figure 3.20).
Some operations performed using the commands of the Table tab are described as
follows -
ConvertTabletoText or Text to Table: <Table><Convert>: A pop up
menu appears. If text is to be converted to table, the Text to Table option
appears, Select it to convert text to table. If a table is already present, then
Table to Text option appears.
Select it to convert table to text.
The Tools tab consists of commands that can be used on the document for better
results. It contains several commands as shown in Figure 3.21. The commands
which are required to be known at this stage are described in the figure. The
commonly used commands allow the user to check spelling and grammar of the
content in the document, and count the number
of words and characters in the document.
Points to Remember
Exercises
7. List the tabs in the OpenOffice Writer. What are the key tasks performed by
the tabs.
8. What is the extension of the file created in OpenOffice Writer?
9. What is the purpose of the following tabs?
a. File
b. Edit
c. View
d. Insert
e. Format
f. T able
g. Tools
10. What is the difference between Save command and Save As command?
11. What is the difference between Move text and Copy text?
13. List the steps for inserting a hyperlink to a web page in a document.
14. What is the difference between toggle case and sentence case when using
Change Case?
15. Name the tabs in which the following commnds are present:
a. Header
b. Find&Replace
c. Status Bar
d. Ruler
e. Hyperlink
f. Formula
g. Paragraph
h. A lignment
i. Word and Count
A spreadsheet stores data in the form of a table comprising of rows and columns. It
is used to store, arrange, and sort data, and perform calculations on numeric data. It
is similar to the ruled paper accounting worksheets traditionally used for
bookkeeping. The computerized version of a worksheet is called a Spreadsheet
application that lets you quickly perform calculations on numerical data, represent
data with charts, analyze, and print.
Spreadsheets are used in various fields such as banking, finance, accounting, and
education.
There are various spreadsheet applications available that can be used to create and
manipulate a spreadsheet. The most commonly used are – Microsoft Office Excel,
Apache OpenOffice Calc, LibreOffice Calc, Google Sheets etc. Microsoft Excel is
a proprietary software from Microsoft for Windows. Both OpenOffice and Libre
Calc are free and opensource alternatives to Excel. Google sheets are a web-based
spreadsheet application which allows you to store and edit the spreadsheets online
and access them from any computer. In this chapter we‘ll study spreadsheets using
Apache OpenOffice Calc. Figure 4.1 shows how an OpenOffice Calc spreadsheet
looks like.
Figure 4.1: OpenOffice Calc Spreadsheet
You can install the complete Apache OpenOffice which include calc
b. Click on Unpack
c. After unpacking, click on Next
f. Click on Install
g. After installation, click on Finish.
To start OpenOffice Calc, there are various ways in which you can start it:
A s a Windows application, you can click
Start -> Programs ->OpenOffice
If the OpenOffice icon as shown in Figure 4.2 is on the desktop, double
click the icon.
Calc‘s default file format is the Open Document Format (ODF), an ISO/IEC
standard, which originated with OpenOffice.org.
Before using Calc to create spreadsheets, let us study the various menus and
toolbars available in the main window of Calc as shown in Figure 4.3.
Figure 4.3: Main Window of Calc
Title Bar: The title bar at the top displays the information about the
spreadsheet such as name of the current spreadsheet (ExampleSheet),
extension of the spreadsheet (.ods), and name of the software (OpenOffice
Calc). If the spreadsheet is new then its name is Untitled N where N is a
number. The ellipsis (three dots ...) in front of an option implies that a dialog
box will open when this option is selected. For example, on selecting the
Open option, a dialog box will appear which is meant for the user to enter
the location of the file to be opened.
Menu Bar: Just below the title bar is the menu bar. It contains various menu
options. On selecting a menu option, a submenu appears which contains
other options related to the main menu option. The menu options and few of
their submenu options are discussed below:
Edit: It contains commands to edit a file such as Cut, Copy, Paste, Paste
Special, Select All, Find & Replace, Delete Contents, Delete Cells,
Headers & Footers.
Standard Bar: It lies below the Menu bar. It contains icons which perform
similar operations as contained in the Menu bar options such as New, Open,
Save, Print, Page Preview, Cut, Copy, Paste, Sort, Chart, Find & Replace,
Spelling.
Find Bar: It contains a text box which can be used to enter text which is
meant to be searched in the spreadsheet. It highlights the cell which contains
the text to be searched. Multiple search results can be traversed by clicking on
the up and down arrows or by pressing the Enter key on the keyboard.
Formatting Bar: In the Formatting toolbar, the leftmost icon is for the Style
& Formatting and the following two boxes are the Font Name and Font Size
lists. They show the current settings for the selected cell or area. Click the
down-arrow to the right of each box to open the list.
Following the boxes, we have the three icons for changing the appearance
of the text such as making the text bold ( ), italics ( ), and underlining ( ).
Next we have the icons which are used to align the text within a cell as left
( ), center ( ), right ( ), or justify ( ).
Merge cells icon ( ) is used to merge multiple cells and form a single cell.
It becomes active when multiple cells are selected.
Text color can also be changed by clicking the Font Color icon ( ). Click
on the drop-down for more options of colors.
Formula Bar: On the left side of the Formula bar is the Name box which
contains a letter and name combination such as C4, whenever you select a
cell on the spreadsheet. This combination is called Cell Reference. The cell
reference is the address of a cell. The letter is meant for the column and the
number for the row. To the right of the Name box, one can see the Function
Wizard ( ), Sum ( ), Function ( ) icons. Function Wizard opens a dialog box
from which you can search through a list of available functions. Sum icon
inserts a formula into the current cell that totals the numbers in the cells
above the current cell. If there are no numbers above the current cell, then
the cells to the left are placed in the Sum formula. Function icon inserts an
equals (=) sign into the selected cell and the Input line, thereby enabling the
cell to accept a formula. When new data is entered into a cell, the Sum and
Function icons change to Cancel ( ) and Accept ( ) icons.
The contents of the current cell (data, formula, or function) are displayed in
the Input line, which is the remainder of the Formula Bar. You can either
edit the cell contents of the current cell here, or you can do that in the current
cell. To edit inside the Input line area, click in the area, then type your
changes. To edit within the current cell, just double-click the cell.
Sheet Tabs: A single spreadsheet Calc file can contain multiple sheets. You
can traverse individual sheets by using the Sheet tabs. The current active
sheet has a white tab. Clicking on another sheet tab displays that sheet, and
its tab turns white. Right click on the Sheet tabs will display various options
such as inserting, deleting, renaming, moving sheets, as shown in Figure 4.5.
Figure 4.5: Menu displayed when you right-click any Sheet tab
Status Bar: Status bar at the bottom provides information about the
spreadsheet and convenient ways to quickly change some of its features.
Sheet Sequence number shows the number of the current sheet / total
number of sheets in the spreadsheet as shown in Figure 4.6.
Selected cell (or cells) information is also displayed on the Status bar.
Zoom Slider
Figure 4.7: Information of Chart Displayed in the Status Bar
Sidebar: Located on the right side of the edit views of Calc, sidebar contains
frequently used tools grouped in decks such as Properties, Styles and
Formatting, Gallery, Navigator. Clicking on any of the vertical tabs opens
the deck for that tab.
ActiveCell: When you select a cell, you will notice a heavy black border
around the selected cell as shown in Figure 4.3. The heavy black border
indicates that selected cell is the active cell.
RowHeaders: Row headers are in the form of numbers -1,2,3.... which are
present at the left of each row.
Create a New Blank Worksheet : There are many ways to create a new
blank worksheet as discussed below:
On the menu bar, click File->Open as shown in Figure 4.8 and then a
dialog box opens up which is used to locate the spreadsheet to be opened
as shown in Figure 4.10.
On the Standard bar, click on the Open icon ( ). Click on the drop-down
to open a list of recently opened OpenOffice files.
You can also use the Calc Navigator on the Standard bar or Press F5
which opens the following Navigator dialog box in which you can enter
the row number and column letter which you want to access.
Cell to Cell Navigation: You can use the Mouse and various keys on the
keyboard such as Tab, Enter keys, and Arrow keys to navigate from one
cell to another.
Saving Worksheet:
While saving a new spreadsheet for the first time, a dialog box will open to
enter a name and select the location for saving the spreadsheet. For example,
in Figure 4.14 a spreadsheet file is saved on the Desktop with the name
ExampleSheet and type .odf.
On the menu bar, click File->Close (Figure 4.8). A dialog box opens up if
the spreadsheet has not been saved as shown in Figure 4.15. The dialog box
gives options to the user to Save the file, Discard the changes or Cancel the
close operation.
You can also directly close the OpenOffice Calc main window.
Data– There are various types of data that can be entered in a cell:
Entering Data: Data can be entered in an active cell. Following are the
steps to enter data in say cell A1 (Figure 4.16):
i) Click on the A1 cell which is at the top left of the spreadsheet. The
heavy black border around the A1 cell indicates that it is the active
cell.
Using the Edit Menu: The Cut, Copy, and Paste functions are available
in the Edit menu. Following example illustrates the steps to do cut/copy-
paste using Edit Menu:
i) Select the cell whose contents you want to cut or copy (say cell
D5).
ii) Go to the Edit menu on the menu bar and click on Cut/Copy.
iii) Select the cell where you want to paste the contents of cell D5
(say cell F5).
iv) Go to the Edit menu and click on Paste. If you have selected Cut
option then the contents of D5 will be removed from D5 and
pasted in F5. But if you have selected the Copy option, then the
contents of cell D5 will remain in intact and the same will be
copied in F5.
Using the Standard bar: The icons are Cut ( ), Copy ( ), and Paste ( ).
Following example illustrates the steps to do cut/copy-paste using
Standard bar:
i) Select the cell whose contents you want to cut or copy (say cell
D5).
ii) Click on the Cut / Copy icon in the Standard bar.
iii) Select the cell where you want to paste the contents of cell D5
(say cell F5).
iv) Click on the Paste icon in the Standard bar.
The AutoFill command also recognizes customized sort lists that are defined
under menu Tools -> Options -> OpenOffice Calc -> Sort Lists. You can also
define your own sort list.
In case you want to enter the same value, say, 1 in 10 consecutive cells simply
press the Ctrl key while dragging the fill handle.
Suppose you want to enter even numbers in a column. For example, entering
2, 4, 6, 8….20. Then follow the procedure:
i) Type the first two values (2 and 4) in the first two cells.
ii) Then select both the cells and drag the fill handle of the cell containing
value 4. You will observe that now the values filled by Calc will be 6,
8, 10…20.
Unit - 3
Thus, if you want to generate your own series, then you have to specify
two values so that Calc can determine how to generate the subsequent
values.
Font: Font refers to the design for a set of characters. It is the combination
of typeface and other qualities, such as size, pitch, and spacing. The font can
be changed from the Formatting bar.
Font Name: Various font types are there in Calc such as Arial, Arimo,
and Century Schoolbook L. The font type can be selected from the Font
Name box in the Formatting bar as shown in Figure 4.19. Using the drop
down, you can select from the list of font types available in Calc. The
appearance of the font types listed in the drop down is how the text will
look when a font type setting is applied as shown in Figure 4.20.
Font Size: Click on the drop down arrow of the font size which is next to
the Font Name box and then select the size you want to use.
Font Style: You can also make the text bold, italics or underlined by
clicking on the icons available on the formatting bar respectively.
Center Align: Both the left and right edges are equally distant from the
left and right cell borders respectively.
Right Align: The right edge of the text is along the right cell border.
Justify: Aligns the text to the left and the right cell borders.
Changing Color: You can easily change the color of the background of the
cells as well as the text color as shown in Figure 4.21. On the left the
background color is changed and on the right the text color is changed.
Gridlines and Borders: The gray gridlines (vertical and horizontal lines)
that you can see in a Calc spreadsheet help you while you‘re working in a
spreadsheet. Gridlines appear automatically showing you how the data is
organized into rows and columns.
Borders are different from gridlines because they help you highlight
important information for people to see as shown in Figure 4.24.
Borders need to be added if you want to highlight certain cells. One more
difference is that gridlines aren‘t automatically printed, while borders are. Thus, to
draw borders around a cell or multiple cells, you can use the Border icon on the
Formatting bar. A drop down (Figure 4.25) in the same icon provides various
options to draw the left or right or top or bottom border, all borders, outer border
etc. In order to create borders, select the cells around which you want borders and
then click on the required border option.
Figure 4.25: Borders
Flow of Text: In order to control the flow of text within cells, Calc provides
various ways:
1) Merging / Splitting Cells: In order to merge cells, select the cells and
click on the Merge Cells icon in the Standard Bar. To split the merged
cells, select the cell and click on the Merge Cells icon.
2) Wrap Text: It means to break the text into multiple lines i.e.,
adjusting the row height to fit the text within the cell but keeping the
column width of the cell same. Steps to wrap text:
i) Right-click on the cell.
ii) Select the option – Format Cells.
iii) A dialog box opens up. Open the Alignment Tab and check the
option – Wrap text automatically as shown in Figure 4.26.
3. Shrink to Fit : This option shrinks the text to fit in the size of the
existing cell. In this case neither the row height nor the column width
is changed. The text size is decreased according to the cell. Steps to
shrink the text size to fit the cell:
In Calc, there are many ways in which numerical data can be formatted i.e.,
changing the appearance of numbers. Some of the number formats are
available on the Standard Toolbar (Currency, Percent, Standard, Add/Delete
Decimal place).
For more options, right-click on the cell and click on Format Cells to open a
dialog box as shown in Figure 4.28. Click on the Numbers tab and then you
can select the category of the format as per requirement.
Figure 4.28: Number Formatting Dialog Box
1. Currency: In the currency format, you can prefix or suffix currency symbols
to the numeric data. The default currency is Rs. which is prefixed
to the number, commas are inserted at the thousand, million,
billion positions, and two decimal places are added to the
number.
2. Percent: It displays the number as a percentage. Two decimal places are
added to the number and the percent symbol (%) is suffixed at
the end.
3. Standard: It sets the number in the cell to the default format by removing
any other numeric formatting applied.
5. Date: By default, the date format in Calc is dd/mm/yy. But in case you
want to change the format, you can find various date formats in
the Format Cells dialog box.
Data can be searched by using the Find toolbar. If you want to find and replace the
data then perform the following steps:
i) Click on the Edit menu and select the Find & Replace option.
ii) A dialog box opens (Figure 4.30) in which you can type the text to be
searched in the ―Search for‖ text box and the replaced text in the ―Replace
with‖ text box. You can find or replace the results individually (Find or
Replace) or all of them at one go by clicking on the Find All or Replace All
button.
iii) The Match case check box when checked implies that the searching is
sensitive to the case of the text i.e., uppercase and lowercase letters are
treated differently. Otherwise uppercase and lowercase letters are treated
as equal.
iv) Entire cells check box when checked implies that Calc will search for the
whole words that are identical to the text to be searched and if the text to
be searched is part of some other text then it will not highlight that in its
results. If this check box is not checked then the text to be searched is
highlighted even if it is part of cell contents.
4.3.7 Deleting
Delete Data: For removing data from a cell, click inside the cell (double-
click) and then press the Backspace key according to the text you want to
delete. However, if you only select the cell (single-click) and then press
the Backspace key then this will result in the deletion of all the text
within the cell, though the formatting of the cell remains.
Deleting Data and Formatting: Delete key (or Right-click the cell and
select Delete All option) can be used to remove data as well as the
formatting from a cell. Selecting the cell and pressing the Delete key
opens a dialog box (Figure 4.31) which can be used to delete different
aspects of the cell. To delete everything in a cell (contents and format),
check Delete all.
Sometimes when you have finished entering data in a spreadsheet you may need to
add or remove rows and columns. One way is to select the row or column by
clicking on the row header (number) on the left or column header (alphabet) on the
top and then right-click. A menu appears (Figure 4.33) which can be used to insert
and delete rows or columns and also adjust the height or width of a row or column.
Insertion of row and columns can also be performed by using the Insert menu on
the Menu bar as shown in Figure 4.34.
Figure 4.34: Insert Menu
Formulas can be used for basic operations such as addition, subtraction, as well as
more complex calculations such as income tax calculations, averaging. The
advantage of using formulas is that even if the data is changed, Calc will
automatically recalculate the answer without the need to rewrite the formula again.
Another advantage of using formulas is that they can be easily copied to a number
of cells.
Example 1: Adding data in two numbers and storing the result in cell D6.
Step 1: In cell D6, type the equal sign (=). This informs Calc that D6 will
contain a formula.
Step 2: Now type 4+5
Step 3: Press Enter Cell D6 will contain 9. You can see the formula (=4+5) in
the Input line in the formula toolbar as shown in Figure 4.35.
Figure 4.35: Example of Adding Two Numbers
In the above example, we have used numbers for addition. What if we were
supposed to add the contents of cell D4 and D5 and then store the result in cell D6?
This can be achieved using cell reference or address of a cell.
In Calc, a cell reference identifies the location of a cell or group of cells in the
worksheet. The cell reference is also called address of a cell. Cell references are
used in formulas, functions, and other commands.
Individual cell reference: Each cell is identified by its column letter and
row number in this order. For example, the cell reference of the topmost and
leftmost cell is A1 (Column=A, Row=1).
Range of cells – You can use cell referencing for a consecutive range of
cells also using a colon (:). For example, cell reference for the range of first
five cells in column D is D1:D5 (i.e., D1, D2, D3, D4, and D5). Cell
reference for the range of first five cells in row 5 is A5:E5 (i.e., A5, B5, C5,
D5, and E5). Cell reference for a group of four cells spanning first 2
columns and first 2 rows of the spreadsheet is A1:B2 (i.e., A1, A2, B1, and
B2).
When you wish to add a reference to a cell in some other cell then there are
two ways. First is to type the cell reference using the keyboard. Second is
using the mouse. The steps to insert cell reference using the mouse is as
follows:
After you press Enter, D6 will contain the sum of the numbers stored in cells D4
and D5. You can view the formula of cell D6 in the Input line of Formula toolbar
as shown in Fig 4.36. If you double-click on cell D6, then also you can see the
formula in cell D6.
Try changing the values in cell D4 and D5 and you will observe that the result in
cell D6 will be automatically recalculated and updated. This is one of the most
important use of Calc.
Just like the plus (+) operator, you can use various other operators in Calc as
shown in Table 1.
Precedence of Operations:
If multiple operators occur in a formula then the calculation is performed by using
the following order:
1. Operations enclosed in parentheses.
2. Exponentiation.
3. Multiplication and division. (If both multiplication and division occurs
in a formula then the calculation is performed from left to right.)
4. Addition and Subtraction. (If both addition and subtraction occurs in
a formula then the calculation is performed from left to right.)
Functions
Calc has a set of predefined formulas called functions. They differ from formulas
in the sense that in a formula we provide both the operands and the operator,
however in functions we only provide operands (or arguments) as functions have
predefined operation to be performed on the arguments. Just like a formula, the
function also begins with an equal (=) sign. We specify the arguments enclosed in
parenthesis () and separated by a comma (,). For
example, SUM function is used to add as shown below:
= SUM (3, 4) – This will add numbers 3 and 4.
= SUM (A3, A4) – This will add numbers in cell A3 and A4.
= SUM (3, 4, A3, A4) – This will add number 3, 4, contents of cell A3 and
A4.
Apart from SUM () there are various commonly used mathematical functions in
Calc which are discussed as follows:
6. SIN (n), COS (n), TAN (n) – To calculate sine, cosine and tangent of n.
Relative Addressing: All cell references are by default relative i.e., they adjust
and change when copied or when using AutoFill. When you enter an address A in
a cell B then Calc does not store the actual address of A but instead it stores the
number of rows and columns relative to the cell containing the address B or in
other words how to reach A from B.
For example, cell A4 contains the address A3 (=A3). Now, if you will copy the
contents of A4 to B4 then it will contain the address B3 (=B3) because the relative
address is used. That means when A4 contains the address A3, it stores the value of
the cell above it (A4-one row) and hence, when it is copied in cell B4, the address
of cell one above B4 (B4-one row) i.e., B3 is actually stored in B4.
Consider the following worksheet as shown in Figure 4.38 which the formula in
cell A6 = SUM (A1:A5) is copied into cell B6. As you can observe that now B6
contains the formula SUM (B1:B5) and not SUM (A1:A5) due to relative
addressing.
Sorting: Data can be easily sorted in Calc by using the sort command available on
the Standard toolbar (Sort Ascending , Sort Descending ) and also in the Data
menu which opens a dialog box for more options as shown in Figure 4.41.
Data will be sorted according to the first column of the selected cells.
Step 2: Click on the Sort option in the Data menu which opens a dialog box.
Step 3: You can change the select the column based on which you want to sort
the data. Also, you can select the Ascending or Descending option.
You can also select multiple criteria (up to 3) to sort with each criterion applied
one after the other.
For example, you have the following data as given in Table 2 and you want to sort
it in ascending order according to the price per item and then if two items have the
same price then in descending order of the number of items and if two items have
the same price and the number then according to their code sorted alphabetically in
increasing order.
Step 1: Select the cells you want to sort including the headings
Step 2: Since the data you have selected contains headers (Price per Item and
Number of Items) which you don‘t want to be included in sorting then
open the Options tab in the same dialog box and check the option
Range contains column headers.
Step 3: Click on the Sort option in the Data menu which opens a dialog box.
Step 4: In the Sortby section select the Price per Item column and ascending
Radio button.
Step 5: In the Thenby section select the Number of Items column and
Descending radio button.
Step 6: Lastly in the next Thenby section select the Item Code and ascending
Radio button as shown in Figure 4.42.
In the Options tab, you can see various other options for sorting as shown below:
Case Sensitive – If the cells to be sorted contain the same letter in the same
position but different in case then the one in uppercase is placed after the one in
lowercase if the sort is ascending and vice versa if the sort is descending.
Filtering Data : Applying a filter means displaying data based on some conditions
or filters.
Filters can be applied by using the Filter option in the Data menu.
Three types of filters can be applied – AutoFilter, Standard Filter and Advance
Filter. Let us study AutoFilter and Standard filter in detail.
1. AutoFilter
This filter is added on the topmost row of the selected data in the form of a drop
down list from which you can select data to be displayed or in other words apply
filters.
Example:
Given the following data in Table 3, the following are the steps to apply
AutoFilter to display all the Female candidates.
Step 1: Select the data.
Step 3: On the topmost cell of each column you will observe drop-down boxes.
Click on the drop down in the gender column and you will see all the unique
values in that column.
Step 4: S elect the Female entry in the drop-down as shown in Figure 4.44.
The resulting sheet will contain all the female entries and the drop-down in the
column in which filter is applied (Gender) will be colored in blue as shown in
Figure 4.45.
You can apply filters to other columns also. Suppose in the above example, data
was to be filtered for all the female students having 98 marks. Then click on the
drop-down of the Marks column and select the 98 entry in the drop-down. The
output will be as shown in Figure 4.46.
2. Standard Filter
Standard filter is used to provide more options for filtering such as combining
multiple filters by using AND and OR operator. AND operator implies that all the
filters must be satisfied for displaying the data. OR operator implies that at least
one filter should be satisfied for displaying the data.
ANDOperator Example - Suppose in Table 3, you have to select the male students
having more than 75 marks. Following are the steps to filter data based on this
criterion:
Step 2: Select Data menu and click on Filter->Standard Filter. A dialog box will
open.
Step 3: Add the criteria for Gender = ―Male‖ AND Marks > 75 as shown in
Figure 4.47.
The AND operator ensures that all the criterion are satisfied.
Step 2: Select Data menu and click on Filter->Standard Filter. A dialog box will
open.
Step 3: Add the criteria for Gender = Female OR Marks > 75 as shown in
Figure 2.49.
Suppose in Table 3, you have to select the female students whose name begins with
the letter ―S‖ or male students whose name begins with letter ―G‖.
Step 2: Select Data menu and click on Filter->Standard Filter. A dialog box will
open.
Step 3: Add the criteria for Gender = Female AND Name of the Students Begins
with ―S‖ OR Gender = Male AND Name of the Students Begins with ―G‖ as
shown in Figure 2.51.
3. Removing AutoFilter –
Select the cells as selected while adding the filter. From the Data menu, select
Filter->Remove Filter as shown in Figure 4.53. The filters will be removed.
In Calc, you can create graphs and charts to represent the data graphically.
Sometimes, it is very difficult to analyze spreadsheets containing huge amount of
data.
For example, analyzing the academic performance of students of a school over the
past 10 years. Such analysis can be done effectively by using charts which provide
a visual presentation of data.
Various types of charts can be created in Calc. It offers a choice of 10 chart types
such as Column chart, Bar chart, Pie chart, Area chart. Each of the chart types has
several sub-types.
Step 2: Go to the Insert menu and select the Chart option as shown in
Figure 4.54 or another way is to click on the Chart icon in the
Standard toolbar.
Step 3: Chart wizard dialog box is displayed as shown in Figure 4.55 which is
used to insert various options related to the chart such as the type of
chart, data range, data series and elements of the chart.
Step 4: Select the chart type (Column chart, Bar chart, Pie chart etc.) and click
on the Finish button.
Let us create different types of charts for the following data as shown in
Table 4.
Column Chart: A Column chart is used to compare values across categories by
using vertical bars. The Column chart can be inserted by selecting the Column
option in the Chart type of the Chart Wizard. You can also select from the various
subtypes of Column chart from the Wizard. The Normal Column chart for the data
in Table 4 is shown in Figure 4.56.
Bar Chart: A Bar chart is the horizontal version of a column chart. It is used if
you have large text labels. Select the Bar chart option in Step 3 above to create a
Normal Bar chart for the Table 4 is shown in Figure 4.57.
Pie Chart : A Pie chart is used to display the contribution of each value (slice) to a
total (pie) i.e., it can be used to plot various pieces of a single entity. The Normal
Pie chart for Table 4 is shown in Figure 4.58.
Line Chart : A Line chart is used to compare trends and changes in values over
time. The line chart (lines only) for the data in Table 4 is shown in Figure 4.59.
Apart from changing the chart type, chart wizard is also used to set various other
options of the chart as discussed below:
InsertingTitle : You can insert title and subtitle of the graph and titles of X-
axis and Y-axis in the Chart Elements of the Chart Wizard as shown in
Figure 4.61.
After inserting the chart elements, the Points and Lines chart for the Table 4 is
shown in Figure 4.62.
You can modify the placement of legends or even remove them in the
chart by using the Chart Wizard->Chart Elements as shown in the right
panel of Figure 4.61.
Grids: To make the data in a chart that displays axes easier to read, you can
display horizontal and vertical chart gridlines. By default, the horizontal
gridlines are displayed. You can turn on and off the gridlines by using the
Chart Wizard->Chart Elements as shown in Figure 4.61.
After the chart has been inserted, you can easily move and resize it. Click
anywhere in the chart area and drag it to another position in the spreadsheet for
moving the chart. For resizing it, click on the chart and then click and drag any of
the chart resizing handle (Eight green small squares on the border of the chart as
shown in Figure 4.63).
Deleting Charts
Select the chart and then press the Delete key on the keyboard for deleting a chart.
Modifying Charts
After the chart has been inserted you easily modify the chart. Double-click on the
chart and then right- click. You can see various options such as Chart type,
legends, titles, as shown in Figure 4.64 which can be changed.
A macro is a recording of each and every command and action you perform to
complete a task. A macro records your mouse clicks and keystrokes while you
work and play them back later. When you run the macro, it plays those actions
back in the exact same order. Thus, if you want to repeat the actions multiple times
you just need to run the macro.
Create/Record Macros:
Observe a small dialog box (Figure 4.66) has appeared on the worksheet displaying
Stop Recording.
2. Calc has started recording the Macro. Until you stop the recording, every
Calc command and keystroke will be recorded in the macro, in the order in
which they are entered.
3. After we have done all the required tasks, we will stop recording the macro
by clicking on the Stop recording option on the dialog box (Figure 4.66). A
new dialog box will open (OpenOffice Basic Macros) in which you have to
specify the name of the macro and the location for saving it (We have named
the macro as ColorChange and saved it in My Macros folder) as shown in
Figure 4.67.
Now we have a macro that can perform in a single operation all the tasks we have
performed during recording of the macro.
Run/Use Macros created:
Following are the steps to run/use a macro that we have already created:
3. The tasks performed during recording of the macro will be repeated in the
same order in which they were performed. (Running ColorChange Macro
will create borders around the cells A1:C3 and set their background color to
green.)
By default, recorded macros use absolute cell referencing, which means that exact
cell locations are recorded into the macro.
Delete Macros:
Following are the steps to delete a macro that we have already created:
Calc offers various options for printing spreadsheets. Many details can be selected
for what is to be printed and what not.
For printing, open the File tab on the Menu bar and select the Print option. A
dialog box will open (Figure 4.70) in which you can select various options such as:
Points to Remember
Exercise
b) Add another column titled ―Total hours per user‖. Using an appropriate
formula, calculate the total hours each student used in the week.
c) Add another column titled ―Daily average hours used‖. Using an appropriate
formula, calculate the average hours each student used per day. The hours
should be rounded to 1 decimal place.
d) Below the last student, add a row titled ―Total hours per day‖. Using an
appropriate formula, calculate the total hours used each day of the week.
2. ABC Sports expects its sales figures for 2015 to exceed the sales in 2014 by
10%. Create the following spreadsheet:
a) Enter a formula in C54 that will calculate the amount of the sales for 2021.
Use an absolute reference in order that the manager can change the rate of
the expected increase to be able to view likely sales figures for 2021.
b) Change the rate of the sales increase to 20% and then 25% and see what
happens to the 2021 figures.
c) Total the sales for the year 2020 and 2021.
5. Create a macro which will set all borders of the cells D3:J15, set the color of
cells as blue and set the first row to have font style as bold and center
aligned text.
Ch -5
Presentation
5.1 Introduction
Presentation software is required for the creation of the presentations for a larger
audience. The presentation software has tools that allow the user to create
presentations with sound, text, movies, pictures, and tables.
To start using the OpenOffice Impress software, any one of the following steps
needs to be performed:
<Start><Programs><OpenOffice><Presentation> , OR,
If the OpenOffice Icon (Figure 5.1) is on the desktop, double click the icon
The Impress layout and its general features are described as follows:
Tabs(File, Edit, View, Insert etc.) contain drop down menu which have
commands provided by the tab.
Scroll Bar:There are two scroll bars – horizontal and vertical. They help to
scroll the content or the body of the slide.
Work Area: It is the working area where the text of the slide is typed.
The OpenOffice Impress has eight tabs – File, Edit, View, Insert, Format, Tools,
Slide Show, and Window. There is also a help tab. On clicking any of the tabs, a
dropdown menu appears which have several commands and options. Select the
command that you want to execute.
The key tasks that can be performed using the tabs are as follows:
Edit: For editing the current presentation, like cut, paste etc.
Insert: For inserting new elements in the presentation, like slide, page
number, hyperlink etc.
Tools: For spelling check, gallery of object art to add to slides, to configure
menus.
When you click <File Tab><Save As>, a Save As dialog box appears.
You can –
Select folder (directory) where the file is to be saved,
Type the File name for the presentation,
Select ―save as type‖ of presentation (.odp etc.)
Click ―Save: button to save the file.
The Edit tab consist of commands required to perform editing on the current
presentation.
It contains several commands as shown in Figure 5.4. The commands which are
required to be known at this stage are described in the figure. The commonly used
commands allow the user to – cut, copy, paste, find & replace, undo, and redo
changes in the current presentation.
Find and Replace:This is used to find words then replace it with the new
one. This option is useful to find the word at multiple places in the
presentation and replace all of them with the new one.
The View tab consist of commands required for viewing the current presentation
on the screen. It contains several commands as shown in Figure 5.5. The
commands which are required to be known at this stage are described in the figure.
The commonly used commands allow the user to view slides in different layouts,
status bar, ruler, sidebar, etc.
View -> Normal: This is the main editing view for writing and creating
slides
View -> Slide Sorter: This presents all slides of the presentation in a
miniature form. It helps in viewing all slides together and allows easy
moving of slides.
View -> Slide Show:It shows slides as they will be actually presented.
No editing can take place in this view.
View -> Notes Page:Allows user to make notes for the selected slide.
The notes can be seen only by the presenter while making a presentation.
The note page is not visible to the audience of the slide show presentation
Figure 5.6.
Figure 5.6: Different views (a) Normal (b) Outline (c) Notes (d) Slide Sorter
Unit - 3
Use Slide Master: Select <View><Slide Master>: This allows changing the
background color, text color, bullet type, bullet color, etc. The change in the
slide master is visible in all slides of the presentation.
The Insert tab consist of commands required for inserting different elements in the
slides or inserting slides itself. It contains several commands as shown in Figure
5.8. The commands which are required to be known at this stage are described in
the figure. The commonly used commands allow the user to insert slide, page
number, date and time, pictures, sound, hyperlinks, etc. in the current presentation.
Unit - 3
138
Figure 5.8: Insert Tab
When using an Insert tab to insert an element, the insertion of an element in the
presentation happens at the location where the cursor is present on the slide.
So, you must place the cursor at the right location on the screen before inserting
the element. Also, when using insert, a dialog box may open for further settings
and selection. Please choose the options in the dialog box and proceed further. The
dialog box is self-explanatory.
Some operations performed using the commands of the Insert tab are described as
follows -
Insert Page Number, Date and Time:
Insert -> Page Number :A Header and Footer Window opens. Make settings
here for date, time and page number.
Insert Fields:
<Insert><Fields> :A pop-up menu appears (Figure 5.9). Select the element to
be inserted. The selected element will insert at the location of the cursor.
Unit - 3 139
Figure 5.9: Insert Fields Option
Insert Hyperlink:
<Insert><Hyperlink> :A dialog box opens. On the left side of the dialog box,
select where you want to link – current presentation slides, new presentation or
Internet link. Then fill the details path, Form (text, button), etc. The Text is the
name that appears in your document as a hyperlink.
The Format tab consist of commands required for formatting the presentation
slides. It contains several commands as shown in Figure 5.10. The commands
which are required to be known at this stage are described in the figure. The
commonly used commands allow the user to format a character, paragraph, slide
design and slide layout, etc. in the current presentation.
When using the Format tab, the formatting happens on the text or the figure that
has been selected.
So, you must select the text or the figure on which the formatting has to be applied
and then use the relevant command from the Format tab.
Some operations performed using the commands of the Format tab are described as
follows –
Format Character:Format -> Character. A dialog box opens. Select the font
type, typeface and size. Select font effects, background etc.
Format Line:Format -> Line. A dialog box opens (Figure 5.11). You can
select from line style, width, color etc. In the slide, formatting applies to the
selected line.
Format Slide Layout:Format -> Slide Layout. You can select a slide layout
for the slide from the different slide layouts presented to you. (Figure 5.12).
Figure 5.11: Format Line
Unit - 3
141
The Tools tab consists of commands that can be used on the presentation for better
results.
It contains several commands as shown in Figure 5.13. The commands which are
required to be known at this stage are described in the figure. The commonly used
commands allow the user to check the spelling of content in the presentation.
Figure 5.13: Tools Tab
Unit - 3
142
Some operations performed using the commands of the Tools tab are described as
follows -
The Slide Show tab consists of commands that can be used on the presentation for
better results. It contains several commands as shown in Figure 5.14.
The commands which are required to be known at this stage are described in the
figure.
Figure 5.14: Slide Show Tab
When using the Slide Show tab, it contains commands that are required during the
presentation of the slide show.
Some operations performed using the commands of the Slide Show tab are
described as follows:
Slide Show Settings: Slide Show -> Slide Show Settings. A dialog box opens
(Figure 5.15). Select the slide to start from, animation allowed etc.
Custom Animation: Slide Show -> Custom Animation.A dialog box opens
on the right side of the screen. Select the element on the slide on which the
animation has to be applied. Click <Add>. Select the animation to be applied.
Slide Transition: Slide Show -> Slide Transition.A dialog box opens on the
right side. Select the transition you want to apply to the slide.
Unit - 3
143
There is a difference between animation and transition. Slide transition applies to
the pattern that will show up when one slide goes to the next (for example, wheel,
diamond etc.). Slide animation applies to elements of a single slide, i.e., how the
different elements in a slide will appear on the screen, their order, etc.
Figure 5.15: Slide Show Settings
The commands in this tab allow the user to open a new window or close an
existing window.
The Help tab consists of commands that provide help to the user of the OpenOffice
Impress software. On clicking on the help tab, a screen as shown in Figure 5.17
appears.
You can browse the Help for the command you want.
Figure 5.17: Help Tab
Points to Remember
11. What is the difference between Save command and Save As command?
12. What is the difference between Move text and Copy text?
13. How is Find and Replace option useful?
14. What is the purpose of the following views -
a. Normal
b. Outline
c. Slide Sorter
d. Slide Show
e. Notes Page
f. Handout Page
15. What is the need to use the Slide Master?
16. List the steps for inserting a hyperlink to a video in a presentation.
17. What is the difference between slide transition and slide animation.
18. Name the tabs in which the following commands are present
a. Header and Footer
b. Find & Replace
c. Status Bar
d. Ruler
e. Hyperlink
f. Animation
g. Transition
h. Normal view
i. Copy
· query the database (that is, ask questions about the data)
· produce flexible reports, both on screen and on paper, that make it easy to comprehend the
Relational Database
In the database named Learner shown below, the data is organized into separate tables. Once
the tables have been set up, a relationship can be created to link them together. Such a
database that stores data in separate tables that are related through the use of a common
column is called a Relational database.
Benefits of using a DBMS are:
RDBMS Terminology
1. Domain
It is pool of values or the collection (set) of possible values from which the value for a
column is derived.
For example, consider the following table named Customer with details about customers:
2. Record - The horizontal subset of the Table is known as a Row/Tuple. Each row
represents a record, which is a collection of data about a particular entity such as person, place
or thing.
3. Field - The vertical subset of the Table is known as a Column/Attribute. The term field is
also often used for column. Each column has a unique name and the content within it must be
of the same type.
5. Key: A column or a combination of columns which can be used to identify one or more
6. Primary Key: The group of one or more columns used to uniquely identify each row of a
When you got admission in the school, you were given an Admission number. The Admission
number assigned to you was not assigned to any other student of your school (it is unique).
When patients go to a hospital, each patient is given a unique patient number. When you go to
open an account in the bank, you are given a unique account number. Admission number,
Patient number, Account number are all examples of Primary key. A primary key is a field in a
table that is unique for each record. Every database table should have a column or a group of
columns designated as the primary key. The value this key holds should be unique for each
record in the table. Some more examples of Primary key are: Accession Number of a Book in
the Book table, Employee ID of an employee in the Employee Table, Item Code of an item in
the Stock table, Flight Number of a flight in the Flight Master Table, etc.
7. Candidate Key: A column or a group of columns which can be used as the primary key of
a relation is called a Candidate key because it is one of the candidates available to be the
primary key of the relation.
In a table, there may be more than one field that uniquely identifies a record. All such fields are
called candidate keys. A Candidate key is an attribute (or set of attributes) that uniquely
identifies a row. A Primary Key is one of the candidate keys. A table may have more than one
candidate keys but definitely has one and only one primary key.
8. Alternate Key: A candidate key of a table which is not selected as the primary key is called
its Alternate Key.
Example: Consider the following Table, RollNo and Admission_no both may be used to
uniquely identify each row in this Table, so both are candidate keys.
Candidate keys which are not made primary key are called Alternate keys. In the above
example, if we use one of the candidate keys, say, Admission_No as the Primary Key, the other
Candidate Key RollNo is the Alternate Key and vice-versa.
9. Foreign Key: A primary key of a base table when used in some other table is called as
Foriegn Key.
For example: Table Employee has columns : EMPID, EMPNAME, ADDRESS, CONTACT NO,
DEPTID. And the table Department has columns : DEPTID, DNAME, CITY. Then the DEPTID
column of the Employee table will be known as Foreign Key because it is declared as Primary
Key in the Department table.
Note: The primary key column and the foreign key column must have the same data type and
size.
Introduction to MySQL:
Characteristics of MySQL:
MySQL is a platform independent application which works on many operating systems like
Windows, UNIX, LINUX etc. and has compatibility with many languages including JAVA , C++,
PHP, PERL, etc.
MySQL is an easy to install RDBMS and is capable of handling large data sets.
Since MySQL is released under an open-source license, it does not require any cost or payment
for its usage. Any one can download this software from specific location on Internet. If you want
to download, follow the following steps. The step for two most popular OS platform, Windows
and Linux are discussed here.
https://www.mysql.com/downloads/
Scroll the above screen and Click on the "Download" button for the Community Server and
choose from the list of supported platforms (i.e., operating systems that it will run on), which
include 32-bit and 64-bit Windows, several different Linux, Solaris, Mac OS X, and a few others.
(Choose appropriate download link as per the operating system)
Keep selecting the default options provided in subsequent windows. If the configuration does
not encounter any errors, then information will be prompted that the configuration file was
created, MySQL server was installed and started, and the security settings applied.
Note: In the process of configuration of MySQL, a prompt for password will be displayed - Here
you should enter a password and remember this password, as it will be required each time to
start MySQL.
Creating a Database
Before creating a table we will first create a database.To create a database we will give
CREATE DATABASE command.
Using a database
Syntax: USE <databasename>;
mysql> USE School;
Database Changed
Creating a Table
After creating a database, the next step is creation of tables in the database. For this CREATE
TABLE statement is used.
Syntax:
CREATE TABLE <TableName>(<ColumnName1> <Data Type1>,
<ColumnName2> <Data Type2>,… ,<ColumnNameN> <Data TypeN>);
Create a simple table named Learner with only two columns RollNo and Name in the School
database.
To do this, enter the following statement:
mysql> CREATE TABLE Learner
(RollNo INTEGER,
Name VARCHAR(25));
Query OK, 0 rows affected (0.16 sec) will be displayed.
If table Student already exists in database school, then the error message "Table Student
already exists" is displayed. Give meaningful name to a table. If a table will store information
about students, name it STUDENT. Table names and column names are not case sensitive. For
example, STUDENT is treated the same as STUDENT or student. Each column in the table is
given a unique name. In the example above the column names are Rollno, Name etc. This
doesn't mean each column that is named has to be unique within the entire database. It only
has to be unique within the table where it exists. Also notice that the names do not use any
spaces. When naming tables and columns be sure to keep it simple with letters and numbers.
Spaces and symbols are invalid characters except for underscore(_). Column names like
first_name, last_name, email are valid column names.
Constraint Purpose
Recall that the 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:
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:
To create a table Bills with the combination of columns Order_No and Cust_Code as the
primary key, we enter the statement:
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:
Let us now check the table structure with the command: DESC bills;
The table structure is as shown below:
+-----------------+---------------------+----------+--------+-----------+------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+----------+--------+-----------+------------+
| Order_Num | INT(4) | NO | PRI | 0 | |
| cust_code | VARCHAR(4) | NO | PRI | | |
| bill_Date | date | YES | | NULL | |
| Bill_Amt | DECIMAL(8,2) | YES | | NULL | |
+-----------------+---------------------+----------+--------+-----------+------------+
Now if we try to enter a NULL in the specified column, MySQL will reject the entry and give an
error.
The table structure also includes the constraints, if any. Therefore, when we use DESC
command,we are shown the table structure as well as constraints, if any. A constraint is shown
beside the column name on which it is applicable. E.g., the statement:
DESC Shoes;
displays the table structure as follows:
+--------+-----------------------+-------+-------+---------+---------
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------+---------+-----+---------+--------
| Code | CHAR(4) | NO | PRI | NULL | |
| Name | VARCHAR(20) | YES | | | |
| type | VARCHAR(10) | YES | | NULL | |
| size | INT(2) | NO | |0 | |
| cost | DECIMAL(6,2) | YES | | NULL | |
| margin | DECIMAL(4,2) | YES | | NULL | |
| Qty | INT(4) | YES | | NULL | |
+---------+--------------------+--------+-------+---------+--------
After execution of the above ALTER TABLE statement, the Games column is added and
a NULL value is assigned to all the rows in this column.
Now, suppose we want to change the newly added Games column to hold integers(in
place of character data) using ALTER TABLE statement:
To delete a column of a table the ALTER TABLE statement is used with Drop clause.
If we create a table without specifying any primary key, we can still specify its primary key by
ALTER TABLE command. Suppose we have created the Shoes table without specifying any
Primary key, then later we can enter the statement as follows:
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, instead 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 for the Shoe table. Now we can add the new
primary key as follows:
ALTER TABLE Shoes ADD PRIMARY KEY (Name, Size);
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 the 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;
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 the 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 the
Name column from the table will result in an error and the Name column will not be removed. If
there are no duplicate entries in the Size column, then the Name column will be removed.
Similar will be the case with the Name column, if we try to remove the 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;
DML COMMANDS :
DML stands for Data Manipulation Language. DML commands are used for retrieving, inserting,
modifying/updating or deleting data from a relation. is used to manipulate the data in the
relation. Following are the DML commands :
- INSERT
- SELECT
- UPDATE
- DELETE
INSERT COMMAND
After creating database and relations, we can add data in the relations. INSERT INTO
command is used to enter values in a table. Syntax of insert command is as follows :
INSERT command is used in various ways to insert values within a table. Following points
should be kept in mind while inserting records in a relation. :
- Numeric values may be entered as numerals
- string must be enclosed in single/ double quotes
- Date should be entered in single/double quotes in format ‘yyyy-mm-dd’
- NULL value should be entered as NULL without any quotes. NULL value means blank
value in the table.
Values entered in the column must be in same order as given in the list enclosed with table
name in INSERT command.
For example :
mysql> INSERT INTO STUDENT(RNO,GENDER, LNAME,FNAME) VALUES(8,'F','SHANU',
'DEEPAKSHI');
Above command will enter the values only in specified columns of the table. Remaining columns
of the table will have a NULL value inserted by default.
If we have to enter a record with values for all the attributes(columns) then list of columns is not
specified with table name in the command then we need to enter value for all the attributes of
the table. The order of values must be same as the order of attributes specified in the table
For example :
INSERT INTO STUDENT VALUES(1,'ABHISHEK','NARULA','M', '1998-10-05',98);
It can be observed that the numeric values can be inserted directly while string and date is
entered enclosed within single quotes.
The order of entering the values must be same as the order of attributes defined in the relation.
Main purpose after storing the data in a table is to retrieve the data for generating various
reports. Data from tables can be retrieved/ fetched using Select Command.
SELECT COMMAND :
SELECT command is used to view the data from a relation in a database. It returns a result set
of data/ records from one or more relations.
Syntax of SELECT Command :
SELECT <column name> FROM <table name >;
Command to retrieve single column display
select Rno from STUDENT;
The output displayed the data in same order as the order of columns given in the command.
Command to display all the columns : ‘* ‘ symbol is used to display all the columns of the table.
Select * from Student;
* is the wild card character ( means ALL) that is used to display names of all the columns.
If a column contains repeated values then the select statement gives the result set with
repeated values like if a command is given to display DISTINCT keyword is used to eliminate
repeated values
For example :
Select DISTINCT marks from student;
+---------+
| marks |
+---------+
| 98 |
| 92 |
| 95 |
| 94 |
| 93 |
| 84 |
| NULL |
+---------+
7 rows in set (0.00 sec)
A number of keywords and clauses are used with SELECT statement to retrieve data as per the
requirement. These are discussed below:
ALL
Keyword ALL when used with Select statement is used to display values of all columns in the
row. It displays even the duplicate values.
WHERE Clause
Where clause is used to fetch data based on a criteria/ condition. Criteria can be given using an
expression. Table has many records in it and it is not always desirable to show all the records
every time. At times only certain set of specific rows need to be displayed. based on the criteria.
Keyword WHERE is used for selection of rows with select statement. We can also say that
WHERE clause is used to filter records. It is used to fetch only those records that satisfy a
specified criterion.
Syntax:
For example if we wish to display records of students who have a got marks greater thn we will
90 then following command needs to be entered:
Following set of examples show the use of arithmetic operators for performing calculations :
Arithmetic operators are used to perform calculations over the numeric fields of a table.
For example, if we wish to see the result after adding 10 marks for activity in each record then
what would be the total then this can also be done using expression as shown below:
Another example: in case to view the salary of employees after adding a bonus of 10 percent to
the salary , following command may be used:
Relational Operators
Relational Operators compare two values and gives a result in the form of true of false. Every
row is filtered using the relational operator in the expression in where clause. Given below are
the relational operators used in MySQL alongwith their functions:
These operators are of great help to fetch data on a particular criteria. If we need to display data
of all the employees who belong to city ‘Jaipur’ then following command may be given :
Logical Operators
SQL supports following set of logical operators:
AND, OR, NOT
AND Operator is used with where clause and returns true if both the conditions are true. Those
records are displayed which are true for both the conditions.
For example:
mysql> select fname from student where gender ='f' and marks>90;;
AND operator can be used to fetch records satisfying in a range of values as shown in the
example given below:
mysql> select fname, lname, marks
FROM student
WHERE marks >= 92 and marks<= 95;
In the above query, the output will display records of all the students who have marks greater
than or equal to 92 and less than or equal to 95. Similar result can be obtained using keyword
BETWEEN .
BETWEEN operator
Keyword BETWEEN is used to fetch data based on a range of values on a column. The result
set includes the values of the upper and lower bound given in the range.
For example , following command displays firstname, last name and marks of the students
whose marks are from 92 to 95;
mysql> select fname, lname, marks
FROM student
WHERE marks BETWEEN 92 and 95;
Output will be :
Coachname Game
NOT Operator
Not is used for negation. It returns the result set that is opposite to the given condition
For example : following command displays name and salary of employees whose salary is not
less than 50000.00
For example, following command is to display the records with NULL values in column edesig
from table employee
mysql>select empname, zone from employee where zone IS NULL;
IS operator is used to compare equality with NULL whereas IS NOT may be used for
comparing the values not equal to NULL;
mysql> select empname, zone from employee where zone IS NOT NULL;
Note: the operations = NULL and <> NULL are not defined!
To make the output more user friendly we can give customized heading to column name in the
select command. Keyword AS is used to give column alias in a set of single quotes as shown in
the example below:
For example :
mysql> select rno AS ‘Roll Number’ , fname AS ‘First Name’ , marks
from Student;
Remember : the name of column if for the query only and no changes are made in the original
table.
Output will be :
IN operator helps in removing multiple conditions. Without IN operator the above command
would have been as follows :
mysql>select fname , marks from student
where marks=88 OR marks=92 OR marks=95;
LIKE keyword
LIKE is used for pattern matching and is very useful. Following characters used for applying
pattern matching:
% percent symbol is used to match none or more characters
_ underscore character is used to match occurrence of one character in the string
For example : To search for records having first name starting with letter ‘R’;
output is:
Command to display list of all the students whose name has upto five characters:
Following command displays list of students whose name starts and ends with a specified
letter.
Notice that in case no record matches the given pattern then the query returns empty set on
execution.
Similarly many more patterns may be given as follows :
‘_ _ _ _’ matches any string with exactly four characters
‘S_ _ _ _’ matches any string of length of exactly 5 characters and starts with letter ‘S’
‘S_ _ _ %’ matches any string of length of 4 or more characters and starts with letter ‘S’
‘_ _ _H matches any string of length of exactly 4 characters and terminates with letter ‘H’
‘_ _ _ %’ matches any string with at least three or more characters
‘%in% matches any string which containing ‘in’
ORDER BY
The result set fetched by the query can be displayed in sorted order. The sorting can be on the
basis of any particular column from the table using ORDER BY clause.
Syntax is :
SELECT <column name>, [<column name >…]
FROM <table name>
[ WHERE <condition> ]
ORDER BY < column name> [DESC];
By default the records are displayed in ascending order of the column name. Keyword ASC is
used with ORDER BY clause for displaying the list in ascending order and keyword DESC is
used with ORDER BY clause to display the records in descending order.
Following commands are used to display records in sorted order of marks of students
mysql>select fname, lname, marks
from STUDENT
order by marks;
It can be observed that the output is displayed in the sorted order of marks. NULL value is
displayed first and records are displayed in ascending order.
Following command displays the records in descending order of fname:
mysql> select fname, lname
from STUDENT
ORDER BY fname DESC;
ORDER By clause can be used to sort the records on the basis of two columns also.
Following command displays the result based on order of marks and then on fname.
mysql> select fname, lname , marks from STUDENT
ORDER BY marks ASC, fname DESC;
It can be observed from the above figure that the records are displayed in ascending order of
marks and for records having similar value of marks are sorted on the basis of descending order
of fname.
UPDATE
UPDATE command is used to modify data of records within the table. It is a type of DML and is
used to make changes in the values entered in the table :
Syntax: `
UPDATE <table name>
SET <column name> = <value>, [<column name> = <value> , …]
[WHERE <condition> ];
The command can be used to update one or more columns and WHERE clause is used for
modifying the records that matches a criteria.
For example:
Following command changes the zone from North to East for employees whose city is ‘Jaipur’;
Now with the help of update command we can add values to date of birth and marks for
Deepakshi :
Again the records as displayed and we can see that the changes have been made:
DELETE
Earlier the table was having 12 records and after the execution of the command it has 11 rows.
It may be noticed that record of Saurabh Makania has been removed.
POINTS TO REMEMBER :
Lab exercises:
Consider the following table named "GYM" with details about Fitness products
being sold in the store.
Table Name : GYM
PrCode stores Codes of Products
PrName stores names of Products
(UnitPrice is in Rs.)
Learning Objectives
• 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
Introduction
In our day to day life, we have to give information innumerable times like fill up bank deposit slips
to deposit money or type in username and password to sign in to our mail account and many
more. Forms are means to accept data (input) from us and respond as soon as we perform an
action like clicking on a button or submitting the form. This chapter deals with teaching the basic
process of designing forms in Netbeans and using them to perform simple manipulations using
Java.
NetBeans ID
NetBeans IDE is used to create java applications very easily using the efficient GUI builder. It
allows us to develop applications by dragging and positioning GUI components from a palette
onto a container. The GUI builder automatically takes care of the correct spacing and alignment
of the different components relative to each other. Let us go through the different components of
the NetBeans IDE (Refer to Fig 5.1):
Figure 5.1 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.
5. Palette: Palette contains controls or components used to create GUI applications.
I 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 (Refer to Figure 5.2):
• 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.
F
i
g
u
r
e
5
.
2
P
a
r
e
n
t
a
n
d
Child controls
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 5.3.
Figure 5.3 Project Window Showing Multiple Forms
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 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(Refer Figure 5.4).
Property Description
Any component of GUI front-end (the form itself and the swing containers and controls placed in
the form) of an application is an object. Each of these objects belongs to its corresponding class
predefined in Java. For example, a form is an object of JFrame class, all the textfields are objects
of JTextField class, and so on. Each object has some properties, methods, and events
associated with it using which you can control the object's appearance and behaviour.
Properties of an object are used to specify its appearance on the form. For example, to set the
background colour of a textfield you change its background property; to set its font you change
its font property; and so on.
Methods are used to perform some action on the object. For example to display something in a
textfield you can use its setText() method, to extract the contents of a textfield you can use its
getText() method. Methods can be divided into two categories- getters and setters.
• Getters are the methods which extract some information from the object and return it
to the program. Getters start with the word get. Examples of getters are: getText(),
getForeground(), getModel(), isEditable etc.
• Setters are the methods which set some properties of the object so that the object's
appearance changes. Setters start with the word set. Examples of setters are:
setText(), setForground(), setModel() etc.
Events are the actions which are performed on controls. Examples of events are:
mouseClick, mouseMoved,keyPressed etc. When the user performs any action on a 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 5.5.
Property Description
Method Description
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 5.6 and 5.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
boolean b =<textfield-name>.isEnabled( );
setEditable Sets whether the user can edit the text in the textField. true
if editable else false.
<textfield-name>.setEditable(boolean b);
<textfield-name>.setText(String t);
<textfield-name>.setVisible(boolean b);
PR
Figure 5.6 Properties and Methods of the jTextField
Property Description
Method Description
String result=<label-name>.getText();
isEnabled() Returns true if the component is enabled,else returns false.
boolean b=<label-name>.isEnabled();
<label-name>.setText(String t);
<label-name>.setVisible(boolean b);
The Text Area 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 5.8.
Property Description
RAMMING - A REVIEW
The jPassword component is used to enter confidential input like passwords which are single line.
We can suppress the display of input as this component allows us to input confidential
information like passwords. Each character entered can be replaced by an echo character. By
default, the echo character is the asterisk, *. The properties of jPassword are summarized below:
PROG
Property Description
The radio buttons are used to provide the user several choices and allow 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 can use Combo boxes as they help save space and are
less cumbersome to design as compared to radio button. We can use check box and list when
we want 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
buttonGroup Specifies the name of the group of button to which the jRadioButton
belongs.
ING - A REVIEW
Method Description
jCheckBox is a small box like component that is either marked or unmarked. When it is clicked,
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.
selected Sets the check box as selected if set to true, default is false.
I PROGRANG - A REVIEW
Method Description
getText() Retrieves the text typed in
String str = <checkbox-name>.getText();
jComboBox is like a drop down box - you can click a drop-down arrow and select an option
from a list whereas jList provides a scrollable set of items from which one or more may be
selected. The properties and methods of jComboBox and jList are summarized below:
Property Description
background Sets the background color.
buttongroup Specifies the name of the group of button to which the jComboBox
belongs.
selectedIndex Sets the index number of the element which should be selected by
default.
ROGRAMMING - 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
ROGRAMMING - A REVIEW
Method Description
Object result=
<list-name>.getSelectedValue();
boolean b =
<list-name>.isSelectedIndex(int index);
We use JOptionPane when we want to request information from the user, display information
to the user or a combination of both. It requires an import statement at the top of the program.
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");
OGRAMMING - A REVIEW
showConfirmDialog() Shows a three-button modal dialog that asks the user a
question. User can respond by pressing any of the suitable
buttons.
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:");
Object Oriented Programming follows bottom up approach in program design and emphasizes on
safety and security of data. It helps in wrapping up of data and methods together in a single unit
which is known as data encapsulation. Object Oriented Programming allows some special
features such as polymorphism and inheritance. Polymorphism allows the programmer to give a
generic name to various methods or operators to minimize his memorizing of multiple names.
Inheritance enables the programmer to effectively utilize already established characteristics of a
class in new classes and applications.
The major components of Object Oriented Programming are as follows:
1. Class
2. Object
A class is used to encapsulate data and methods together in a single unit. It helps the
programmer to keep the data members in various visibility modes depending upon what kind of
access needs to be provided in the remaining part of the application. These visibility modes are
classified as private, public and protected. Usually, data members of a class are kept in private or
protected visibility modes and methods are kept in the public visibility mode.
An object is an instance of a class that is capable of holding actual data in memory locations.
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 5.15 to reinstate the
theoretical concepts learnt above.
Figure 5.15 Illustration Showing the Class, Object, Members and
Methods
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.
The 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
5.16.
Figure 5.16 JTextField and JLabel Classes
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.
Variables
Variables are containers used to store the values for some input, intermediate result or
the final result of an operation. The characteristics of a variable are:
• It has a name.
• It is capable of storing values.
• It provides temporary storage.
• It is capable of changing its value during program execution.
However, as different materials require different containers, and so we used different data
types to hold different values. 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 data
types. The data types supported by java are summarized as follows:
Data Types
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.
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.
Operators are symbols that manipulate, combine or compare variables. The operators
available in java are summarized below:
Assignment Operator:
One of the most common operators 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;
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
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:
> greater than Tests if the value of the left expression is greater
than that of the right.
< less than Tests if the value of the left expression is less than
that of the right.
>= greater than or Tests if the value of the left expression is greater
equal to than or equal to that of the right.
<= less than or Tests if the value of the left expression is less
equal to than or equal to that of the right.
Logical Operator:
A logical operator denotes a logical operation. Logical operators and relational operators are
used together to form a complex condition. Logical operators are:
Operator Use Meaning
! !a a is false
Bitwise Operator:
Bitwise operators are used to perform manipulation of individual bits of a number. They can be
used with any of the integral types (char, short, int, etc). They are used when performing
update and query operations of Binary indexed tree.
When we click the Source button, the application's Java source code in the Editor is displayed
with sections of code that are automatically generated by the Netbeans Builder indicated by
gray/blue areas, called Guarded Blocks. Guarded blocks are protected areas that are not
editable in Source view. Note that we can only edit code appearing in the white areas of the
Editor when in Source view.
Executing a File
Now that the code for the first application is ready let us test our first application. To
execute the application simply select Run>Run File or press Shift+F6 as shown in
Figure 5.24.
Figure 5.24 Executing a File
On executing the first example, the window shown in Figure 5.25 will appear. Click
on the button and observe the result.
The window in which we have designed our form is called the Design window and the window
in which we have written the code is called the Source window. We can easily switch between
the two views by simply clicking on the relevant tab as displayed in Figure 5.22.
Changing Properties of Components
Each component of our application including the form has certain attributes associated with it.
The Properties Window displays the names and values of the attributes (properties) of the
currently selected component. We can edit the values of most properties in the Properties
window.
Now when we execute the file the button with the changed text appears as shown in Figure
5.25.
Observe the Figure 5.30 carefully. we have used a new component - a label and the two text
fields. A label is a component which is used to display simple text or as a label for another
component. Out of the two text fields one of them has a white background while the other has
the same background colour as the form. The difference in the background colour tells us that
one of the text field is editable while the other is not. In simple words editable means that the
user can change the text displayed in the text field at run time. The text field at the top has to
accept the name of the user and is editable. The text field at the bottom has to display the
greeting and is non-editable.
Figure 5.31 displays the properties of both the text fields.
After completing the designing of the form, now we are ready to add the code. Remember that
we had to use the getText() method in our code. Again double click on the three separate
buttons one by one to attach relevant code to each one of them. Observe the coding given in
Figure 5.33.
The code teaches us another useful method - getText(). This is used to return the text
contained in the referred text component. It is generally used to retrieve the value typed by the
user in a textbox or label. The syntax for this method is given below:
Syntax:
jtextField1.getText()
This command is used to retrieve the value of the text Field named jtextField1.
Let us now understand the code. We want to display the message in the second text field
along with the name of the user which has been entered in the first text field.
jTextField1.getText()
● Retrieves the name entered by the user in the first text field using getText().
"Good Morning" + jTextField1.getText()
● The message "Good Morning" is concatenated with the name retrieved from the first
text field using the + symbol.
jTextField2.setText("Good Morning" + jTextField1.getText())
● The display text of the second text field is set to the concatenated message
using setText().
Figure 5.34 displays an alternative method of concatenating the message and the contents of
the text field.
Figure 5.34 Code to Display Personalized Time Based Greeting on Click of a Button
using concat() method
This alternate uses the concat() method to add the two strings together. The syntax of this
method is:
Syntax:
string1.concat(string2)
This will result in adding the string2 at the end of the string1. For example: "sham".concat("poo")
returns shampoo
And
"to".concat("get").concat("her") returns together
Finally, our code is ready for execution. Figure 5.35 displays the output when the user enters
the name and clicks on the Morning button.
After both the radio buttons have been associated together, clicking on any one of them will
show an association between them informing us that they belong to a group. Add one more
non-editable text field to display the name along with the title. Double click on each of the two
radio buttons one by one to associate them with the appropriate code displayed in Figure 5.37.
Figure 5.38 Code for displaying Multiline Text in a Text Area on the click of a Button
Figure 5.39 shows the sample output of the code given in Figure 5.38.
Figure 5.41 code to display the message on the click of the LOGIN button
In all the previous examples we have been doing text manipulation. Let us now do some
simple computations and calculations. Design the form as shown in Figure 5.42. The form
components are:
● 1 editable text field to input the price per Apple
● 1 non-editable text field to display the amount to be paid
● 3 buttons, one for calculating and displaying the price of one dozen apples, one for
calculating and displaying the price of two dozen apples and one to exit out of the
application.
● 2 labels to guide the user what information is to be added.
Figure 5.42 Price Calculator
Let us first analyze the problem so that we can easily write the one line code required for all
three buttons.
● The first button with the "One Dozen" display text has to calculate the price of one
dozen apples and display it in the second text field. To calculate the price of one dozen
apples, we need to know the price of one apple. This is given in the first text field. So
we need to retrieve the value of the first text field. After retrieving the value we will
simply multiply it by 12 and display the answer in the second text field.
● The second button with the "Two Dozen" display text has to calculate the price of two
dozen apples and display it in the second text field. So the process remains similar to
the first button but only while calculating we will multiply the price of one apple by 24
and display the answer in the second text field.
● The third button with the "STOP" display text has to simply end the application.
Enter the code for each button separately as shown in Figure 5.43.
Figure 5.45 Code for the Amount Calculator Using Numbers with Decimals
The code has introduced us to one new method:
● Double.parseDouble() - to convert a value to Double type We are already familiar with
setText(), getText()and toString() so now we are ready to understand the code.
jTextField1.getText() and jTextField2.getText()
● Retrieves the value entered by the user in the first and second text fields respectively
using getText(). These values by default are treated as strings i.e. a group of characters
and not as numbers
Double.parseDouble( jTextField1.getText()) and
Double.parseDouble( jTextField2.getText())
● The string values need to be converted to numbers with decimals and this is achieved
using the parseDouble() method. After converting both the values they are multiplied to
get the total amount payable.
Double.toString(Double.parseDouble( jTextField1.getText()) *
Double.parseDouble( jTextField2.getText()))
● The value calculated is a number with decimals which is to be displayed in a text field. So
before displaying it needs to be converted to a string type and this is achieved using the
toString() method.
jTextField3.setText(Double.toString(Double.parseDouble( jTextField1.getText()) *
Double.parseDouble( jTextField2.getText()))
● The converted value is displayed in the third text field using the setText() method.
Relation between a Project, Form and Components
Remember each project can have multiple forms and this fact is clear from the Projects
window as shown in Figure 5.46.
Variable Declaration
We have learnt that variables are capable of storing values, which we need to use. To
reference a variable, it should have a name. Moreover, variables in java can only accept a
value that matches its data type. So before we use a variable we must decide on its name
and its data type. Giving this information to the language compiler is called variable
declaration. Thus, the declaration of a variable tells us about the name of the variable which is
necessary to reference it, the type of data it will store and optionally an initial value. Given
below are some commonly used ways of variable declaration.
● Keywords or words, which have special meaning in java, should not be used as
the variable names.
● Variable names should be short and meaningful.
● All variable names must begin with a letter, an underscore (_) or a dollar sign ($).
The convention is to always use a letter and avoid starting variable names with
underscore (_) and dollar sign ($).
● After the first initial letter, variable names may contain letters and digits (0 to
● 9) and (_,$), but no spaces or special characters are allowed.
Using the above conventions and rules following is an indicative list of acceptable and
unacceptable variable names.
Acceptable Variable Names - Grade, Test_Grade, TestGrade
Java variable names are case sensitive, so sum1 and SUM1 aren't the same
variable.
As is clear from the sample run, we need to concatenate the message and the selected
character depending upon the button clicked by the user. Let us now design the application:
First add a new JFrame form and set its title property to "Magic Text". Design the form as
shown in Figure 5.48 with the following components:
▪ one editable text field to accept the message
▪ five buttons - four to concatenate message with different characters and one to exit
from the application
▪ one non-editable text field to display the concatenated message
Change the properties of the components as learnt in the previous chapter so that the form
looks exactly like the one displayed in Figure 5.48. The next step is to associate code with the
all the buttons. Double click on the buttons one by one in the design window to reach at the
point in the source window where the code needs to be written. Add the code for each of the
buttons shown as follows.
▪ four buttons to decide the operation, one button to reset the fields and one
button to exit out of the application.
▪ one non-editable text field to display the result.
When the user enters two numbers and clicks on the + button, the sum of the numbers is
displayed in the jtextField3 which has been disabled (by setting its editable property to false) as
shown in Figure 5.49.
When the user clicks on the RESET button the contents of all the Text Fields are cleared.
Now write the code for each button of the basic calculator shown as follows:
steps of computation remain the same. So we will explain one (coding for the first button) in
detail here:
double Number1,Number2,Result;
Number1=Double.parseDouble(jTextField1.getText()); and
Number2=Double.parseDouble(jTextField2.getText());
● retrieves the value entered by the user in the first and second text field using
getText(). These values by default are treated as strings i.e. a group of
characters and not as a number so the string values need to be converted to a
double type and this is achieved using the parseDouble() method. After
converting it to a double type the values are assigned to the variables declared in
the first line of code
Result=Number1+Number2;
● The two values stored in the variables are added and the calculated value is
stored in the variable Result.
jTextField3.setText(Double.toString(Result));
● The value stored in the variable Result is of type double so it is first converted to
type string using the toString() method and then the display text of the third text
field is set to the converted value using setText().
The working of the other three buttons (second, third and fourth) is similar to the one
explained above. We are already familiar with the working of the STOP button so 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.
In all the applications developed so far we have used a single type of data and done simple
calculations. Next let us explore the use of multiple data types and using these data types try
to perform complex calculations.
Observe the form shown in Figure 5.50 and design a similar form.
The aim of the application is to accept the principal amount, rate and time in three separate
text fields and calculate the simple interest on the click of a button. The calculated interest is
displayed in a disabled text field. The coding for the same is given in Figure 5.51.
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;
}
RAMMING -REVIEW
Points to remember about if statement:
• 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.
Let us now design another application: “Vote Eligibility Checker” where we are accepting the
age from the user and we want to validate whether the person is eligible to vote or not. We
are accepting the age of the user in a text field and testing whether the age entered by the
user is greater than 18 or not. If the age is greater than 18 then the message "You are
eligible to VOTE" is displayed. If the age is less than then the message “You are NOT
eligible to VOTE” is displayed. In such situations when we have to take action on the basis
of outcome of a condition, we need to use a Selection statement. Design the form and set
the properties of the components so that the form looks exactly like the one displayed in
figure 5.52.
Private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Code to check eligibility to vote with else condition: if
(Integer.parseInt(jTextField1.getText())>=18)
JOptionPane.showMessageDialog(null,"You are eligible To
VOTE");
else
JOptionPane.showMessageDialog(null,"You are NOT eligible
To VOTE");
}
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.
if (Integer.parseInt(jTextField1.getText()) >=18)
● check whether the value retrieved from the text field is greater than or equal to 18
or not. The if statement is used to check the condition and if the condition
evaluates to true then we specify what action is to be taken
if (Integer.parseInt(jTextField1.getText()) >=18)
JOptionPane.showMessageDialog(null, "You are eligible to VOTE")
● This if statement is used to check whether the value retrieved from the text field
is greater than or equal to 18 or not and if it is then it displays the message
"You are eligible to VOTE" using the showMessageDialog() method.
else
JOptionPane.showMessageDialog(null,"You are NOT eligible to VOTE");
● The else statement is executed if the value retrieved from the text field is less
than 18 and if it is then it displays the message "You are NOT eligible to VOTE"
using the showMessageDialog() method.
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;
}
Let us now develop another application called the Week Day Finder in which we will learn how
to use if statement when we have multiple test conditions. The Week Day Finder will display
the name of the week in a disabled text field depending upon the day selected by the user.
The days are displayed as radio button options, which have to be selected. So, the form will
have 7 radio buttons and depending on the button selected the day of the week will be
displayed.
Figure 5.53 Sample Run of the Week Day Finder
Design the form as shown in Figure 5.53. and set the properties of the components
according to the functionality required as shown in Figure 5.53. Monday is displayed when
the radio button corresponding to Day One is selected as shown in Figure 5.53 as it is the
first day of the week. If we select the radio button corresponding to Day Six then Saturday is
displayed, as it is the sixth day of the week.
It is clear from the above form that we have to test for multiple conditions. If jRadioButton1 is
selected then Monday will be displayed and if jRadioButton2 is selected then Tuesday will
be displayed and so on. All the select conditions will be checked from top to bottom and
wherever the condition evaluates to true, the statements corresponding to that jRadioButton
will get executed. What happens in case none of the jRadioButton is selected?
After understanding the working let us now write the code for the Week
Day Finder application as shown in Figure 5.54.
F
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{ i
g
u // To find the day of the
week if
(jRadioButton1.isSelected())
jTextField1.setText("Monday");
else if (jRadioButton2.isSelected())
jTextField1.setText("Tuesday");
else if (jRadioButton3.isSelected())
jTextField1.setText("Wednesday"
); else if
(jRadioButton4.isSelected())
jTextField1.setText("Thursday")
; else if (jRadioButton5.isSelected())
jTextField1.setText("Friday");
else if (jRadioButton6.isSelected())
jTextField1.setText("Saturday")
; else if (jRadioButton7.isSelected())
jTextField1.setText("Sunda
y"); else
jTextField1.setText("Day - Not Selected");
}
The above code introduces us to a new method called isSelected(). This method is
used to check whether a particular radio button is selected or not. The syntax of this
method is given below:
Syntax:
jRadioButton.isSelected()
This method returns a boolean value i.e. true or false. The true indicates that the
radio button is selected and false indicates that the radio button is not selected.
Let us now understand the code in detail. Since the code in each subsequent else is
almost the same except the display text, so we will try and understand the first
three lines.
if (jRadioButton1.isSelected())
● check whether the first radio button is selected or not
if (jRadioButton1.isSelected()) jTextField1.setText("Monday")
● Display "Monday" in the text field if the first radio button is
selected
if (jRadioButton1.isSelected()) jTextField1.setText("Monday")
else if (jRadioButton2.isSelected())
● If the first radio button is not selected then check whether the
second radio button is selected or not
Note that to handle multiple conditions, we have used a series of if-else
statements. Such a if else statement is called nested if else statement. In
this form the if statement checks each of the conditions one by one from
top to bottom until it finds one that is true. In case none of the conditions
are true then the statement corresponding to the last else is executed.
Therefore, in case none of the jRadioButton is selected then "Day - Not
Selected" will be displayed.
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:
ING
switch (Variable/Expression)
{
case Value1:statements1 ;
break ;
case Value2:statements2 ;
break ;
.
.
default:statements3 ;
}
After understanding the working of switch statement, let us now develop a discount
calculator using the switch statement. Design the form as shown in Figure 6.30. The
Customer is given a discount on the Bill Amount depending upon the Customer Type
selected from the combo box. Discount is calculated as follows:
Customer Type Discount
Platinum 30%
Gold 20%
Silver 10%
When the application is executed the discount amount is deducted from the Bill Amount
depending upon the Customer Type selected by the user.
When Customer Type is Silver the customer gets a discount of 10% as shown in figure 5.55.
When Customer Type is Gold the customer gets a discount of 20% and when
Customer Type is Platinum the customer gets a discount of 30% on the Bill Amount.
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:
experience."; break;
default: comment =
"Oops -- something is wrong with this code.";
Equivalent if statement
1,or 2. if (choice == 0)
experience"; 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.
Points to Remember:
• NetBeans is an IDE using which we can develop GUI applications in Java.
• NetBeans provides various components used to create a GUI front-end
interface.
• GUI components' appearance and behaviour is controlled by their
properties and methods.
• We should use meaningful names for controls on the form and variables
in the code. It makes programming convenient.
• Some useful Data Types supported in Java are: int, double, char and boolean.
• String is an Object (reference) type supported in Java.
• A variable must be declared before it can be used.
• Different types of operators are available in Java. Operators are used to
perform various operations on data.
• The if statement selects among a set of statements depending on the
value of a controlling expression.
EXERCISES
1. What will be the final value of sum1 after the execution of the program given below?
int sum1 = 3; sum1=sum1+1;
jTextField1.setText(""+sum1);
sum1=sum1+1; jTextField2.setText(""+sum1);
sum1=sum1+1; jTextField3.setText(""+(sum1));
sum1=sum1+1;
jTextField4.setText(""+sum1);
jTextField5.setText(""+sum1);
a. 5 b. 6
c. 4 d. 7
if (anumber >=10)
jLabel1.setText("first string");
else
jLabel1.setText("second string");
jLabel2.setText("third string");
4. If there is more than one statement in the block of a if statement, 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;
vii) a >= c
a) IDE
b) Inspector Window
c) Form
2. Differentiate between :
61
LineWrap WrapStyleWord
8. Write and explain two methods each of check box and radio button.
AMMING - A REVIEW
LAB EXERCISES
1. Design a GUI application in which the user enters a three digit 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 number from the user in a text field and print using
option pane whether it is a positive even number 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.
6. Design a GUI application in java to convert kilograms into grams, litres into milliliters,
rupees into paisa using combobox and text fields.
School - 20%
Customer - 5%
PROGRAMMING - A REVIEW
8. A networking company decided to computerize its employee salary . Develop an
62
application to store employee's personal data which will be saved in the back end. The
front end should accept Name, Father's Name, Mother's Name, Address, Gender, Basic
Salary, Medical and Conveyance. Calculate gross and net salary.
Basic DA HRA
63