You are on page 1of 79

INSERVICE COURSE ( I SPELL ) 2017-18 , JAIPUR REGION

STUDY MATRIAL

CHAPTER 01
Computer Networking

What is a Network?
The collection of interconnected computers is called a computer network.
Two computers are said to be interconnected if they are capable of sharing
and exchanging information.

Why it is needed?
Resource Sharing
Reliability
Cost Factor
Communication Medium

Resource Sharing means to make all programs, data and peripherals available to
anyone on the network irrespective of the physical location of the resources and
the user.

Reliability means to keep the copy of a file on two or more different machines,so if
one of them is unavailable (due to some hardware crash or any other) them its other
copy can be used.

Cost factor means it greatly reduces the cost since the resources can be shared

Communication Medium means one can send messages and whatever


thechanges at one end are done can be immediately noticed at another.

1|Page
EVOLUTION OF NETWORKING

1969 - First network came into existence


ARPANET (ADVANCED RESEARCH PROJECT AGENCY NETWORK)

MID 80’S - NSFNET (NATIONAL SCIENCE FOUNDATION NETWORK)

Diagrammatic presentation for slow learners

1980
NSFnet

a high capacity network to be


used strictly for academic and
engineering research.
1969 1990
ARPANET INTERNET

to connect computers at U.S. the internetworking of


defense and different ARPANET, NSFnet and other
universities. private networks

2|Page
INTERNET IS THE NETWORK OF NETWORKS.

SWITCHING TECHNIQUES

Switching techniques are used for transmitting data across networks.

Different types are :


Circuit Switching
Message Switching
Packet Switching

CIRCUIT SWITCHING

Circuit switching is the transmission technology that has been used sincethe first
communication networks in the nineteenth century.
First the complete physical connection between two computers is established and then
the data are transmitted from the source computer tothe destination.

When a call is placed the switching equipment within the system seeks out a physical
copper path all the way from the sender to the receiver.
It is must to setup an end-to-end connection between computers before any data
can be sent.
The circuit is terminated when the connection is closed.
In circuit switching, resources remain allocated during the full length of a
communication, after a circuit is established and until the circuit is terminated and
the allocated resources are freed.

MESSAGE SWITCHING

In this the source computer sends data or the message to the switchingcircuit
which stores the data in its buffer.
Then using any free link to the switching circuit the data is send to the switching
circuit.
Entire message is sent to the destination. It reaches through different
intermediate nodes following the “store and forward” approach.
No dedicated connection is required.

PACKET SWITCHING
• Conceived in the 1960's, packet switching is a more recent technology than
circuit switching.
• Packet switching introduces the idea of cutting data i.e. at the source entire
message is broken in smaller pieces called packets which are transmitted over a
network without any resource being allocated.
• Then each packet is transmitted and each packet may follow any rout available and
at destination packets may reach in random order.
• If no data is available at the sender at some point during a communication, then no
packet is transmitted over the network and no resources are wasted.
• At the destination when all packets are received they are merged to form the
original message.
• In packet switching all the packets of fixed size are stored in main memory.

3|Page
DATA COMMUNICATION TERMINOLOGIES

Data channel The information / data carry from one end


to another in the network by channel.

Baud & bits per second (bps) It’s used to measurement for the
information carry of a communication
channel.
Measurement Units :-
bit
1 Byte= 8 bits
1 KBPS ( Kilo Byte Per Second)= 1024
Bytes ,
1 Kbps (kilobits Per Second) = 1024 bits,
1 Mbps ( Mega bits Per Second )=1024
Kbps

Bandwidth It is amount of information transmitted


or receives per unit time.
It is measuring in Kbps/Mbps etc unit.

TRANSMISSION MEDIA

Data is transmitted over copper wires, fiber optic cable, radio and microwaves. The
term 'media' is used to generically refer to the physical connectors, wires or devices
used to plug things together.

Basic Communications Media Types


Copper
Unshielded Twisted Pair (UTP)
Shielded Twisted Pair (STP)
Coaxial Cable (Thinnet, Thicknet)
Fiber Optic
Single-mode
Multi-mode
Infrared
Radio & Microwave

Twisted Pair Cable

These cables consist of two insulated copper wires twisted around each other in a
double helix.
Twisting of wires reduces crosstalk which is bleeding of a signal from one wire to
another.

4|Page
TYPES:
1. Unshielded Twisted Pair (UTP)
2. Shielded Twisted Pair (STP

STP offers greater protection from interference and crosstalk due to shielding.
But it is heavier and costlier than UTP.

USE:
1. In local telephone communication
2. For digital data transmission over short distances upto 1 km

Advantages:
Easy to install and maintain
Simple
Inexpensive
Low weight
Suitable for small (Local) Networks

Disadvantages:
Not suitable for long distance due to high attenuation.
Low bandwidth support.
Low Speed

Coaxial cable

Coaxial cable consists of a solid copper wire core surrounded by a plastic cladding
shielded in a wire mesh.
Shield prevents the noise by redirecting it to ground.

TYPES:
Coaxial cable comes in two sizes which are called thinnet and thicknet.
Thicknet : segment length upto 500 m
Thinnet : segment length upto 185 m

USE:
In TV channel communication

Advantages:

5|Page
Better than twisted wire cable.
Popular for TV networks.
Offers higher bandwidth & Speed

Disadvantages:
Expensive than twisted wires.
Not compatible with twisted wire cable.
OPTICAL FIBRES

Thin strands of glass or glass like material designed to carry light from one source to
another.
Source converts (Modulates) the data signal into light using LED (Light Emitting Diodes)
or LASER diodes and send it over the Optical fiber.
It consists of three parts:
1. The core: glass or plastic through which the light travels.
2. The cladding : covers the core and reflects light back to the core
3. Protective coating : protects the fiber

Advantages
Not affected by any kind of noise.
High transmission capacity
Speed of Light
Suitable for broadband communication

Disadvantages
Installation requires care.
Connecting two Optical fibers is difficult.
Optical fibers are more difficult to solder
Most expensive

Microwaves
Microwaves are transmitted from the transmitters placed at very high towers to the
receivers at a long distance.

Microwaves are transmitted in line of sight fashion, and also propagated through the

6|Page
surfaces.
Advantages
• Maintenance easy than cables.
• Suitable when cable can not be used.

Disadvantages
• Repeaters are required for long distance communication.
• Less Bandwidth available.

Satellite
Geostationary satellites are placed around 36000 KM away from the earth’s surface

In satellite communication transmitting station transmits the signals to the satellite. (It is called
up-linking)

After receiving the signals (microwaves) it amplifies them and transmit back to earth in whole
visibility area.

Receiving stations at different places can receive these signals. (It is called down-linking).

Advantage

7|Page
• Area coverage is too large
Disadvantage
• High investment

NETWORK DEVICES

MODEM

A modem is a computer peripheral that allows you to connect and communicate with other
computers via telephone lines.

Modem means Modulation/ Demodulation.

Modulation: A modem changes the digital data from your computer into analog data, a
format that can be carried by telephone lines.

Demodulation: The modem receiving the call then changes the analog signal back into
digital data that the computer can digest.

The shift of digital data into analog data and back again, allows two computers to speak
with one another.

External Modem

Internal Modem

8|Page
RJ- 45 Connector

RJ-45 is short for Registered Jack-45. It is an eight wire connector which is commonly used to
connect computers on the local area networks i.e., LAN.

Network Interface Cards (Ethernet Card)

A network card, network adapter or NIC (network interface card) is a piece of computer
hardware designed to allow computers to communicate over a computer network. It
provides physical access to a networking medium andoften provides a low-level
addressing system through the use of MAC addresses. It allows users to connect to each
other either by using cables or wirelessly.

Repeaters

A repeater is an electronic device that receives a signal and retransmits it at a higher


level or higher power, or onto the other side of an obstruction, so that the signal can
cover longer distances without degradation. In most twisted pair Ethernet
configurations, repeaters are required for cable runs longer than 100 meters.

Hubs

9|Page
A hub contains multiple ports. When a packet arrives at one port, it is copied to all the
ports of the hub. When the packets are copied, the destination address in the frame
does not change to a broadcast address. It does this in a rudimentary way, it simply
copies the data to all of the Nodes connected to the hub.

Bridges

A network bridge connects multiple network segments at the data link layer (layer 2) of
the OSI model. Bridges do not promiscuously copy traffic to all ports, as hubs do, but
learn which MAC addresses are reachable through specific ports. Once the bridge
associates a port and an address, it will send traffic for that address only to that port.
Bridges do send broadcasts to all ports except the one on which the broadcast was
received.
Bridges learn the association of ports and addresses by examining the source address
of frames that it sees on various ports. Once a frame arrives through a port, its source
address is stored and the bridge assumes that MAC address is associated with that
port. The first time that a previously unknown destination address is seen, the bridge
will forward the frame to all ports other than the one on which the frame arrived.
Bridges come in three basic types:
Local bridges: Directly connect local area networks (LANs)
Remote bridges: Can be used to create a wide area network (WAN) link between LANs.
Remote bridges, where the connecting link is slower than the end networks, largely
have been replaced by routers.
Wireless bridges: Can be used to join LANs or connect remote stations to LANs.

Switches

switch is a device that performs switching. Specifically, it forwards and filters OSI layer 2
datagrams (chunk of data communication) between ports (connected cables) based on
the Mac-Addresses in the packets. This is distinct from a hub in that it only forwards the
datagrams to the ports involved in the communications rather than all ports connected.
Strictly speaking, a switch is not capable of routing traffic based on IP address (layer 3)
which is necessary for communicating between network segments or within a large or
complex LAN. Some switches are capable of routing based on IP addresses but are still
called switches as a marketing term. A switch normally has numerous ports with the
intention that most or all of the network be connected directly to a switch, or another
switch that is in turn connected to a switch.

10 | P a g e
Switches is a marketing term that encompasses routers and bridges, as well as devices
that may distribute traffic on load or by application content (e.g., a Web URL identifier).

Routers

routers are networking devices that forward data packets between networks using
headers and forwarding tables to determine the best path to forward the packets.
Routers work at the network layer of the TCP/IP model or layer 3 of the OSI model.
Routers also provide interconnectivity between like and unlike media (RFC 1812). This is
accomplished by examining the Header of a data packet, and making a decision on the
next hop to which it should be sent (RFC 1812) They use preconfigured static routes,
status of their hardware interfaces, and routing protocols to select the best route
between any two subnets. A router is connected to at least two networks, commonly
two LANs or WANs or a LAN and its ISP's network. Some DSL and cable modems, for
home (and even office) use, have been integrated with routers to allow multiple
home/office computers to access the Internet through the same connection. Many of
these new devices also consist of wireless access points (waps) or wireless routers to
allow for IEEE 802b/g wireless enabled devices to connect to the network without the
need for a cabled connection.

GATEWAY

A Gateway is a network device that connects dissimilar networks. It established an


intelligent connection between a local area network and external networks with completely
different structures.

11 | P a g e
NETWORK TOPOLOGIES AND TYPES OF NETWORK TOPOLOGY

Computer networks may be classified according to the network topology upon which
the network is based, such as Bus network, Star network, Ring network,Mesh network,
Star-bus network, Tree or Hierarchical topology network, etc.
Network Topology signifies the way in which intelligent devices in the network see
their logical relations to one another. The use of the term "logical" here is significant.
That is, network topology is independent of the "physical" layout of the network.
Even if networked computers are physically placed in a linear arrangement, if they
are connected via a hub, the network has a Star topology, rather than a Bus
Topology. In this regard the visual and operational characteristics of a network are
distinct; the logical network topology is not necessarily the same as the physical
layout

Mesh Topology

The value of fully meshed networks is proportional to the exponent of the number of
subscribers, assuming that communicating groups of any two endpoints, up to and
including all the end points.

12 | P a g e
Star Topology
The type of network topology in which each of the nodes of the network is connected
to a central node with a point-to-point link in a 'hub' and 'spoke' fashion, the central
node being the 'hub' and the nodes that are attached to the central node being the
'spokes' (e.g., a collection of point-to-point links from the peripheral nodes that
converge at a central node) – all data that is transmitted between nodes in the
network is transmitted to this central node, which is usually some type of device that
then retransmits the data to some or all of the other nodes in the network, although
the central node may also be a simple common connection point (such as a 'punch-
down' block) without any active device to repeat the signals.

Server

Bus Topology

The ty pe of network to pology in which all of the nodes of the network are
connected to a common transmission medium which has exactly two endpoints (this is
the 'bus', which is also commonly referred to as the backbone, or trunk) – all data that
is transmitted between nodes in the network is transmitted over this common
transmission medium and is able to be received by all nodes in the network virtually
simultaneously (disregarding propagation delays).

13 | P a g e
Ring Topology

The type of network topology in which each of the nodes of the network is connected
to two other nodes in the network and with the first and last nodes being connected to
each other, forming a ring – all data that is transmitted between nodes in the network
travels from one node to the next node in a circular manner and the data generally
flows in a single direction only.

Server

COMPTER NETWORKS

A communications network is two or more computers connected to share data and


resources are “networked.” The simple idea behind computer networking is to allow
users to access more information and give them access to devices not directly
attached to their “local” system, such as printers or storage devices

14 | P a g e
Local Area Network (LAN)

A network covering a small geographic area, like a home, office, or building. Current
LANs are most likely to be based on Ethernet technology. For example, a library will
have a wired or a communications network is two or more computers connected to
share data and resources are “networked.” The simple idea behind computer
networking is to allow users to access more information and give them access to devices
not directly attached to their “local” system, such as printers or storage devices
Users to interconnect local devices (e.g., printers and servers) and to connect to the
internet. All of the PCs in the library are connected by category 5 (Cat5)cable, running
the IEEE 802.3 protocol through a system of interconnection devices and eventually
connect to the internet. The cables to the servers are on Cat 5e enhanced cable, which
will support IEEE 802.3 at 1 Gbit/s.
The staff computers (bright green in the figure) can get to the color printer, checkout
records, and the academic network and the Internet. All user computers can get to the
Internet and the card catalog. Each workgroup can get to its local printer. Note that the
printers are not accessible from outside their workgroup.

Metropolitan Area Network (MAN)

A Metropolitan Area Network is a network that connects two or more Local Area
Networks or Campus Area Networks together but does not extend beyond the
boundaries of the immediate town, city, or metropolitan area. Multiple routers,
switches & hubs are connected to create a MAN.

Wide Area Network (WAN)

15 | P a g e
WAN is a data communications network that covers a relatively broad geographic area
(i.e. one city to another and one country to another country) and that often uses
transmission facilities provided by common carriers, such as telephone companies.
WAN technologies generally function at the lower three layers of the

OSI reference model: the physical layer, the data link layer, and the networklayer.

16 | P a g e
NETWORK PROTPCOL

PROTOCOLS
A protocol means the rules that are applicable for a network.
It defines the standardized format for data packets, techniques for detecting
and correcting errors and so on.
A protocol is a formal description of message formats and the rules that two or more
machines must follow to exchange those messages.
E.g. using library books.

Types of protocols are:

1. HTTP
2. FTP
3. TCP/IP
4. SLIP/PPP

Hypertext Transfer Protocol (HTTP)is a communications protocol for thetransfer of


information on the intranet and the World Wide Web. Its original purpose was to
provide a way to publish and retrieve hypertext pages over the Internet.
HTTP is a request/response standard between a client and a server. A client is the end-
user; the server is the web site.

FTP (File Transfer Protocol) is the simplest and most secure way toexchange
files over the Internet. The objectives of FTP are:
1. To promote sharing of files (computer programs and/or data).
2. To encourage indirect or implicit use of remote computers.
3. To shield a user from variations in file storage systems among different hosts.
4. To transfer data reliably, and efficiently.
TCP/IP (Transmission Control Protocol / Internet Protocol)

TCP -is responsible for verifying the correct delivery of data from client to server.Data
can be lost in the intermediate network. TCP adds support to detect errors or lost data
and to trigger retransmission until the data is correctly and completely received.

IP -is responsible for moving packet of data from node to node. IP forwards eachpacket
based on a four byte destination address (the IP number). The Internet authorities assign
ranges of numbers to different organizations. The organizations assign groups of their
numbers to departments. IP operates on gateway machines that move data from
department to organization to region and then around the world.

TCP and IP were developed by a Department of Defense (DOD) research project to connect
a number different networks designed by different vendors into a network of networks.

17 | P a g e
Several computers in a small department can use TCP/IP (along with other protocols) on a
single LAN. The IP component provides routing from the department to the enterprise
network, then to regional networks, and finally to the global Internet.

SLIP/PPP (Serial Line Internet Protocol / Point to Point Protocol)


SLIP/PPP provides the ability to transport TCP/IP traffic ever serial line between two
computers.

The home user’s computer has a communications link to the internet.


The home user’s computer has the networking software that can speak TCP/IP with other
computers on the Internet.
The home user’s computer has an identifying address (IP address) at which it can be
contacted by other computers on Internet.

E.g. dial up connection.

Telnet-
It is an older internet utility that lets us log on to remote computer system. It also facilitates
for terminal emulation purpose. Terminal emulation means using a pc like a mainframe
computer through networking.
(i) Run telnet client-
Type telnet in run dialog box.
(ii) Connect to telnet site -specify the host name, port and terminal type.
(iii) Start browsing- surf the shown site with provided instruction.
(iv) Finally disconnect-press Alt+f4

WIRELESS/MOBILE COMPUTING

Wireless communication is simply data communication without the use of landlines. Mobile
computing means that the computing device is not continuously connected to the base or
central network.

1. GSM(Global System for Mobile communication): it is leading digital cellularsystem.


In covered areas, cell phone users can buy one phone that will work any where the
standard is supported. It uses narrowband TDMA, which allows eight simultaneous calls
on the same radio frequency.

2. CDMA(Code Division Multiple Access): it is a digital cellular technology thatuses


spread-spectrum techniques. CDMA does not assign a specific frequency to each user.
Instead ,every channel uses the full available spectrum.

3. WLL(Wireless in Local Loop) : WLL is a system that connects subscribers to thepublic


switched telephone network using radio signals as a substitute for other connecting media.

4. Email(Electronic Mail): Email is sending and receiving messages by computer.

5. Chat: Online textual talk in real time , is called Chatting.

18 | P a g e
6. Video Conferencing: a two way videophone conversation among
multipleparticipants is called video conferencing.

7. SMS(Short Message Service): SMS is the transmission of short text messagesto and from
a mobile pone, fax machine and or IP address.

8. 3G and EDGE: 3G is a specification for the third generation of


mobilecommunication of mobile communication technology. 3G promises
increased bandwidth, up to 384 Kbps when a device is stationary.

EDGE(Enhanced Data rates for Global Evolution ) is a radio based high speed
mobile data standard.

NETWORK SECURITY CONCEPTS

While ensuring network security, the concerns are to make sure that only legal or authorized
users and program gain access to information resources like databases.
Problems encountered under network security can be summarized as follows.
(i) Physical security holes-when individuals gain unauthorized physical access to acomputer and
temper with files.
(ii) Software security holes-when badly written programs or privileged software
arecompromised into doing things that they should not be doing
(iii) Inconsistent usage holes -when a system administrator assembles a
combination of hardware and software such that the system is seriously flawed from a
security point of view

Under this type of security, mechanism like authorization, authentication, encryption,


biometrics and firewalls are implemented.

Protection methods
1 Authorization- Authorization confirms the service requestor's credentials.It determines
if the service requestor is entitled to perform that operation.
2 Authentication -Each entity involved in using a web service the requestor,
the provider and the broker(if there is one) - is what it
actually claims to be.
conversion of the form of data from one form to another form.
3 Encryption –
4 Biometric System - involves unique aspect of a person's body
such asFinger-
prints, retinal patterns etc to establish his/her Identity.
5 Firewall A system designed to prevent unauthorized access to or from a private
network is called firewall. it can be implemented in both
hardware and software or combination or both.

There are several types of firewall techniques-


* Packet filter- accepts or rejects of packets based on user defined rules.

19 | P a g e
* Application gateway- security mechanism to specific application like FTP and Telnet servers.
* Circuit level gateway - applies security mechanism when a connection is established.

Intercepts all messages entering and leaving the network.

Related Terms:

Cookies - Cookies are messages that a web server transmits to a web browser so thatthe web
server can keep track of the user’s activity on a specific web site.

Cookies have few parameters name, value, expiration date

Hackers and crackers -


Hackers are more interested in gaining knowledge about computer systems and possibly using
this knowledge for playful pranks.
Crackers are the malicious programmers who break into secure systems.

Cyber Law -
It is a generic term, which refers to all the legal and regulatory aspects of internet and the
World Wide Web.

WEB SERVERS

WWW (WORLD WIDE WEB)


It is a small part of Internet. It is a kind of Application of internet.
It is a set of protocols that allows us to access any document on the Net through a
naming system based on URLS. Internet was mainly used for obtaining textual
information. But post-WWW the internet popularity grew tremendously because of
graphic intensive nature of www.

Attributes of WWW
(i) User friendly- www resources can be easily used with the help of browser.
(ii) Multimedia documents-A web page may have graphic, audio, video, and animation
etc at a time.
(iii) Hypertext and hyperlinks-the dynamic links which can move towards another web page is
hyperlink.
(iv) Interactive -www with its pages support and enable interactivity between users and
servers.
(v) frame-display of more than one section on single web page.

Web server-It is a WWW server that responds to the requests made by web browers.e.g. :
Apache, IIS, PWS(Personal web server for Windows 98).

Web browser-It is a WWW client that navigates through the World Wide
Web and displays web pages. E.g.: FireFox Navigator, Internet Explorer
etc.
Web sites-A location on a net server where different web pages are linked together bydynamic
links is called a web site. Each web site has a unique address called URL.

20 | P a g e
Web page -A document that can be viewed in a web browser and residing on a
web site is a web page.
Home page-a web page that is the starting page and acts as an indexed page ishome
page.
Web portal -that facilitates various type of the functionality as web site. for
e.g.www.yahoo.com,www.rediff.com

Domain name-An internet address which is a character based is called a Domainname.


Some most common domains are com, edu, gov, mil, net, org, and co. Some
domain names are location based also. For e.g.
au for Australia, a for Canada, in for India etc.

URL-A URL (uniform resource locator) that specifies the distinct address for eachresource
on the internet.
e.g.
http://encycle.msn.com/getinfo/stypes.asp

Web hosting -means hosting web server application on a computer system throughwhich
electronic content on the internet is readily available to any web browser client. there are
various types of web hosting:
(i) free hosting-available with most prominent sites that offer to host some webpages for no
cost. Like geocities, tripod, homestead etc.
(ii) Shared hosting-This type of hosting is provided under one’s own domainname,
www.yourname.com. With a hosting plan with the web hosting company, one can present
oneself as a fully independent identity to his web audience.
(iii) Dedicated hosting- the company wishing to go online , rents an entire webserver from a
hosting company.
(iv)co-location hosting - The company actual owns the server on which its site is hosted but web
hosting company is responsible for al server administration.

HTML -

It stands for Hyper Text Markup Language that facilitates to write web document that can be
interpreted by any web browser. It provide certain tags that are interpreted by the browser how
to display and act with the text, graphics etc. tags are specified in <>.
For e.g.
<body bgcolor=green> it is opening tag
</body> it is closing tag.
body is the tag with bgcolor attributes.

XML (eXtensible Markup Language)


XML is a markup language for documents containing structured information. Structured
information contains both content (words, pictures etc.) and some indication of what role
content plays.

21 | P a g e
DHTML-It stands for Dynamic Hyper Text Markup Language. DHTML refers to Webcontent that
changes each time it is viewed. For example, the same URL could result in a different page
depending on any number of parameters, such as:
*geographic location
*time of the day
*previous pages viewed by the user
*profile of the reader

WEB SCRIPTING – The process of creating and embedding scripts in a web pageis known
as web-scripting.

SCRIPT: A Script is a list of commands embedded in a web page. Scripts


areinterpreted and executed by a certain program or scripting –engine.

Types of Scripts:

1. Client Side Script: Client side scripting enables interaction within a web page.Some
popular client-side scripting languages are VBScript, JavaScript, PHP(Hyper
Text Preprocessor).

2. Server-Side Scripts: Server-side scripting enables the completion or carrying out atask at
the server-end and then sending the result to the client –end.
Some popula server-side Scripting Languages are PHP, Perl, ASP(Active Server Pages),
JSP(Java Server Pages) etc.

OPEN SOURCE TERMINOLOGIES

TERMINOLOGY & DEFINITIONS:

Free Software: The S/W’s is freelyaccessible and can be freely used changedimproved
copied and distributed by all and payments are needed to make for free S/W.

Open Source Software: S/w whose source code is available to the customerand it can be
modified and redistributed without any limitation .OSS may come free of cost but nominal
charges has to pay nominal charges (Support of S/W and development of S/W).

FLOSS (Free Libre and Open Source Software) : S/w which is free as wellas open source
S/W. ( Free S/W + Open Source S/W).

GNU (GNU’sNotUnix) : GNU project emphasize on the freedom and itsobjective is to


create a system compatible to UNIX but not identical with it.

FSF (Free Software Foundation) : FSF is a non–profit organization createdfor the purpose
of the free s/w movement. Organization funded many s/w developers to write free
software.

OSI (Open Source Initiative) :Open source software organization dedicatedto cause of
promoting open source software it specified the criteria of OSS and its source code is not
freely available.

22 | P a g e
W3C(World Wide Web Consortium) :W3C is responsible for producing thesoftware
standards for World Wide Web.

Proprietary Software: Proprietary Software is the s/w that is neither opennor freely
available, normally the source code of the Proprietary Software is not available but
further distribution and modification is possible by special permission by the supplier.

Freeware: Freeware are the software freely available , which permitredistribution but not
modification (and their source code is not available). Freeware is distributed in Binary
Form (ready to run) without any licensing fees.
Shareware: Software for which license fee is payable after some time limit, itssource code
is not available and modification to the software are not allowed.

Localization:localization refers to the adaptation of language, content anddesign to


reflect local cultural sensitivities .e.g. Software Localization: where messages that a
program presents to the user need to be translated into various languages.
Internationalization: Opposite of localization.

OPEN SOURCE / FREE SOFTWARE

Linux : Linux is a famous computer operating system . popular Linux server setof program
–LAMP(Linux, Apache, MySQL, PHP)
Mozilla :Mozilla is a free internet software that includes
a web browser
an email client
an HTML editor
IRC client

Apache server: Apache web server is an open source web server available formany
platforms such as BSD, Linux, and Microsoft Windows etc.
Apache Web server is maintained by open community of developers of Apache
software foundation.

MYSQL : MYSQL is one of the most popular open source database system.Features of
MYSQl :
Multithreading
Multi –User
SQl Relational Database Server
Works in many different platform
PostgreSQL : Postgres SQL is a free software object relational databaseserver .
PostgresSQL can be downloaded from www.postgressql.org.

Pango : Pango project is to provide an open source framework for the layoutand
rendering of internationalized text into GTK + GNOME environment.Pango using Unicode
for all of its encoding ,and will eventually support output in all the worlds major
languages.

OpenOffice : OpenOffice is an office applications suite. It is intended tocompatible and


directly complete with Microsoft office.
OOo Version 1.1 includes:
Writer (word processor)
Calc(spreadsheet)
Draw(graphics program)
etc

23 | P a g e
Tomcat : Tomcat functions as a servlet container. Tomcat implements theservlet and the
JavaServer Pages .Tomcat comes with the jasper compiler that complies JSPs into servlets.
PHP(Hypertext Preprocessor) : PHP is a widely used open sourceprogramming language
for server side application and developing web content.
Python: Python is an interactive programming language originally as scriptinglanguage
for Amoeba OS capable of making system calls.

Website Supporting the Open Source Software

www.sourceforge.net
www.openRDF.org
www.opensource.org
www.gnu.org

IMPORTANT BOARD QUESTIONS

1. Explain function of hub and router. 1


Ans:

1. Hub: A hub contains multiple ports. When a packet arrives at one port, it is copied to all the
ports of the hub. When the packets are copied, the destination address in the frame does not
change to a broadcast address. It does this in a rudimentary way, it simply copies the data to
all of the Nodes connected to the hub.

2. Router : routers are networking devices that forward data packets between networks using
headers and forwarding tables to determine the best path to forward the packets

2. Expand the following terms 2

(i) URL (ii) ISP (iii) DHTML (iv) CDMA:

Ans; (i) URL: Unified Resource Locator


(ii) ISP: Internet Service Provider.
(iii) DHTML: Dynamic Hyper Text Markup Language

3. Differentiate between message switching and packet switching 1

Ans: Message Switching–In this form of switching no physical copper path isestablished in
advance between sender and receiver. Instead when the sender has a block of data to be
sent, it is stored in first switching office, then forwarded later , one jump at a time.
Packet Switching – With message switching there is no limit on block size, in
contrast packet switching places a tight upper limit on block size.

4. Write two applications of Cyber Law. 2


Ans: Two applications of cyber law are Digital Transaction and Activities on Internet.

24 | P a g e
5. Explain GSM. 1
Ans: Global system for mobile, communications is a technology that uses narrowbandTDMA,
which allows eight simultaneous calls on the same radio frequency. TDMA is short for Time
Division Multiple Access. TDMA technology uses time division multiplexing and divides a radio
frequency into time slots and then allocates these slots to multiple calls thereby supporting
multiple, simultaneous data channels.

6. Write difference between coaxial and optical cable. 1


Ans: Coaxial cable consists of a solid wire core surrounded by one or more foil or wireshield ,
each separated by some kind of plastic insulator. Optical fibers consists of thin strands of glass or
glass like material which are so constructed that they carry light from a source at one end of the
fiber to a detector at the other end.

7. Write two advantage and disadvantage of RING topology. 2


Ans:
Advantages:
1. Short cable length.
2. No wiring closet space required.
Disadvantages:
1. Node failure causes network failure
2. difficult to diagnose faults

8. Define Open Source Software, Free Software, Freeware, and Shareware. 2

Ans:

Free Software : The S/W’s is freely accessible and can be freely used changedimproved copied
and distributed by all and payments are needed to made for free S/W.

Open Source Software : S/w whose source code is available to the customer andit can be
modified and redistributed without any limitation .OSS may come free of cost but nominal
charges has to pay nominal charges (Support of S/W and development of S/W).

Freeware: Freeware are the software freely available , which permit redistributionbut not
modification (and their source code is not available). Freeware is distributed in Binary Form
(ready to run) without any licensing fees.

Shareware: Software for which license fee is payable after some time limit, itssource code is
not available and modification to the software are not allowed.

25 | P a g e
9. What is the difference between WAN and MAN? 2

Ans: MAN (Metropolitan Area Network) is the network spread over a city.

WAN (Wide Area Network) spread across countries.

10. What is the purpose of using FTP? 1

Ans: (i)To promote sharing of files (computer programs and/or data).

(ii)To encourage indirect or implicit use of remote computers

11. What is a Modem? 1

Ans: A modem is a computer peripheral that allows you to connect and communicatewith other
computers via telephone lines.

12. How is a Hacker different from a Cracker? 1

Ans: Hackers are more interested in gaining knowledge about computer systems andpossibly
using this knowledge for playful pranks.

Crackers are the malicious programmers who break into secure systems

13. Expand the following terms with respect to Networking: 2

(i) Modem (ii) WLL (iii) TCP/IP (iv) FTP

Ans: (i) Modem : Modulator/Demodulator

(ii) WLL: Wireless in Local Loop

(iii) TCP/IP: Transmission Control Protocol/Internet Protocol

(iv) FTP: File Transfer Protocol

14. What are Protocols? 1

Ans: A protocol means the rules that are applicable for a network.
It defines the standardized format for data packets, techniques for detecting and
correcting errors and so on.
A protocol is a formal description of message formats and the rules that two or more machines
must follow to exchange those messages.
E.g. using library books.

Types of protocols are:


1. HTTP
2. FTP
3. TCP/IP
4. SLIP/PPP

26 | P a g e
15. What is the difference between Repeater and a Bridge? 1

Ans: A Repeater is a network device that amplifies and restores signals for long distance
transmission where as a Bridge is a network device that established an intelligent connection
between two local networks with the same standard but with different types of cables.

HOTS (HIGHER ORDER THINKING SKILLS)

4 Marks Questions

1. Knowledge Supplement Organization has set up its new centre at Mangalore for itsoffice and
web based activities. It has four building as shown in the diagram below (4)

alpha
Gamma

Beta
Lambda

Centre to Centre distance between various buildings

Alpha to Beta 50m

Beta to gamma 150m

Gamma to Lambda 25m

Alpha to Lambda 170m

Alpha 25

Beta 50

Beta to Lambda 125m Gamma 125

Alpha to Gamma 90m Lambda 10

27 | P a g e
(a) Suggesting a cable layout of connection between building state with justification
where Server, Repeater and hub will be placed. (2)
(b) The organization is planning to link its front office situated in the city in a hilly
region where cable connection is not feasible, suggest an economic way to
connect it with reasonably high speed? (2)

Ans:

(i)
The most suitable place to house the server of this organization would be building Gamma , as this
building contains the maximum number of computers , thus decreasing the cabling cost for most of
the computers as well as increasing the efficiency of the maximum computers in the network
Distance between alpha to gamma and beta to gamma is large so there repeater will require and
hub is necessary for all premises because it is used in local networking.
The most economic way to connect it with a reasonable high speed would be to use radio
wave transmission, as they are easy to install, can travel long distances, and penetrate
buildings easily, so they are widely used for communication, both indoors and outdoors.
Radio waves also have the advantage of being omni directional, which is they can travel in
all the directions from the source, so that the transmitter and receiver do not have to be
carefully aligned physically.

H
U
B

28 | P a g e
2. Software Development Company has set up its new center at Jaipur for its office and
web based activities. It has 4 blocks of buildings as shown inthe diagram below:

Center to center distances between various blocks

Black A to Block B 50 m

Block B to Block C 150 m


Block C to Block D 25 m
Block A to Block D 170 m

Block B to Block D 125 m

Block A to Block C 90 m

Number of Computers

Black A 25
Block B 50

Block C 125

Block D 10

e1) Suggest a cable layout of connections between the blocks.


e2) Suggest the most suitable place (i.e. block) to house the server of this company with
a suitable reason.
e3) Suggest the placement of the following devices with justification
(i) Repeater
(ii) Hub/Switch
e4) the company is planning to link its front office situated in the
city in a hilly region where cable connection is not feasible, suggest an economic
way to connect it with reasonably high speed?

Ans:

(e1) (Any of the following option)

29 | P a g e
Layout Option 1

Layout Option 2

(e2) The most suitable place / block to house the server of this organization would be
Block C, as this block contains the maximum number of computers, thus decreasing the
cabling cost for most of the computers as well as increasing the efficiency of the
maximum computers in the network.

(e3)
(i) For Layout 1, since the cabling distance between Blocks A and C, and that between B
and C are quite large, so a repeater each would ideally be needed along their path to
avoid loss of signals during the course of data flow in these routes.
For layout 2, since the distance between Blocks A and C is large so a repeater would
ideally be placed in between this path.

(ii) In both the layouts, a hub/switch each would be needed in all the blocks, to
Interconnect the group of cables from the different computers in each block.

(e4) The most economic way to connect it with a reasonable high speed would be to use
radio wave transmission, as they are easy to install, can travel long distances, and
penetrate buildings easily, so they are widely used for communication, both indoors and
outdoors. Radio waves also have the advantage of being omni directional, which is they
can travel in all the directions from the source, so that the transmitter and receiver do not
have to be carefully aligned physically.

3. Ram Goods Ltd. has following four buildings in Ahmedabad city.

30 | P a g e
Computers in each building are networked but buildings are not networked
so far. The company has now decided to connect building also.
(a) Suggest a cable layout for these buildings.
(b) In each of the buildings, the management wants that each LAN segment gets
a dedicated bandwidth i.e. bandwidth must not be shared. How can this be
achieved?
(c) The company also wants to make available shared Internet access for each of
the buildings. How can this be achieved?
(d) The company wants to link its head office in GV1 building to its another office in
Japan.
(i) Which type of transmission medium is appropriate for such a link? (ii)
What type of network would this connection result into?

Ans:
(a) Total cable length required for this layout = 75 mts

(b) To give dedicated bandwidth, the computers in each building should


beconnected via switches as switches offer dedicated bandwidths.
(c) By installing routers in each building, shared internet access can be made
Possible.
(d) (i) Satellite as it can connect offices across globe.
(ii) WAN (Wide Area Network)

4. Abhivandan Sanskriti in Udaipur is setting up the network between its different


wings. There are 4 wings named as SENIOR(S), MIDDLE(M), JUNIOR(J) and OFFICE(O).
Distance between the various wings are given below:

No. of Computers

(i) Suggest a suitable Topology for networking the computer ofall wings.

31 | P a g e
(ii) Name the wing where the server to be installed. Justify your answer.
(iii) Suggest the placement of Hub/Switch in the network.
(iv) Mention an economic technology to provide internet accessibility to all wings.

Ans:
(i) Star or Bus or any other valid topology.
(ii) Wing S, because maximum number of computers are located at Wing S.
(iii) Hub/ Switch in all the wings.
(iv) Coaxial cable/Modem/LAN/TCP-IP/Dialup/DSL/Leased Lines
or any other valid technology

32 | P a g e
Chapter 2
FREE AND OPEN SOURCE SOFTWARE
Brief Summary of the Chapter:

In this chapter we are going to discuss about various open source software and how they are different from
software which are not open source.

Key Points:

Free Software: It means software is freely accessible, free to use, changed, improved, copied, and
distributed without any payments.
Four kinds of freedom:
► Freedom to run the program for any purpose
► Freedom to redistribute copies.
► Freedom to study how the program works
► Freedom to improve the program and release your improvements to the public
Open Source Software:
Definition: The categories of software / programs whose Licenses do not impose many
conditions.
Features:
1. Freedom to run and use the software
2. Modify the program
3. Redistribute copies of either original or modified program (without paying royalties to
previous developers).
It can be freely used for modifications, but it does not have to be free of charge. Its source code is
available.

Criteria for the distribution of open source software


1. Free distribution
2. Source code
3. Derived works
4. Integrity of the Author’s Source code
5. No discrimination against fields of endeavor.
6. Distribution of License
7. License must not be specific to a product
8. License must not restrict other software. FOSS
(free and open software):Free software- no payments
Open source software- for technical progress

33 | P a g e
OSS and FLOSS
► OSS- Source code is available

(Open source modified and redistributed software) free of cost or with nominal charge.
► FLOSS- (free libre and open source software)
FSF (free software foundation)
Founded by Richard Stallman in 1985 to support GNU project.
Non-profit organization created for the purpose of supporting free software movement
GNU (free and open source)
Objective: To create a system compatible to UNIX but not identical with it.
Now it offers a wide range of software, including applications apart from operating system.
Proprietary software (neither open nor freely available)
• Definition- Its use is regulated and further distribution and modification is either
forbidden or requires special permission by the supplier
• Source code is not available.
Freeware
• Free of cost
• Copying and further distribution but not modification.
• Source code is not available
Example Internet Explorer
Shareware
• Right to redistribute copies
• After a certain period of time license fee should be paid.
• Source code is not available.
• Modifications are not possible.
• Objective- to increase user’s will to pay for the software. Limits functionality after a trial period
of 1-3 months.

Important Software’s
LINUX
• Linux: - free and open source software.
• It can be downloaded from www.linux.org
• Linux is a part of popular web server program LAMP (Linux, apache, MySql, PHP).
Mozilla
• Freeware
• No source code available
• free internet software
It can be downloaded from www.mozilla.org
Apache Server
• The most common web server (or HTTP server) software on the Internet.
• Apache is designed as a set of modules, enabling administrators to choose which features they wish
to use and making it easy to add features to meet specific needs including handling protocols other
than the web-standard HTTP.
• Apache HTTP server is an open source web server.
• It is component of LAMP.

Denial-of-services attacks:
DOS are those attacks that prevent the legal users of System from accessing or using the
resources, information or capabilities of the system. It may be of following types:

34 | P a g e
• Denial of Access to Information: Such attacks cause deletion or changing of important information to
non-readable format.
• Denial of Access to Applications: Such attacks make the applications unusable or unavailable for legal
user of the system.
• Denial of Access to Communications: Such attacks includes cutting of communication wire, jamming
radio communications, flooding a system with junk mail.
Threats to network security: It may be of following types:
• Snooping: It refers to unauthorized access to someone else’s data, email or computer activity.
• Eavesdropping: It refers to unauthorized listening / intercepting someone else’s
privatecommunication / data/ information.
Standards:
Standards refers to an established set of rules or requirements which are approved by recognized
body or widely used across various software platforms. For ex.: PDF (Portable documents format) is a
technical standard widely used by the industry. They are of two types: Proprietary Standards and
Open Standards.
Proprietary standards are those for which users have to buy license to use them. For e.g. MSOffice
format .doc, .ppt, .xlsetc
Open Standards are internationally accepted technical standards that guarantee that data canbe
exchanged across platforms and for any applications. Open is feely open to all.
Advantages of Open Standards:
Making the data accessible to all.
It ensures data is application and platform independence.
Diversity and Interoperability in the Industry i.e. it enables business and people to go for
any technology of their choice as per their needs and budget.
E.g.: ASCII Characters, HTML file, Joint Photographic Expert Group, Portable Network Graphic
etc.

• It is a new audio compression which is open format developed by Xiph.org. It is roughly comparable to
mp3, mpeg-4 formats and is completely free, open and unpatented. Hence it imposes no restrictions on
its usage, types of usage, distributions, redistribution etc.

Indian Language Computing:


• Indian Language computing refers to ability to interact in diverse Indian language on electronic
system.
How to represent character in Memory?
• ASCII: American Standard Code for Information Interchange is widely used alphanumeric code in most
microcomputers and minicomputers and in many mainframes. It is 7 bit code hence it can represent
standard 27 =128 characters.
ISCII:
• Indian Standard Code for Information Interchange (ISCII) is an eight bit code capable of coding 256
characters. It retains all ASCII characters and also offers coding for Indian Scripts.
Transliteration:
• When we type Indian Language words phonetically in English script and tool will automatically convert
them into corresponding language words called as transliteration.
Unicode
• Unicode provides a unique number for every character, no mater what the platforms, no matter what
the program, no matter what the language. Unicode can represent 94140 characters. Unicode standard
has incorporated Indian Scripts under the group named Asian scripts. Indian

35 | P a g e
scripts included as Devnagari, Bengali, Gurumukhi, Gujarati, Oriya, Tamil, Telgu, kannada, and
Malayalam.
Fonts:
• A Font refers to a set of displayable text characters called glyphs, having specific style and size. There
are two categories of font: True Type Font and Open Type Font.
• True Type Font: It is developed by Apple and licensed to Microsoft. It is 8 bit font which iscompatible
with Microsoft Windows and MAC OS.
•Open Type Font: It is the extension of the True Type Font Format which is 16 bits font andsupport
65536 characters (Unicode characters).
Indian Language Text Entry:
Many Tools / software have been developed to facilitate the typing of Indian
Language text. There are two types text entries:
• Phonetic Text Entry: Words typed as per their pronunciation in English script and later
onconverted to Corresponding (Hindi/Gujarati) language work is known as phonetic text entry.
• Key map based text entry: When you type text from a keyboard having key mapping ofIndian
language characters, is known as key map based text entry.

Questions and Answer


Q1. What is OSS?
Ans Open Source Software is a software available with source code and free to change/edit / redistribute
and imposed no further restrictions on product or its usage.
Q2. Expand the terms: OSI, FLOSS, FSF, GNU, W3C, and PHP.
Ans: OSI: Open source Initiative
FLOSS: Free Libre and Open Source Software.
FSF: Free software Foundation created for the purpose of supporting free Movement.
GNU : GNU’s Not Unix Project established with an objective to create a system Compatible to
UNIX but not identical with it.
W3C: World Wide WEB consortium is responsible for producing the software standards for
World Wide Web.
PHP: Hypertext Pre-processor is a widely used open source programming language
primarily for server side applications and developing dynamic web content.
Q3. What is free software?
Ans : Free Software means the software is freely accessible and can be freely used, changed, improved,
copies and distributed to others.
Q4. Define freeware and shareware.
Ans The freeware is the software available free of cost and allows copying and further distribution but does
not allows modification as its source code is not available.
Shareware is as software which is available for redistribution for stipulated time but after some time
some license fee is required to be paid.
Q5. What is openoffice.org?
Ans It is Office an application suite which is free software and directly competes with Microsoft Office. It is
compatible with MS Operating System, UNIX, MAC OS.

Q6. What is font? What is OTF?


Ans : A font is a set of displayable or printable text characters having specific style and size. Open Type Font:
It is the extension of the True Type Font Format which is 16 bits font and support 65536 characters (
Unicode characters).

36 | P a g e
Q7. What are different font categories?

Ans :There are two categories of font: True Type Font and Open Type Font.
True Type Font: It is developed by Apple and licensed to Microsoft. It is 8 bit font which iscompatible
with Microsoft Windows and MAC OS.
Open Type Font: It is the extension of the True Type Font Format which is 16 bits fon andsupport
65536 characters ( Unicode characters).
Q8. Define ODF.
Ans :ODF is an Open Document file Format used for exchanging office documents such as memos,reports,
spreadsheets, database, charts and presentations. Open document is open, XML based file format
used for exchanging office documents such as memos, reports, spreadsheets, database, charts and
presentations.
Q9. What is key map based text entry?
Ans: When you type text from a keyboard having key mapping of Indian Languages characters is known as
key map based text entry.
Q10. What is Unicode?
Ans10: Unicode provides a unique number for every character, no mater what the platforms, no matterwhat
the program, no matter what the language. Unicode can represent 94140 characters.
Q11. What is ISCII?
Ans : Indian Standard Code for Information Interchange (ISCII) is a coding scheme for representing various
writing systems of India. It encodes the main Indic scripts and a Roman transliteration. When we type
Indian Language words phonetically in English script and tool will automatically convert them into
corresponding language words called as transliteration.
Q12. What is Indian Script key map known as?
Ans : Key map based text entry: When you type text from a keyboard having key mapping ofIndian language
characters, is known as key map based text entry.

Unsolved Questions
1. What is open source software?
2. Compare Free software and open source software.
3. Compare OSS and floss.
4. Compare Proprietary software and free software.
5. Compare Free ware and shareware.
6. Compare Freeware and free software
7. Write Short notes on GNU.
8. Write short notes on LINUX.
9. Write Short notes on MOZILLA.
10. Write short notes on APACHE.
11. Write short notes on POSTGRE SQL.
12. Write short notes on PHP.
13. Write short notes on Open Office.
14. What are technological standard and its various categories?
15. Mention some advantages of open standards.
16. What is the significance of Unicode in terms of Indian Language Computing?
17. How phonetic text entry is different from key map based text entry?
18. What is OggVorbis? Why?
19. How to represent character in Memory?
20. What is font and its types?

37 | P a g e
CHAPTER 3:
JAVA GUI PROGRAMMING REVISION TOUR-I
Learning Objective
After studying this Lesson students will be able to;
 Identify , name and usages of different components of Netbeans IDE
 Identify and name the various method and properties associated with the
various form controls
 Create simple applications in Java using Netbeans IDE
 Create GUI applications using the concepts of variables and control structures
Rapid Application Development: It describes a method of developing software
through the use of pre-programmed tools or wizards. The pre-programmed tools or
controls are simply dropped on a screen to visually design the interface of
application. It enables program development in shorter time.
NetBeans Java IDE: It is a free, open-source, cross-platform IDE with built-in support
for Java programming language. It has more advanced GUI building tools available in
any open-source Java IDE.
Event: Occurrence of an activity.
Message: Information sent to the application or received from the application.
Types of Swing Components:
(a) Component: It is a self-contained graphic entity like JLabel, JTextField etc.
(b) Container: It can hold other components. It is of two types:
(i) Top Level Container: Can be displayed directly on a desktop. Every swing
application must have at least one top level container, i.e. JApplet, JDialog, JFrame.
(ii) Non Top Level Container: Can be displayed within another top level container,
i.e. JPanel, JScrollPane, JInternalFrame, JLayeredPane etc.
Child controls are controls inside a container control.
Basic Graphical Controls of JAVA(Swing controls)
The Java offers various Swing controls to facilitate development of GUI applications. Most
commonly used controls are-
 jFrame: Used as a Basic Window or form.
 jLabel: Allows Non-editable text or icon to be displayed.
 jTextField: Allows user input. It is editable through text box.
 jButton: An action is generated when pushed.
 jCheckBox: Allow user to select multiple choices.
 jRadioButton: They are option button which can be turned on or off. These are suitable for
single selection.
 jList: Gives a list of items from which user can select one or more items.
 jComboBox: It gives dropdown list of items with facility to add new items. It is combination
of jList and jTextField.
 jPanel: It is container controls which contains other controls using a frame.
FRAME
It is a top level window with title and border. It is created through JFrame component. It has title and
boarder. Each project must have at least one frame.

38 | P a g e
Swing controls Methods Properties
JButton getText() setText() • Background
• Enabled
• Font
• Foreground
• Text
• Label
JLabel getText() • Background
• Enabled
• Font
• Foreground
• Text
JText Field getText() isEditable() • Background
isEnabled() setText() • Enabled
• Editable
• Foreground
• Text
jTextArea getText() setText() • Background
append() • Enabled
• Editable
• lineWrap
• Text
JRadioButton getText() setText() • Background
isSelected() • Enabled
setSelected()
• Font
• Foreground
• Buttongroup
• Selected
• Label
JCheckBox getText() setText() • Buttongroup
isSelected() • Font
setSelected()
• Foreground
• Label
• Selected
• Text
jList getSelectedValue() Foreground
getSelectedValues() Model
getSelectedIndex() SelectionModeSelectedIndex
getSelectedIndices()
SelectedIndices
setSelectedIndex()
setSelectedValue()

39 | P a g e
• Foreground
• Model
• SelectedIndex
• SelectedItem
• SelectionMode
• Text
JTable getText() addRow() • Model
getModel()

JOptionPane showMesageDialog() • getRowCount()


• removeRow()
• addRow()

Java Character Set: It is the set of valid character set that a language can recognise. Java uses
Unicode character set.
Data Types: Data Types are means to identify the type of data and associated operations of
handling it.
Type Conversion: It is the process of converting one predefined data type into another. It has two
forms:
• Implicit (Coercion): Compiler automatically performs conversion to the type of the
largest operand in mixed mode expression.
• Explicit (Type casting): Done by programmer. Converting to or from Boolean is not
permitted. : (type) expression e.g. (float) (x/5 * y + 5)

Type Size Description Range


byte 1 Byte Byte integer -128 to +127
short 2 Byte Short integer -32768 to +32767
int 4 Byte integer -231 to 231-1
long 8 Byte Long integer -263 to 263-1
float 4 Byte Single precision floating -3.4x10-38 to +3.4x1038
point (up to 6 digit)
double 8 Byte Double precision floating -1.8x10-308 to
(up to 15 digit) +1.8x10308
char 2 Byte Single character 0 to 65536
Boolean 1 Byte Logical Boolean values True or False

Variables: It is a named memory location which holds a data value of a particular data type.
Variable declaration &Initialisation:
A variable with declared first value is said to be initialized variable.
e.g. introllno = 1;
Text Interaction:
(i) getText() Method : String name = nametf.getText();
(ii) setText() method: Stores or changes text in text based controls e.g.
ranktf.setText(“1”);
(iii) Parse() Methods: Used to convert a string value into numeric value.
(iv) JOptionPane.showMessageDialog (): Displays a Message Box.
System.out.print (): It prints the desired output on output window.
System.out.println():It prints the desired output on output window and also changes the line.

40 | P a g e
Variable Scope: Program region within which a variable is accessible. It is accessible within
the set of braces it is declared in.
Constant: Named memory locations whose value can’t be changed in the program. It makes program
easy to read, check & modify. e.g. final intrateofinterest = 10;
Operator: It represents particular task and the objects of the operation is called operands. It may
be Unary (working on one operand, eg. unary -), binary (working on two operands, e.g. subtract -)
or ternary (working on three operands, e.g. ?:).
Arithmetic Operators:
+ Unary plus Represents positive values. int a=+25;
- Unary minus Representsnegative values. int a=-25;
+ Addition Adds two values int x= a+b;
- Subtraction Subtract second operands from int x=a-b;
first.
* Multiplication Multiplies two values int x= a*b;
/ Division Divides first operand by second int x=a/b;
% Modulus Finds remainder after division. int x= a%b;
+ Concatenate Adds two strings (String Addition) “ab”+”cd” =”abcd” “25”+”12”
=”2512”
Relational Operators:
== Equalto Tests whether two values are a==b
equal.
!= Notequalto Tests whether two values are a!=b
unequal.
> Greaterthan Returns true a>b
if the value of the left expression
is greater than right value.
< Lessthan Returns true if the value of the a<b
left expression is less than the
right.
>= Greaterthanorequa Returns true if the value of the a>=b
lto left expression is greater or
equal than right.
<= lessthanorequalto Returns true if the value of the left a<b
expression is less or equal .
Logical Operators :
&& And Returns true X and y both x&&y
true
|| Or Returns true Either x or y is x||y
true
! Not Returns true X is false !x

Conversion of String into number - Parsing Some time it is required to convert numbers stored in
string form in to numeral form so that calculation can be carried. Any number typed in text field
assumed as string, so no any arithmetic operation can be applied directly. Any character or string
type must be converted into its numeric form before applying any arithmetic calculation. The
parse()methodshelpstoparsestringintodifferentnumerictypes.

Method Syntax Usage


parseByte() Byte.parseByte(string) Toconvertastringvaluetoby
tetype

41 | P a g e
parseShort() Short.parseShort(string) Toconvertastringvaluetoty
pe short
parseInt() Integer.parseInt(string) ToconvertastringvaluetoIn
tegertype
parseLong() Long.parseLong() ToconvertastringvaluetoLo
ngtype
parseFloat() Float.parseFloat() ToconvertastringvaluetoFl
oattype
pareseDouble() Double.parseDouble() ToconvertastringvaluetoD
oubletype

Programming Constructs: Flow of Control

Selection:

If statement; if
if (expression) else
statement ; if
if . . . else statement if (expression)
if (expression) body ;
statement 1 ; else if (expression) body;
else else
statement 2; body;
Nested if: Dangling else Problem:
if (expression) { if (expression)
if (expression) if (expression)
statement 1 ; statement 1 ;
[else statement 2;] else
} statement 2;
else (Indentation indicates else for outer if but it actually
body of else; matches with preceding If.)
The Switch Statement:
switch (expression)
{ case constant 1 : statement sequence 1;
break; // value of expression must be byte, short, int or a char.
case constant 2 :
statement sequence 2;
break;

42 | P a g e
[default : statement sequence n]; }

In absence of break in switch statement, Java will start executing all statements after the
correct case. This phenomenon is called Fall-Through.

Iteration (Looping) statements:


(i) for loop (ii) while loop (iii) do-while loop
Parts of loop:
Initialisation Test Expression Update Expression
Loop Body
for loop:
for (inti = 1; i<= 10; ++i)
System.out.print(i + “ ”);
Program to find factorial using for loop:
int fact = 1, a; intnum = Integer.parseInt(numtf.getText());
for (a = 1; a <= num; a++)
{ fact = fact*a; }
System.out.println(“The factorial of ” + num + “ is ” + fact);
The While Loop: It is an Entry-controlled/Top-tested/Pre-Tested loop.
Program to find factorial using while loop:
intnum = integer.parseInt(numtf.getText());
longi = num, fact = 1;
while (num != 0)
{ fact = fact *num;
-- num;
}
System.out.println(“The factorial of ” + i + “ is ” + fact);
The do-while Loop: It is an Exit-controlled/Bottom-Tested/Post-Tested loop. It executes at least once.
Syntax:
do {statement ;
} while (test-expression);
Example:
charch = ‘A’;
do {
System.out.printIn(ch);
ch++;
} while (ch<= ‘Z’);

Jump statement
Return: To return from a function.
Break: It is used to terminate the body of while, do-while, for or switch statement and transfers
control to the statement following the body.
Continue: It skips the rest of the loop (while, do-while or for) and starts the next iteration.

Solved Questions:
1. Write a java code to find out whether a year (4 digit number stored in a variable) is a leap
year.
private void lybutActionPerformed(java.awt.event.ActionEventevt)

43 | P a g e
{
longi = Long.parseLong(lytf.getText()); if (i%100 ==0) if (i%400 ==0)
System.out.println(i + “ is Leap Year");
else
System.out.println(i + " is Normal Century Year");
else if (i%4==0)
System.out.println(i + " is Leap Year");
else
System.out.println(i + " is not a Leap Year"); }
2. Write a java program to find the greatest out of three numbers.
int a = Integer.parseInt(tf1.getText()), b = Integer.parseInt(tf2.getText());
int c = Integer.parseInt(tf3.getText());
if (a>b && a>c)
System.out.println( a + “ is greater”);
elseif (b>c)
System.out.println( b + “ is greater”);
else
System.out.println( c + “ is greater”);

Unsolved Questions

1. What will be output of the following code:


byte b;
double d= 417.35;
b= (byte) d;
system.out.println(b);
2. Given the value of a variable, write a statement, without using if construct, which will produce the
absolute value of a variable.
What is wrong with the following code fragment?
Switch (x)
{
case 1:
n1= 10;
n2= 20;
case 2:
n3=30;
break;
n4= 40;
}
3. What will be the output of the following program code?
int m = 100;
int n = 300;
while(++m < --n);
System.out.println(m+” “+ n);
4. What does the following fragment display
String s = “Six:” + 3+ 3;
System.out.println(s);
5. What is the output of the following code?
String s = new string();
System.out.println(“s = “ + s);
6. What will be the output of the following code snippet?
int x= 10;
44 | P a g e
int y = 20;
if ((x<y)||(x=5) > 10)
System.out.println(x);
else
System.out.println(y);
7. State the output of the following program:
public static void main(String args[ ])
{
int x = 10;
int y = 15;
System.ou.println((x>y)? 3.14: 3);
}
8. State the output of the following program:
public static void main(String args[ ])
{
int x = 10;
float y = 10.0;
System.ou.println((x>y)? true: false);
}
9. Given a pacakage named EDU.student, how would you import a class named Test
contained in this package? Write one line statement.
10. Consider the following class definition:
Class Student
{
abstract double result( )
}
This code will not compile since a keyword is missing in the first line. What is the
keyword?

CHAPTER 4
Basics of Object Oriented Programming
Programming

45 | P a g e
Computer programming is a process of designing, writing, testing, debugging and maintaining the source
code of computer programs written in a particular programming language. The purpose of programming
is to organize instructions that are capable of solving real life problems.
Writing instructions in the desired order gives the required result from the program but when these
instructions increase in number, it becomes extremely difficult for the programmer to debug and
maintain the code. For this reason, technology experts kept developing and introducing different
programming paradigm and accordingly kept developing languages to support these paradigms. Major
programming paradigms are:
1. Procedural Programming
2. Modular Programming
3. Object Oriented Programming
4. Event Driven Programming

Here we will focus only on Object Oriented Programming.


Object Oriented Programming
Object Oriented Programming (also called as OOP) is a very user friendly yet a powerful approach to
solve basic to difficult problems. The idea was created for developing a language that could be used for
system description and system prescription. There are several object-oriented languages. Some common
Object Oriented languages are Smalltalk, C++ and Java.
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 methods together into single unit. There are four
features of Object Oriented Programming. These are listed below:
1. Abstraction
2. Encapsulation
3. Polymorphism
4. Inheritance

Components of OOP
The major components of Object Oriented Programming are as follows:
1. Class
2. Object
3. Data Members and Methods
4. Access Specifier and Visanibility Modes

Let us take a look at each of them in details:


Classes and Objects
A class is used to wrap data and methods together in a single unit. An object is an instance of a class that
is capable of holding actual data in memory. We can say that a class is a blueprint that is used to create
objects.
For example we can say that Human is a class and Arun, Aneek, Ramya, you, me will be the objects of
this Human Class.
Class and objects are related to each other in the same way as data types and variables. For example
when we declare an integer variable count, the variable count can be thought of as an object of type int
which can be assumed as the class.
All components/controls such as JTextField, JLabel etc. are all classes and components dragged to jFrame
are its objects which are named as jTextField1, jLabel1 etc. In fact, jFrame used as container for other
object is itself is a class.
Data Members and Methods
Each class/object has some properties and its associated behaviours. These properties are represented
in a class by variables and Methods are represented by functions. For example the Class Human can have
properties of Name, Age, Sex and Address and corresponding functions can be Add the data and change
the age. So class Human will have Data Members as Name, Age, Sex and Address and its methods can
be Add(), ChangeAge() etc.
Features of Object Oriented Programming
46 | P a g e
Abstraction
Abstraction is the capability of hiding inner details so that we should not worry about inner or
implementation details. For example, we know how to drive a car by knowing clutch handling,
accelerator, break and other essential functioning. But we are not worried about the internal details
such as wiring etc. This is an example of abstraction.
In Java, Abstraction is implemented by creating class. A class hides its inner details and provides methods
to work with the objects. In this way a class implements Abstraction. For example:
classHuman
{
private:
String Name;
int Age;
String Sex;
String Address;
public:
void Add()
{
Name = jTextField1.getText();
Age = Integer.parseInt(jTextField2.getText());
Sex = jTextField3.getText();
Address = jTextField4.getText();
}
voidchangeAge(int A)
{
Age = A;
}
};
Any object of this class can access only methods Add() and changeAge() and all internal details are hidden
from outside world.
Encapsulation
Encapsulation is the property of Object Oriented Programming which enables wrapping of data and its
corresponding functions together in a single unit. In java class implements encapsulation along with
abstraction. In the above example there are four data members and two functions in the same class.
Polymorphism
Polymorphism is the ability of a method to execute in many forms. In OOP there is a provision by which
an operator or a method exhibits different characteristics depending upon different sets of input
provided to it. This feature in OOP is known as Polymorphism.
In java, Polymorphim can be of two types – method overloading and operator overloading.
Method Overloading
Method overloading is where a method name can be associated with different set of
argumetns/parameters and method bodies of the same class. substring() method of the String class is a
good example of method overloading. For example if single argument is passed to the substring()
method then it returns all characters from the start position to the end of the string whereas if two
arguments are passed to the substring() method then it returns a substring of the characters between
the two specified positions of the string. This simply means that the substring() method is overloaded on
the basis of the number of arguments supplied to it. For example:
String str = “Good Morning”, str1, str2;
str1 = str.substring(5);
str2 = str.substring(0,4);
Now, str1 will hold “Morning” whereas str2 will hold “Good”.

Operator Overloading
Operator Overloading is another example of polymorphism. Just as method can be overloaded,
operators can also be overloaded. A very good example of operator overloading is the + operator which

47 | P a g e
returns the sum of two numbers if the operands are numbers but returns the concatenated string if one
or both the operands are characters or strings. For example:
String str1 = “Hello”, str2 = “There”;
String str3 = str1 + str2;
int n1 = 10, n2 = 20;
int n3 = n1 + n2;
Here str3 will have “HelloThere” n3 will have value 30.

Inheritance
Inheritance is the most powerful feature of Object Oriented Programming, after Classes themselves.
Inheritance is a process of creating new class (called derived class or sub class or child class) from already
existing class (called base class or super class or parent class). The derived classes not only inherit
capabilities of the base class but also can add new feature of their own. The process of inheritance does
not affect the base class.
For example consider the following class Vehicle:
Class Name Vehicle
Data Members Colour, Height
Methods getColour(), getHeight()
Now if a new class Car is needed to be prepared then we know that since car is also a vehicle then class
Vehicle can be derived to make the new class Car. After deriving the class Car will be like:
Class Name Car
Data Members Colour*, Height*, Type
Methods getColour()*, getHeight()*, setType()
Here * represents the derived members.
In java a class can be derived using the keyword extends.
If you look at the pre-fabricated code in any of your application (JFrame Form) created in NetBeans, you
will observe that javax.swing.JFrame acts as a base class (super class) and the name given by you for the
JFrame Form acts as the name for the derived class (sub class). Each new JFrame form added to the
application inherits all the features of the javax.swing.JFrame class. The code of one such application is
shown below:
public class Example extends javax.swing.JFrame
{
/** Creates new form named Example */
public Example()
{
initComponents();
}
}
The most important aspect of inheritance is that it allows reusability of code, and also a debugged class
can be adapted to work in different situations. Reusability of code saves money as well as time and
increase program reliability. Inheritance is very useful in original conceptualization and design of a
programming problem.
Abstract Class and Concrete Class
The classes for which objects are required to be declared are known as concrete class like JLabel,
JTextField, JComboBox etc. The classes for which it is not essential to declare objects to use them are
known as abstract classes like JOptionPane. Abstract classes are normally used as base class in
inheritance for which no direct object is required to be created. Also abstract classes are used for
defining generic methods where there is no requirement of storing results. Abstract class can work as
base class from which other classes can be derived.
JOptionPane class is an abstract class which has no data members so it will not be able to store any
values. The reason behind this is that because we cannot create objects of an abstract class, so we will
not be able to provide any data to this class. Therefore, there is no point of having a data member.

48 | P a g e
Chapter -5
Advanced java Libraries

Key Points:-
49 | P a g e
IDE- Integrated development Environment:
 A programming environment, where all the tools required for programming are
available under one roof is called IDE.
RAD- Rapid Application Development:
 A programming style which aims at building programs fastly through the use of
tools and wizards is called RAD.
Token:
 The smallest individual unit in a program is known as Token. Java has the
following types of tokens: keyword, Identifier, literal, punctuators and operators.
Keywords:
 Keywords are words that have a specific predefined meaning in Java. They
cannot be used as variable names. They are also known as reserve words. Eg.
void, private, if, while etc.
Literals:
 items having fixed data values are referred to as Literals. They are also known
as Constants. Various types of literals available in Java are :
• integer literals
• Floating literals
• Boolean literals
• Character literals
• String literals
• Null literals
Variable:
 Variable is a named storage location in computer memory whose contents can
change during a program run.
Data Type:
 Data type helps us identify the type and the range of value that can be stored in avariable. For
example a short data type variable in java can store only nondecimalvalues in the range -32768
to 32767. Various primitive data typesavailable in java are byte, short, int, long, float, double,
char and Boolean
Commonly available Swing Controls in Java
jFrame: A Frame is a container control, in which all the controls can be lace.
jLabel: JLable allows placing un-editable text on the Frame/Panel
jTextField: JTextFeild allows placing editable text on the Frame/Pane. User can enter text in a textFiled
during runtime.
jbutton: is used to initiate an action when it is clicked.
jList: is a group of values or items from which one or more selections can be made.
jComboBox: jComboBox is similar to jList but also allow to enter editable text during run time. It is a
combination of jTextFiled and jList.
jRadioButton: Allow us to choose a single item from a group of jRadioButton options.
jCheckBox: Allow us to choose one or more items from a group of jCheckBox options.
jPasswordField: Allow us to enter a text during the run time but shows an encrypted text instead of
the original text
jTextArea: JTextArea is a multi-line text component to enter or edit text.
Focus: The control under execution is said to have the focus. The control having the focus obtains input
form the user.
getText(): getText() method is used to obtain the text from a jTextFeild during the run time.
setText(): setText() method is used to set or change the text of a jTextFeild during run time.

Chapter 6
DATABASE CONNECTIVITY TO MYSQL

50 | P a g e
As we know storing the data is an important work, we need data connectivity. In order to
connect to the database from within an application, we need a framework that helps to send and
execute SQL statement from within the application code.

MYSQL provides connectivity for client applications developed in the Java programming language via
JDBC driver, which is called “MYSQL Connector/J”.

There are four main classes in the JDBC API for database connectivity:

(i) Driver Manager Class: It locates and logs on to the database and returns a connection
object.
(ii) Connection Class: It manages the communication between Java & MySQL.
(iii) Statement Class: It contains SQL string that is submitted to the database. An SQL
Selectstatement returns a ResultSet object that contains the data retrieved as the result of SQL
statement.
(iv) ResultSet Class: A result set is the logical set of records that are fetched from the database
byexecuting a query and made available to the application program. It accesses, analyzes and
converts data values returned by the SQL select statement.

Steps for Creating Database Connectivity Application:


(i) Import the package required for database programming:
importjava.sql.Connection;
importjava.sql.DriverManager;
java.sql.Statement;
importjava.sql.ResultSet;
OR
Simply write
import java.sql.* import
(ii) Register the JDBC driver with Driver Manager:
Class.forName(“java.sql.Driver”); or Class.forName(“com.mysql.jdbc.Driver”);

(iii) Open a connection:


Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”, “root”, “tiger”);
Test is the name of SQL database, root is user id and tiger is MySQL password.

(iv) Execute a query: Create an object of type Statement using createStatement() method. Then execute
the SQL statement using executeQuery( ) method, in case of SELECT query, or executeUpdate() method,
in case of UPDATE, INSERT or DELETE or Create Table query. It returns an object of resultSet type.

Statement stmt = conn.createStatement();


String sql= “Select id, name from employee”;
ResultSetrs = stmt.executeQuery(sql);
OR

sql = “delete from employee”;


ResultSetrs = stmt.executeUpdate(sql);

ResultSet Cursor: When a ResultSet object is created, the cursor is placed just before the first row.To
move the cursor to first row use rs.next() or rs.first(). rs.next() forwards the cursor by one row – since
Initially cursor is before the first row, first rs.next() will move the cursor to first row. Any following
rs.next() commands forward the cursor by one row.

(v) Extract data from result set: This step is required if data is fetched from the database i.e., incase of
SELECT query. To retrieve the data ResultSet.getXXX() method is used. i.e., getInt(), getLong(),

51 | P a g e
getString(), getFloat(), getDate() etc. All these method takes parameter as Column Name or Column
Index. Column Index is the order of the column.
int id = rs.getInt(“id”); // if more than one column exists in result set with same
Column Name then the first one is returned.
Or
int id = rs.getInt(1); // If id is first field of table.
String name = rs.getString(“name”);

Retrieving data from result set if it contains multiple rows:


Use rs.next() method. In addition to moving a result-set by one row, it also returns true if cursor is
positioned on a row and false if cursor is positioned after the last row.
int id; String name;
while (rs.next()){ id = rs.getInt(1);
name = rs.getString(2); // display or process here.}
(v) Clean up the environment: Close all database resources using close()
method.rs.close();
stmt.close();
conn.close();

Example : Suppose the GUI is as and we have to write the code for save, search, update and
delete button

The firstly add MYSQL Connector/J connector in library.


You can write following code for save button
private void SaveBTNActionPerformed(java.awt.event.ActionEventevt) {
try{
Class.forName("java.sql.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/employee","root","");
//here the name of the database is employee, the username is root and password is empty
stmt=con.createStatement();
String query="insert into user values('"+uidTF.getText()+"','"+passTF.getText()"');";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Record inserted successfully");
}
catch(Exception p) {
JOptionPane.showMessageDialog(null, p.getMessage());
}
}

Similarly you can write following code for search button

private void searchBTNActionPerformed(java.awt.event.ActionEventevt) {


try{
Class.forName("java.sql.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/employee","root","");
52 | P a g e
//here the name of the database is employee, the username is root and password is empty
stmt=con.createStatement();
String query="select * from employee where uid =”++uidTF.getText();
ResultSetrs=stmt.executeQuery(query);
uidTF.setText(rs.getString(1));
passTF.setText(rs.getString(2));
// you may also write the fieldname of table in getString function within double quote.
}
catch(Exception p) {
JOptionPane.showMessageDialog(null, p.getMessage());
}
}

Similarly we can write the code for modify and delete function.
For navigating in records where more than one record found in select operation next(),
first(), last() function can be used with the object of ResultSet class.

Sample Questions:
1. What is a connection and a result set?
2. What does Driver Manager do?
3. Write a statement to open a connection object namely myconn for a MySQL database namely
school.
4. What are the steps to connect to a database from the Java application?

Q. Differentiate between JDBC and ODBC?


Ans: JDBC (Java Database Connectivity) is developed by Sun Java for the purpose of connecting java
applications with a variety of relation database systems like MySQL or Oracle. On the other hand,
ODBC (Open Database Connectivity) is a system developed by Microsoft to connect Microsoft based
programming application (like visual basic) with a variety of relational databases.
Q. What are the main tasks of JDBC?
Ans: Mainly JDBC perform the following:
a) Establishes a connection with a relational database
b) Sends SQL queries/ statements to the database
c) Processes the results obtained from the database server.

CHAPTER 7

WEB APPLICATION DEVELOPMENT


53 | P a g e
Brief Summary of the Chapter:
World Wide Web is an example of an information protocol/service that can be used to send and
receive information over the internet. It supports:
Multimedia Information
Hyper Text Information
3.Graphical User Interface
The World Wide Web is an example of an information protocol/service that works using a Client/Server
software design. A service that uses Client/Server design requires two pieces of software to work:
Client software (e.g. Web Browser) to request information, and
Server software(Web server) to answer requests and provide their information. Most Web applications
are designed this way.
Key Points of the Chapter:
URL(Uniform Resource Locator): The uniform resource locator (URL) is the uniqueidentifier of a
web page.
Protocol :A standard set of regulations and requirements that allow two electronic itemsto
connect to and exchange information with one another. Protocols regulate data transmission
among devices as well as within a network of linked devices. E.g HTTP
Web Server: Web server delivers (serves) content, such as web pages, using the
HypertextTransfer Protocol (HTTP), over the World Wide Web.
Web Browser: A web browser is a client that initiates communication by making arequest for a
specific resource. The server then responds with the content of that resource, or an error
message if unable to do provide the contents due to any reason.
Client Server Computing: It refers to a network set-up in which programs andinformation reside
on the server and clients connect to the server for network access.
Dynamic Web Page: A dynamic document is created by web server whenever a browserrequests
the documents.
Static Web Page: A static document is a fixed content document that is created by webserver
whenever a browser requests the documents.

HTML-I : BASIC HTML ELEMENTS:-

The World Wide Web (or simply the Web or WWW) is a system of sharing interlinked hypertext
documents over the internet. These documents are stored on web-servers on the internet and
contain text, images, videos and other multimedia. These documents also contain hyperlinks to
navigate among them. HTML (Hyper Text Markup Language) is the basic language which is used to
create Hypertext documents. In this lesson we are going to learn how to create hypertext
documents using HTML.

Key Points of the Chapter:


· HTML stands for Hyper Mark-up Language.
· HTML is the subset of SGML (Standard Generalised Markup Language)
· The head of the HTML document is where you enter the title of the page.
· Headings are typically displayed in larger and/or bolder fonts than normal body text. HTML
has six levels of heading, numbered 1 to 6, with 1 being the largest.
· The BACKGROUND is the image attribute in <BODY> tag where you can place graphic
object to make more attractive Web page.
· The BGCOLOR attribute is used to set the background color of your Web page with <BODY>
tag.

54 | P a g e
· <HR> is used as a section separator and attributes used in it are width and size to specify
width and height of the line
· <BR> is used for line break in the page
· <P> tag is used to specify a paragraph body
· The <IMG SRC> tag specifies an image to be displayed in a Web page. This is an empty
element, which is coded in HTML document. It has attributes like : SRC, ALIGN, BORDER,
HEIGHT, WIDTH and ALT.
e.g. <imgsrc=”Photo.jpg” align=”center” border=” 2”>
· Links between Web pages is known as hyperlink.
· The anchor tag <A> marks the text as hypertext link.
· The HREF attribute specifies the destination of a link.
· The HREF or the name attribute must be present in the <A> tag.
· HREF is an attribute for the <A> tag, which is displayed in a browser, the work Text describing
link would appear underlined and in another order to indicate that clicking that text initiates
the hypertext link.
e.g.
<A href=” www.kvssangathan.nic.in “> Open KVS Sangathan’s website </A>Or
<A href=”myphoto.jpg”> Click to see my photo</A>

Tags are not case sensitive

55 | P a g e
HTML-II :LISTS, TABLES AND FORMS:-

Key Points of the Chapter:


Lists
The numbered/ordered list <OL>tag is used to indicate a list item as contained in an ordered
ornumbered form.
e.g.
1. Keyboard
2. Mouse
3. CPU
Bulleted/unordered list <UL>tag is used to indicate a list item as contained in an unordered orbulleted
form.
e.g.
oKeyboardoM
ouse
o CPU

<LI> list tag is used to denote the beginning of each new list item.
· The TYPE attribute is used to change the bulleted symbol in a list. The attribute may have a value
of circle, disc, or square. For example, <UL TYPE=disk>.
· The list items are marked with bullets (typically small black circles).
· The START attribute is used to change the beginning value of an ordered list. Normally, the
ordered list starts with 1. For example, <OL START = A>

Table
A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td>
tag). The letters td stands for “table data”, which is the content of a data cell.
<Table></Table> is used to specify that Table is to be created
Attributes which may be used in Table tag are Border, Align, Background, Bgcolor,
Height, Width etc.
<TR></TR> is used to specify that table row is specified
<TD></TD> is used to specify columns of the table by specifying Table Data. e.g.

COLSPAN and ROWSPAN


Table cells can span across more than one column or row. The attributes COLSPAN ("how many across")
and ROWSPAN ("how many down") indicate how many columns or rows a cell should take up.

56 | P a g e
For example, we might want to create header cells for each department in our table of names and phone
numbers. In this table, the header cells in the first and fifth rows span across two columns to indicate
the department for each group of names.
<TABLE BORDER=2 CELLPADDING=4>
<TR><TH COLSPAN=2>Production</TH></TR>
<TR><TD>RahaMutisya</TD> <TD>1493</TD></TR>
<TR><TD>Shalom Buraka</TD> <TD>3829</TD></TR>
<TR><TD>Brandy Davis</TD> <TD>0283</TD></TR>
<TR><TH COLSPAN=2>Sales</TH></TR>
<TR><TD>Claire Horne</TD> <TD>4827</TD></TR>
<TR><TD>Bruce Eckel</TD> <TD>7246</TD></TR>
<TR><TD>Danny Zeman</TD> <TD>5689</TD></TR>
</TABLE>

which gives us:

Production
RahaMutisya 1493

Shalom Buraka 3829

Brandy Davis 0283

Sales

Claire Horne 4827

Bruce Eckel 7246

Danny Zeman 5689

Forms
HTML Forms are required when you want to collect some data from the site visitor. For example during
user registration you would like to collect information such as name, email address, credit card, etc.
A form will take input from the site visitor and then will post it to a back-end application such as CGI,
ASP Script or PHP script etc. The back-end application will perform required processing on the passed
data based on defined business logic inside the application.
There are various form elements available like text fields, textarea fields, drop-down menus, radio
buttons, checkboxes, etc.
HTML Form Controls
There are different types of form controls that you can use to collect data using HTML form:
Text Input Controls
Checkboxes Controls
Radio Box Controls
Select Box Controls
File Select boxes
Hidden Controls
Clickable Buttons
Submit and Reset Button
Example:
<form method=”post” action=”datacollection.php”>
Name<input type=”text” name=”txtname”>
<br>
Name<input type=”text” name=”txtname”>
</form>

57 | P a g e
Similarly other form tags may be used . The visual example shows the FORM in the form of table so
form will be create dinside the table <td> tag. It basically nests the two major tags.

Problem 1

<html>
<body>
<P ALIGN =RIGHT>
<RIGHT><H1>PIZZA
FACTORY</H1></RIGHT><form method="post">
<p aling=right
<right><h1><hr>PIZZA ORDER
FORM</hr></h1></right>
Name
<input
type="text"name="name"/><br>
Address
<input
type="text"name="address"/><br />
<p
aling=right><right><h1>SIZE</
h1></right></p>
<input type="radio" name="size" value ="small"/>small
<br />
<input type="radio" name="size" value ="medium"/>medium
<br />
<input type="radio" name="size" value ="large"/>large
<br />

58 | P a g e
<p
aling=right><right><h1>TOPPINGS</
h1></right></p>
<br />
<input type ="checkbox"name="s1" value="cheese">cheese
<br />
<input type ="checkbox"name="s2" value="olives">olives
<br/>
<input type ="checkbox"name="s3" value="pepperoni">pepperoni
<br />
<input type ="checkbox"name="s4" value="bacon">bacon
<br />
<p>
<input type="submit"name="request" value="process
order"><input type ="reset"name="clear"value="clear">
<br />
<textarea rows="5"
cols="50"name=""></textarea>
</p>
</form>
</body>
</html>

Problem 2

59 | P a g e
<html><b
ody><for
m...> first
name:
<input type="text" name ="first_name"
/><br>
e.mail
<input type = "text" name ="e.mail" />
<p>select choose the one thing you love best of my
pages</p><br>
<input type ="radio" name ="choose the one thing you love best of my pages"

value ="that gorgeous picture of you and your dogs"/> that gorgeous picture

of you and your dog


<br>
<input type ="radio" name ="choose the one thing you love best of my pages"

value ="the inspiring recap about youe childhood" />the unspiring recap

about your childhood


<br>
<input type ="radio" name ="choose the one thing you love best of my pages"

value ="the detailed list of your hobbies"/>the detailed list of your hobbies
<br>
<p> Check all that apply:</p>
<input type ="checkbox" name = "s1" value ="i really like your web site"/>i
really like your web site
<br>
<input type ="checkbox" name = "s2" value ="one of the best site i've seen"/>
one of the best site i've seen<br>
<input type ="checkbox" name = "s3" value ="i have no taste so your site

didn't do much for me"/>i have no taste so your site didn't do much for me

<br><input type ="submit" name =" submit" value


="submit"/></form>
</body>
</html>PROB
LEM 3

60 | P a g e
<html>
<head>
<title>first page</title></head>
<body>
<table border=all><tr>
<td rowspan=3>A<br>C<br>G</td><td colspan=3>B</td>
</tr>
<tr>
<td>D</td>
<td>E</td>
<td rowspan=2>F</td></tr>
<tr>
<td colspan=2>H</td></td>
</table>
</form>
</body>
</html>

61 | P a g e
eXentensible Markup Language:-

Brief Summary of the Chapter:


It is a markup language. Markup language is a set of rules that defines the structure and format of text
while presenting text. XML stands for eXtensibleMarkup Language. XML is designed to transport,
store and describe data. Whereas HTML was designed to display data. XML tags are not predefined.
We must define your own tags in XML. An XML document that follows all grammar rules is well
formed document.
KEY POINTS OF THE CHAPTER
A markup language is a set of rules that defines the structure and format of text while
presenting text.
XML is a markup language.
A meta-language is a language that is used to define other languages.
XML is based on SGML.SGML was the first markup language.
XML is different from HTML as it does not display the data but describes and carries it.
XML is free and extensible.
XML is platform independent.
The XML document that obeys XML grammar rule is called well-formed document.
DTD (Document definition type) is a set of rules that defines what tags appear in an XML
document.
CSS (Cascading Style Sheet) are a collection of forming rules that control the appearance of
content in a webpage.
Important full forms:
(i) XML-extensible Markup Language
(ii) EDI-Electronic Data Interchange
(iii) CSS- Cascading Style Sheet
(iv) DTD- Document Type Definition

HTML versus XML


HTML XML
1 HTML document formats and displays XML documents carry data along with their

2 HTML tags are predefined New tags can be created as per our

3 HTML may not have closing tags. XML must have closing tags.

4 HTML tags are not case sensitive XML tags are case sensitive.
5 HTML documents are directly viewable XML documents are viewed only if proper
in a browser. style sheet file is also available.

62 | P a g e
CHAPTER 8
DATABASE FUNDAMENTALS (MySQL)
Brief Summary of the Chapter:
A database is any collection of related data. Restrictive: • A database is a persistent, logically coherent collection
of inherently meaningful data, relevant to some aspects of the real world.A database system is basically a
computer based record keeping system. There are different data models are available. The most popular data
model is Relational Data Model (RDBMS). In RDBMS data is arranged in the form of table. MYSQL is software to
manipulate database. It is free, open-source RDBMS. In order to access data within MYSQL database, all
programs and users must use, Structured Query Language (SQL).SQL is the set of commands that is recognized
by nearly all RDBMs. SQL commands can be classified into three categories. These are DDL (Data Definition
Language), DML (Data Manipulations Language) and TCL (Transmission Control Language). Apart from MYSQL
is commands, it has various functions that performs some operation and returns a single value. In this chapter
we will learn various commands and functions in MYSQL and its implementation.
KEY POINTS OF THE CHAPTER
Structure Query Language
A non-procedural UGL used for querying upon relational database
DDL: Data Definition Language
Part of the SQL that facilitates defining creation/modification etc. of database object such as tables,
indexes, sequences etc.
DML: Data Manipulation Language.
Part of the SQL that facilitates manipulation (additions/deletions/modification) of data which residing
in the database tables.
Meta Data
Facts/data about the data stored in table.
Data Dictionary
A file containing facts/data about the data stored in table
Relational Data Model
In this model data is organized into tables i.e. rows and columns. These tables are called relations.
The Network Data Model
In this model data are represented by collection of records & relationships among data. The
collections of records are connected to one another by means of links.
The Hierarchical Data Model
In this model records are organized as trees rather than arbitrary graphs.
Object Oriented Data Model
Data and associated operations are represented by objects. An object is an identifiable entity with
some characteristics and behavior.
Relation:
Table in Database

Domain:
Pool of values from which the actual values appearing
Tuple:
A row of a relation
Attribute:
A column of relation
Degree:
Number of attributes
Cardinality:
Number of tuples
View:
Virtual table that does not really exist in its own right
Primary Key:
Set of one or more attributes that can uniquely identify tuples with in the relation.

63 | P a g e
Candidate Key:
A Candidate Key is the one that is capable of becoming Primary key i.e., a field or attribute that has
unique value for each row in the relation.
Alternate Key:
A candidate key that is not primary key is called alternate key.
Foreign Key:
A non-key attribute, whose values are derived from the primary key of some other table.
Integrity Constraints
Integrity Constraints are the rules that a database must comply all the times. It determines what all
changes are permissible to a database.

Accessing Database in MySql :


Through USE keyword we can start any database
Syntax:
USE <database Name>;
Example: USE STUDENT;

CREATING TABLE IN MYSQL


Through Create table command we can define any table.
CREATE TABLE <tablename>
(<columnname><datatype>[(<Size>)],……..);
CREATE TABLE Student(SRollNo integer, Sname char(20));

INSERTING DATA INTO TABLE


The rows are added to relations using INSERT command.
INSERT INTO <tablename>[<columnname>]
VALUES (<value>, <value>…);
INSERT INTO student (Sid, Sname)
VALUES (100,’ABC’);

SELECT COMMAND:
It lets us make queries on the database.
SELECT * FROM tablename WHERE condition;
SELECT * FROM student WHERE Sid=100;

Eliminating Redundant Data


DISTINCT keyword eliminates redundant data
SELECT DISTINCT Sid FROM Student;

Selecting from all the rows-ALL Keyword


SELECt ALL Sid FROM Student;

Viewing structure of table:


DESCRIBE/DESC <tablename>;
DESCRIBE student;
Using column aliases:
SELECT <column name> AS [columnalias][,…]
FROM <tablename>;
SELECT rollno, name AS “studentname”
FROM student;

Condition based on a range:


Keyword BETWEEN used for making range checks in queries.
SELECT rollno, name FROM student WHERE rollno BETWEEN 10 AND 20;
Condition based on a list:
Keyword IN used for selecting values from a list of values.
SELECT rollno, name FROM student WHERE rollno IN (10, 20, 60);
64 | P a g e
Condition based on a pattern matches:
Keyword LIKE used for making character comparison using strings
percent(%) matches any substring
underscore(_) matches any character
SELECT rollno, name FROM student WHERE name LIKE ‘%ri’;
ORDER BY clause:
It is used to sort the results of a query.
SELECT <column name> [, <column name>, …]
FROM <table name>
[WHERE <condition>]
[ORDER BY <column name>];
SELECT *
FROM student
WHERE marks>50
ORDER BY name;
MySQL functions:
A function is a special type of predefined command set that performs some operation and
returns a single value.
String functions :(Lower / LCASE( ), Upper/UCASE( ), Concate( ), Instr( ), Length( ),
RTrim( ), LTrim( ), Substr( ) )
Numeric function :(Round( ), Truncate( ), Mod( ), Sign( ) )
3.Date functions:(Curdate( ), Date( ), Month( ), year( ), DayName( ), DayofMonth( ),
DayofWeek( ), DayofYear( ), Now( ), SysDate( ))

Creating tables with SQL Constraint :


CREATE TABLE command is used to CREATE tables
CREATE TABLE tablename
(columnnamedatatype size, …);

SQL Constraint:
A Constraint is a condition or check applicable on a field or set of fields.
NOT
NULL/UNIQUE/DEFAULT/CHECK/PRIMARY
KEY/FOREIGN
KEY
Constraint:
CREATE TABLE student (Srollno integer NOT NULL, …);

CREATE TABLE student (Srollno integer UNIQUE …);

CREATE TABLE student (Srollno integer NOT NULL, Sclass integer, Snamevarchar(30),
Sclass DEFAULT 12 );

CREATE TABLE student (Srollno integer CHECK (Srollno>0), Sclass integer, Sname
varchar(30));

CREATE TABLE student (Srollno integer NOT NULL PRIMARY KEY, Sclass integer,
Snamevarchar(30));

CREATE TABLE teacher (Tid integer NOT NULL, FOREIGN KEY (Studentid )
REFRENCES student (Sid));

Inserting data into table:


INSERT INTO command is used to insert data into table

INSERT INTO tablename VALUES (value1,….);

INSERT INTO student VALUES (1,’Ram’, 12);


65 | P a g e
Modifying data in tables:
Existing data in tables can be changed with UPDATE command.

UPDATE student SET Sclass=11 WHERE Sname=’Ram’;

Deleting data from tables:


Tuples in a table can be deleted using DELETE command.

DELETE FROM student WHERE Srollno>10;

SOLVED QUESTIONS

1. What do you mean by a Database Management System?

Ans- Database Management is a collection of programs and files that allow a user to define structure of a
database, store data into it, modify the structure and manipulate the data.
2. What do you mean by Relational database?

Ans-Relational Database is a type of database in which relation is used as its basic element.Row and
columns are used to store data.
3. What is a foreign key?

Ans If a key is available in a table as a primary key then this key is called foreign key in another table.
4. What is primary key?

Ans-Primary key is a unique key in a relation which can uniquely identifies a tuple (row) in a given
relation.
5. What is SQL?

Ans-SQL is stands for structured query language. This language is used to manipulate data stored in a
table.
6. What is referential integrity?

Ans-This is a rule which ensures that in DBMS relationships between records in related tables are
valid. And that user don’t accidently delete or change related data.
7. What is MySql?
Ans-Mysql is an open source RDBMS which uses SQL.
8. What is DDL?

Ans- DDL provides commands to define or redefine the schema of a table.Table is created,altered and
dropped using DDL.
9. What are DML commands?

Ans- DML commands are used to manipulate data stored in a table.Insertion, deletion and modifications
are possible using DML commands.

10. Maximum how many characters can be stored in a (i) text literals (ii) numeric literal Ans-(i) Text
literals can have 4000 bytes (ii) A numeric literals can store 53 digits.

66 | P a g e
11. What is null value in MySql?
Ans-If a column in a row has no value, then column is said to be null.

12. Which keyword eliminates redundant data in from a query result? Ans-
DISTINCT
13. How would you display system date as the result of a query?
Ans- CURDATE()
14. What is NOW() function in MySql? Ans- It
returns the current date and time.
15. What is NOT NULL constraint?
Ans- NOT NULL constraints impose a condition that value of a row cannot be left blank.
16. What is error in following statement?
UPDATE EMPL;
Ans- WHERE clause is missing in given query.
17. Identify the error?
DELETE ALL FROM TABLE EMP;
Ans-There is no need to write ALL and TABLE word in above query. Correct
form is-DELETE FROM EMP;
18. Differeniate WHERE and HAVING clause?
Ans-:- Where clause is used to select particular rows that satisfy condition whereas having clause is used
in connection with aggregate function, group by clause.
19. How SQL commands are are classified?
Ans-SQL Commands are classified into three categories
(i)Data Definition Language (DDL)-Commands that allow us to perform tasks related to data
definition. E.g. creating, altering and dropping

(ii) Data Manipulation Language (DML) - Commands that allows us to perform data manipulation
e.g retrieval, insertion, and modification of data stored in a database.

(iii) Transaction Control Language (TCL)-Commands that allow us to manage and control the
transactions.
20. What is difference between char and varchar?
Ans-The difference between char and varchar is that of fixed length and variable length.The CHAR datatypes
specifies a fixed length character string.When a column is given datatype as CHAR(n) then MySQL ensures that
all values stored in that column have this length.But on other hand when a column is given datatype as
VARCHAR(n) ,then the maximum size of a value in this column stores exactly what we specify.
21. What do you understand by the terms primary key and degree of a relation in relational data base?
Ans: Primary Key: A primary key is a set of one or more attributes that can uniquely identify tuples within the
relations. The number of attributes in a relation is called Degree of arelation in relational data base.
22. What do you understand by the candidate key and cardinality of a relation in relational data base?
Candidate Key: All attribute combinations inside a relation that can serve as primary key(uniquely identifies a
row in a relation) are Candidate Keys as they are candidates for the primary key position. The number of rows
in a relation is known as cardinality of a relation.

67 | P a g e
CHAPTER 9:
ADVANCED MYSQL
Learning Objectives
After studying this lesson the students will be able to:
Define the terms:
(i) Group (Aggregate) functions, Constraints
(ii) Cartesian Product, Join, Referential Integrity, Foreign Key.
Write queries using aggregate functions and GROUP BY clause.
Access data from multiple tables
Create tables with PRIMARY KEY and NOT NULL constraints
Add a constraint to a table, remove a constraint from a table, and modify a column of a table
using ALTER TABLE command.
Delete a table using DROP TABLE
SQL Aggregate (Group) Function: These function operates on group of rows instead of single
row that is why these functions are known as group or aggregate functions. Some important
group functions are as follows:
TABLE:Student
Rollno Sname Subject Marks grade
001 SUMIT MATHS 95 A
002 SHERRY IP 96 A
003 SUMAN IP 75
004 LALIT HINDI 84 B
005 RAHUL MATHS 88 B

Name of Purpose/Use Syntax or Example OUTPUT


the
MAX() Returns the MAXIMUM values in a Mysql> select max(marks) from 96
specified column student;
MIN() Returns the MINIMUM values in a Mysql> select min(marks) from 75
specified column student;
SUM() Returns the SUM of values in given Mysql> select sum(marks) from 438
column/expression. student;
AVG() Returns the AVERAGE value in the Mysql> select avg(marks) from 87.6
specified column/expression. student;
COUNT() Returns the total number of non null Mysql> select count(grade) 4
values in a column. from student;
COUNT(*) Returns the total no of rows Select Count(*) from student; 5

TYPES OF FUNCTIONS:
Single Row Function: It works with a single row at a time. A single row function returns a result for
every row of the queried table
Multiple Row or Group Function: It works with data of multiple rows at a time and returns aggregate
values.
The main difference between these two functions is in the number of rows they act upon.

68 | P a g e
Grouping Result by using Group By: The GROUP BY clause is used in a select statement in
conjunction with aggregate functions to group the result based on DISTINCT or ALL values in
a column. Grouping can be done by column name, or with aggregate functions in which case
the aggregate produces a value for each group. Example:
Mysql> select count (marks) from student Group By subject;
Mysql> select SUM (marks) from student Group by Subject;
OUTPUT:
Conditions on Group-Having Clause: We can use any condition on group, if required. HAVING clause is
used to apply a condition on a group.
Mysql> select SUM (marks) from student Group By subject having MAX(marks)>80; OUTPUT:
HINDI 84
MATHS 183
IP 96
Mysql> Select SUM (marks) from student Group By subject having COUNT (*)>1; OUTPUT:
MATHS 2
IP 2
JOINS: A join is a query that combines rows from two or more tables. In a query involving join, more than one
table is listed in FROM clause separated by comma (,).
EXAMPLE: SELECT * FROM EMP1, DEPT;

CROSS JOIN (Cartesian product): Cartesian product of two tables is a table obtained by
pairing each row of one table with each row of the other. It contains all the columns of both
tables. e.g. mysql> SELECT * FROM Order, product ;
Note:-In final table cardinality will be multiplication of rows of both tables and degree will be addition of
columns of both tables.
Order Product
code Name Qty
P101 SOAP 20
SN Pcode scode
P102 OIL 10
1 P101 S002
2 P102 S003

(After Cross Join following output will be produced)


SN Pcode scode code Name qty
1 P101 S002 P101 SOAP 20
2 P102 S003 P101 SOAP 20
69 | P a g e
1 P101 S002 P102 OIL 10
2 P102 S003 P102 OIL 10
This table will contain (2*2=4) rows and (3+3=6) Columns.
EQUI JOINS:
The Joins, in which a column is compared for equality, is called Equi-Join. The Join Column is a column which is
common in both tables.
SQL Statement: mysql> SELECT * FROM Order, product where order.pcode=product.pcode;
(After Equi Join following output will be produced)
SN Pcode scode Pcode Name qty
1 P101 S002 P101 SOAP 20
2 P102 S003 P102 OIL 10
MySQL creates a Cartesian product of the tables; from this Cartesian product MySQL select only those records
for which Pcode of order table matches with code of product table.
NON EQUI JOINS:
Non equi join is a query that specifies some relationship other than equality between
the columns. It means that records are joined on the condition other than Equal
operator (<,>,<>,>=,<=) for joining column.

NATURAL JOINS: The join in which one of the identical columns exist, is called Natural
Join. The natural join is much similar to Equi-Join, records are joined on the equality
condition of joining column except that the common column appears one time.
(After Natural Join following output will be produced)

SN Pcode scode Name Qty


1 P101 S002 SOAP 20
2 P102 S003 SOAP 20

Joining Tables Using Join Clause of SQL Statement: MySQL offer two ways by which you may
join two or more tables. One is using multiple tables with FROM clause and using JOIN
keyword with FROM clause.
Using multiple tables with FROM clause
Select * from Student, Stream where student.scode= stream.scode;
Table: Student Table: Stream
Scode Stream
RNO Name Subject Fee Scode
S101 Science
101 RAM MATHS 1000 S101
C102 Commerce
102 SHAM ECO 800 C102
H103 Humanities
103 RITU ENG 500 H103
104 SHERRY PHY 1200 S101

OUTPUT
RNO Name Subject Fee Scode Stream
101 RAM MATHS 1000 S101 Science
102 SHAM ECO 800 C102 Commerce
103 RITU ENG 500 H103 Humanities
104 SHERRY PHY 1200 S101 Science

70 | P a g e
Using multiple tables with FROM clause
Select RNO, Name from student join streams on student.scode= streams.scode where
stream=”Science”
OUTPUT
RNO Name Stream
101 RAM Science
104 SHERRY Science
UNION:-The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The
columns must also have similar data types. Also, the columns in each SELECT statement must be in the
same order.

Syntax : UNION

SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the ALL
keyword with UNION.

Syntax :- UNION ALL

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the result-set of a UNION are usually equal to the column names in the first
SELECT statement in the UNION. The number of Columns must be same In both the tables.

INTERSECTION

First, let's explain what an INTERSECT query is. An INTERSECT query returns the intersection
of 2 or more data sets. If a record exists in both data sets, it will be included in the
INTERSECT results. However, if a record exists in one data set and not in the other, it will be
omitted from the INTERSECT results.

Intersect Query

Explanation: The INTERSECT query will return the records in the shaded area. These are the
records that exist in both Dataset1 and Dataset2.

Syntax The syntax for the INTERSECT operator in MySQL is:

SELECT expression1, expression2, ...expression_n


FROM tables
[WHERE conditions]

71 | P a g e
INTERSECT
SELECT expression1, expression2, ...expression_n
FROM tables
[WHERE conditions];
Although there is no INTERSECT operator in MySQL, you can easily simulate this type of query using either the
IN clause or the EXISTS clause, depending on the complexity of the INTERSECT query.

Integrity Constraints:
One of the major responsibility of a DBMS is to maintain the Integrity of the data i.e. Data being stored in the
Database must be correct and valid.

An Integrity Constraints or Constraints are the rules, condition or checks applicable to a column or table which
ensures the integrity or validity of data.
Most of the constraints are applied along with Column definition which are called Column-Level (in-line
Constraints),but some of them may be applied at column Level as well as Table-Level (Out-line constraints) i.e.
after defining all the columns with CREATE TABLE command. Ex.- Primary Key & Foreign Key
The following constraints are commonly used in MySQL.

Constrains Role
NOT NULL Ensures that a column cannot have NULL
value.
DEFAULT Provides a default value for a column,
when nothing is given with INSERT
command.
UNIQUE Ensures that all values in a column are
different.
CHECK Ensures that all values in a column satisfy
certain user defined condition.
PRIMARY KEY Used to identify a row uniquely.
FOREIGN KEY Used to ensure Referential Integrity of the
data.

UNIQUE v/s PRIMARY KEY


UNIQUE allows NULL values but PRIMERY KEY does not.
Multiple columns may have UNIQUE constraints, but there is only one PRIMERY KEY constraints in a table.
Implementing Primary Key Constraints:
Defining Primary Key at Column Level:

mysql> CREATE TABLE Student


( StCode char(3) NOT NULL PRIMARY KEY,
Stnamechar(20) NOT NULL,
………………………..);
Defining Primary Key at Table Level:

mysql> CREATE TABLE Student


( StCode char(3) NOT NULL,
Stnamechar(20) NOT NULL,
………………………..
PRIMARY KEY (StCode));
Example:
mysql> CREATE TABLE Student
(StCodechar(3) NOT NULL PRIMARY KEY,
Stnamechar(20) NOT NULL,
StAddvarchar(40),
AdmNochar(5) UNIQUE,

72 | P a g e
StSexchar(1) DEFAULT ‘M’,
StAge integer CHECK (StAge>=5) );

Implementing Foreign Key Constraints: A Foreign key is non-key column in a table whose value is derived
from the Primary key of some other table.
Each time when record is inserted or updated in the table, the other table is referenced. This constraint is also
called Referential Integrity Constraints.
This constraint requires two tables in which Reference table (having Primary key) called Parent table and table
having Foreign key is called Child table.

Let us take two table Employee and Department as per given columns-

The following command can be given to implement Foreign key constraint-

Modifying Constraints:
Some time it is required to modify the defined constraints after creating a table. ALTER command can be used
to modify (adding/deleting of columns) Table structure as well as modifying constraints.
Adding new column and Constraints
ALTER TABLE <Table Name>ADD<Column>[<data type><size>][<Constraints>]
Example:
mysql> ALTER TABLE Student ADD (TelNo Integer);
mysql> ALTER TABLE Student ADD (Age Integer CHECK (Age>=5));
mysql> ALTER TABLE Emp ADD Sal Number(8,2) DEFAULT 5000 ;
mysql> ALTER TABLE Emp ADD PRIMARY KEY (EmpID);
mysql> ALTER TABLE Emp ADD PRIMARY KEY (Name,DOB);
Modifying Existing Column and Constraints
ALTER TABLE <Table Name>MODIFY<Column>[<data type><size>] [<Constraints>]
Example:
mysql> ALTER TABLE Student MODIFY Name VARCHAR(40);
mysql> ALTER TABLE Emp MODIFY (Sal DEFAULT 4000 );
mysql> ALTER TABLE Emp MODIFY (EmpName NOT NULL);

73 | P a g e
Removing Column & Constraints

ALTER TABLE <Table Name>DROP<Column name> |<Constraints>


Example:
mysql> ALTER TABLE Student DROP TelNo;
mysql> ALTER TABLE Emp DROP JOB, DROP Pay;
mysql> ALTER TABLE Student DROP PRIMARY KEY;

Changing Column Name of Existing Column


ALTER TABLE <Table Name>CHANGE<Old name><New Definition>
Example:
mysql> ALTER TABLE Student CHANGE Name Stname Char(40);
To View the Constraints

The following command will show all the details like columns definitions and constraints of EMP table.
mysql> SHOW CREATE TABLE EMP;
Alternatively you can use DESCribe command:
mysql> DESC EMP;
Enabling / Disabling Foreign Key Constraint
You may enable or disable Foreign key constraints by setting the value of FOREIGN_KEY_CHECKS variable.
You can’t disable Primary key, however it can be dropped (deleted) by Alter Table… command.
To Disabling Foreign Key Constraint
mysql> SET FOREIGN_KEY_CHECKS = 0;
To Enable Foreign Key Constraint
mysql> SET FOREIGN_KEY_CHECKS = 1;

Very Short Answer Type Question (1 Marks)


1. What is single row and multiple row functions?
2. What is the significance of Group By clause in MYSQL?
3. What is Join? How many types of joins are there?
4. What are joins? Why are they used?
5. How natural join differs from Equi Join?
6. What is the Cartesian product of two tables? Is it same as an Equi-join?
7. There is a column C1 in a table T1. The following two statements:
SELECT COUNT (*) FROM T1; and SELECT COUNT(C1) from T1; are giving different
outputs. What may be the possible reason? What is the significance of NOT NULL
constraints?
8. There are two tables T1 and T2 in a database. Cardinality and degree of T1 are 2 and 4
respectively. Cardinality and degree of T2 are 3 and 2 respectively. What will be the degree and
Cardinality of their Cartesian product?
9. Do aggregate Functions consider Null values? Does NULL play any role in actual calculations?
10. Write a query to delete a column pincode from the table employee?
11. Write a query to display the highest marks of each subject where Max marks is more than 90
from table student
12. Write a statement to disable the constraints of table.
13. Write a query to display the number of employees in each department in table emp.

74 | P a g e
CHAPTER 10
CONCEPT OF DATABASE TRANSACTION
Transaction
Suppose you want to transfer Rs. 1000/- from account no 101 to account no 201 in the column Balance of table
Customer. What command will you use? Answer is that it cannot be done through one single command.
Following two commands will be used for the above mentioned task:
UPDATE Customer SET Balance = Balance – 1000 WHERE AcctNo = 101;
UPDATE Customer SET Balance = Balance + 1000 WHERE AcctNo = 201;
Here you can see first Rs. 1000/- is deducted from AcctNo 101 and then Rs. 1000/- is added to AcctNo 201.
Suppose for some reasons only first statement gets executed and second statement does not get executed.
What will happen then?
Yes, you are right. AcctNo 101 gets deduced but 201 does not get added. Thus, our task remains incomplete.
Not only that we have an inconsistency of Rs. 1000/- with our data.
In database as well as in real life there are several situations where a task cannot be completed in one single
statement. These situations are called Transactions.
“A Transaction if a unit of work that must be done in logical order and successfully as a group or not done at
all.” Unit of work means that a Transaction consists of different task but together they are considered as one
unit.
Each transaction has a beginning and an end. If anything goes wrong in between the execution of transaction,
the entire transaction should be cancelled. If it is successful, then entire transaction should be saved to the
database.
In the above example, if the transaction fails after execution of first statement then updates done by first
statement should be undone to maintain the database in a consistent state.

ACID Properties
To ensure data integrity, the database systems maintain the following properties of transaction called ACID
properties:
1. ATOMICITY: This property ensures that either all operations of the transaction are reflected properly in
the database, or none are. This property ensures “All-or-none” operations are carried out i.e., the
transaction runs to completion as an indivisible unit, at the end of which either no changes will be made
to the database or all changes will be made to it. According to this property a transaction can have only
two states: Done or Never-Started.
2. CONSISTENCY: This property implies that if the database was in a consistent state before the start of
transaction-execution, then upon termination of transaction, the database will also be in a consistent
state.
3. ISOLATION: This property implies that each transaction is unaware of other transactions executing
concurrently in the system. It indicates that actions performed by a transaction will be isolated or hidden
from outside the transaction until the transaction terminates.
4. DURABILITY: This property of a transaction ensures that after the successful completion of a transaction
the changes made by it to the database persist, even if there are system failures.

START TRANSACTION Statement


START TRANSACTION statement commits the current transaction and starts a new transaction. It tells MySQL
that the transaction is beginning and the statements that follow should be treated as a unit, until the transaction
ends. It is written like this:
START TRANSACTION;

COMMIT Statement
The COMMIT statement is used to save all changes made to the database during the transaction to the database.
Commit statement is issued at a time when the transaction is complete-all the changes have been successful
and the changes should be saved to the database. COMMIT ends the current transaction.
COMMIT statement is used like this:
COMMIT;
Or
75 | P a g e
COMMIT WORK;
Here WORK is a keyword and is optional.
Example:Consider the following table Customer:
AcctNo Name AcctType Balance
101 Amar Savings 20000.00
102 Vishal Current 55000.00
201 Vishakha Savings 99000.00
Now the following statements are executed:
START TRANSACTION;
UPDATE CUSTOMER SET BALANCE = BALANCE + 1000 WHERE ACCTNO = 201;
UPDATE CUSTOMER SET BALANCE = BALANCE – 2000 WHERE ACCTNO = 101;
COMMIT;
Now the resultant table will be:
AcctNo Name AcctType Balance
101 Amar Savings 18000.00
102 Vishal Current 55000.00
201 Vishakha Savings 100000.00
Here you can see that after commit statement all changes made to the database has been reflected and saved.

ROLLBACK Statement
When a transaction is being executed, some type of error checking is usually performed to check whether it is
executing successfully or not. If not, the entire transaction is undone using the ROLLBACK statement. The
ROLLBACK statement cancels the entire transaction i.e. it rolls the transaction to the beginning. It aborts any
changes made during the transaction and the state of database is returned to what it was before the transaction
began to execute and does not save any of the changes made to the database during the transaction. ROLLBACK
statement is used like this:
ROLLBACK;
Or
ROLLBACK WORK;
Example:Consider the table Customer:
AcctNo Name AcctType Balance
101 Amar Savings 20000.00
102 Vishal Current 55000.00
201 Vishakha Savings 99000.00
Now the following statements are executed:
START TRANSACTION;
UPDATE CUSTOMER SET BALANCE = BALANCE + 1000 WHERE ACCTNO = 201;
UPDATE CUSTOMER SET BALANCE = BALANCE – 2000 WHERE ACCTNO = 101;
Status of table Customer till the execution of the above statements will be:
AcctNo Name AcctType Balance
101 Amar Savings 18000.00
102 Vishal Current 55000.00
201 Vishakha Savings 100000.00
Now if we issue the following statement:
ROLLBACK;
Then the result will become:
AcctNo Name AcctType Balance
101 Amar Savings 20000.00
102 Vishal Current 55000.00
201 Vishakha Savings 99000.00
Here you can see that both changes made to the table have been undone due to execution of ROLLBACK
statement.

76 | P a g e
SAVEPOINTS
The SAVEPOINT statement defines a marker in a transaction. These markers are useful in rolling back a
transaction till the marker.
We can add savepoint anywhere in a transaction. When you roll back to that savepoint, any changes made to
the database after the savepoint are discarded, and any changes made before the savepoint are saved. It is like
semicomitting a transaction. To define a Savepoint, we enter the SAVEPOINT statement like this:
SAVEPOINT <savepoint_name>;
Example:Consider the table Customer:
AcctNo Name AcctType Balance
101 Amar Savings 20000.00
102 Vishal Current 55000.00
201 Vishakha Savings 99000.00
Now the following statements are executed:
START TRANSACTION;
UPDATE CUSTOMER SET BALANCE = BALANCE + 1000 WHERE ACCTNO = 201;
SAVEPOINT S1;
UPDATE CUSTOMER SET BALANCE = BALANCE – 2000 WHERE ACCTNO = 101;
ROLLBACK TO SAVEPOINT S1;
Status of table Customer till the execution of the above statements will be:
AcctNo Name AcctType Balance
101 Amar Savings 20000.00
102 Vishal Current 55000.00
201 Vishakha Savings 100000.00
Here you can see that changes made before S1 have been saved and after S1 has been undone.

AUTOCOMMIT
By default, Autocommit mode in on in MySQL. It means that MySQL does a commit after every SQL statement
that does not return an error. If it returns an error then either rollback or commit happens depending on the
type of error. If we do not want individual statement of SQL to be automatically committed, we should se the
autocommit mode to off.
When autocommit is off then we have to issue commit statement explicitly to save changes made to the
database.
The following statement sets the autocommit mode to off. It also starts a new transaction:
SET AUTOCOMMIT = 0;
The following statement sets the autocommit mode to on.:
SET AUTOCOMMIT = 1;

77 | P a g e
Chapter -11
IT- Applications
Brief Summary
Three major groups of IT applications covered in this chapter are: e-Governance,e-Business, ande-Learning.
e-Governance involves applications which are used by government agencies/ organizations
to provide better governance.
e-Business applications use technology to effectively access and deliver businessrelated services and perform
various kinds of business transactions.
e-Learning applications use technology to effectively deliver and monitor learning and
teaching processes. They help the trainer to organize and manage his/her lesson plans,
present them to students/learners, evaluate and take the feedback to enhance & fine-tune
this process in future.
An IT application has two major parts: Front-end (The user interface) and back-end(The
database).
The front-end of an IT application is usually a group of one or more forms through which
the user enters the input values and is shown the corresponding output.
The back-end of an IT application is the database in which all the data is stored. This
database resides in the server. All the data which is requested by the front-end is supplied
by back-end. A good back-end ensures sustainability, efficiency and easy modification of
the application.
Use of ICT has its social and economic impacts.
People change their way of conducting the transactions and thus save their_time, money, and
energy. Economy is impacted as ICT leads to fast completion of data transfer and data processing
jobs. ICT also brings transparency in the administration.
ICT stands for Information and Communication Technology. Like everything else that is usedby common man,
ICT (Information and Communication Technology) also has impacted the
society. ICT has impacted the society in a much wider way than any other technology. Most of
these impacts are positive, though there are some negative impacts also.
Social and Economic benefits of ICT:
• Social networking sites help people remain in touch with their nears and dears even when
they are staying on opposite sides of the globe.
• Social networking sites help like-minded people come together and work for some cause.
• e-Governance sites help people save their productive time by performing various
government related jobs like getting some forms, depositing bills online.
• ICT helps economy grow at a faster rate as it provides transparency in the processes and
helps the government to keep check on defaulters.
• Due to e-Banking and use of plastic money more money is put in circulation leading to
faster growth of GDP.
• e-Learningsites make quality study material available even to the students staying at
remote places.
e-Business- To reach the customers and business associates in an effective and fast manner
business houses (now a days many small shops like snacks corners and paan shops also) provide
their services on the net.
These ICT enabled counters are used to get orders and feedbacks from the customers and also for
inter-business transactions. This helps the businesses to widen their customer base.
1. Amazon.com ( e-Business site of Amazon.com) - Amazon is the world's largest online
store. Through this URL Amazon does its online business
2. flipkart.com – Very popular online shopping store offering a range of products at very
reasonable prices.
e-Learning : e-Learning has multiple goals. It is much more than having a net connection and/or
CDs through which people learn. E-Learning is about giving freedom to people to learn whatever
they want to learn and whenever they want to learn. This is irrespective of (except in exceptional
cases) age, caste, gender, economical background, or qualification of the learner. The only
requirement is the will to learn. E-learning is available on almost all the topics imaginable.
1. www.khanacedemy.com (e-Learning site) - You will access free tutorials in all web
78 | P a g e
development technologies and almost on any topic of learning from a vast variety of subjects.
Matter is available in interactive video formats.
2. www.cbsecsnip.in - It is an educational site where subject content and solved papers are present
along with sample projects , from which students can benefit.
3. www.kvselearning.in- This portal provides interactive modules for students to learn various
topics on informatics practices using interactive video lessons.
CLOUD COMPUTING( Future trends)
This means that cloud computing is a type of Internet-based computing, and it consists of every
situation where the use of IT resources by an entity, including a person or an organization.
Properties of cloud computing are :
Access to the resources is:
 Controlled by the entity, and restricted by them to their authorized users.
 Delivered via the Internet to all of these users.
 The resources are:
 Hosted by a service provider on behalf of the entity.
 Dedicated to their exclusive use.
 Data processed by the resources is:
 Private to the entity and its associates.
 Entered or collected by them, or automatically produced for them

 Text Field: Text Field is used to get small textual information like Name, RollNo, email
address, quantity, etc.
 Text Area: Text Area is used to get long textual information which may span multiple lines
of text. E.g. to get Address, Complaint, Suggestion etc.
 Radio Button: Radio buttons are used to get an option out of several mutually exclusive
(out of which only one can be selected) options. Examples of such options are Gender
(Male or Female or Other), Type of Credit Card (Master or Visa or Other), Type of
internet connection (DialUp or Braodband), etc.
 Check Box: Check boxes are used to get one or more options out of several given options
which are not mutually exclusive. Examples of such options are Hobbies (a user may have
zero or more hobbies), Magazines to subscribe for (a user may subscribe to zero or more of
the given magazines) etc.
 List: A list is used to get one or more options out of several given options which may or
may not be mutually exclusive. This may seem to be the case where Check Boxes are to be
used, but the difference is in the number of options available. If the number of options is
small, then Check Boxes can be used. In case of large number of options, using Check
Boxes may take up a lot of space on the form and it may also be inconvenient for the user
to select the desired options. In such cases Lists are preferred over checkboxes. Examples
of such cases are: To select cities out of a given list of cities, to select magazines out of a
given list of magazines, etc.
 Combo Box: A Combo Box is used to get an option out of several given options which are
mutually exclusive. This may seem to be the case where Radio Buttons are to be used, but
the difference is in the number of options available. If the number of options is small, then
Radio Buttons can be used. In case of large number of options, using Radio Buttons may
take up a lot of space on the form and it may also be inconvenient for the user to select the
desired option. In such cases Combo Boxes are preferred over radio buttons. Examples of such
cases are: To select a city out of a given list of cities, to select a train out of a given list of trains,
etc.
 Password Field: A Password Field is used to get some secret textual information like Password, CVV
number of a credit card etc.

79 | P a g e

You might also like