Dbms Notes
Dbms Notes
C) Relational model
The relational model was introduced by E.F. Codd in 1970[1] as a
way to make database management systems more indeendent
o! any articular alication. "t is a mathematical model de!ined
in terms o! redicate logic and set theory.
The roducts that are generally re!erred to as relational
databases in !act imlement a model that is only an
aro#imation to the mathematical model de!ined by Codd. Three
key terms are used e#tensi$ely in relational database
models% relations& attributes& and domains. ' relation is a table
with columns and rows. The named columns o! the relation are
called attributes& and the domain is the set o! $alues the
attributes are allowed to take.
The basic data structure o! the relational model is the table&
where in!ormation about a articular entity (say& an emloyee) is
reresented in rows (also called tules) and columns. Thus& the
*relation* in *relational database* re!ers to the $arious tables in
the database+ a relation is a set o! tules. The columns
enumerate the $arious attributes o! the entity (the emloyee,s
name& address or hone number& !or e#amle)& and a row is an
actual instance o! the entity (a seci!ic emloyee) that is
reresented by the relation. 's a result& each tule o! the
emloyee table reresents $arious attributes o! a single
emloyee.
'll relations (and& thus& tables) in a relational database ha$e to
adhere to some basic rules to -uali!y as relations. First& the
ordering o! columns is immaterial in a table. .econd& there can,t
be identical tules or rows in a table. 'nd third& each tule will
contain a single $alue !or each o! its attributes.
' relational database contains multile tables& each similar to the
one in the *!lat* database model. /ne o! the strengths o! the
relational model is that& in rincile& any $alue occurring in two
di!!erent records (belonging to the same table or to di!!erent
tables)& imlies a relationshi among those two records. 0et& in
order to en!orce e#licit integrity constraints& relationshis
between records in tables can also be de!ined e#licitly& by
identi!ying or non1identi!ying arent1child relationshis
characteri2ed by assigning cardinality (1%1& (0)1%3& 3%3). Tables
can also ha$e a designated single attribute or a set o! attributes
that can act as a *key*& which can be used to uni-uely identi!y
each tule in the table.
Q. Describe Entity Types, Entity Sets, Attributes and Keys?
Entity Types & Sets:- An entity is a term from the entity-relationship model.A
relational model (your database schema) is one of the ways to implement the ER
model.Relational tables represent relations between simple types like integers and
strings, which, in their turn, can represent everything: entities, attributes, relationships.
An entity is any object in the system that we want to model and store
information about
Individual objects are called entities
Groups of the same type of objects are called entity types or entity sets
Entities are represented by rectangles (either with round or square
corners)
Attribute:-
All the data relating to an entity is held in its attributes.
An attribute is a property of an entity.
Each attribute can have any value from its domain.
Each entity within an entity type
o !ay have any number of attributes.
o "an have different attribute values than that in any other entity.
o #ave the same number of attributes.
Attributes can be
simple or composite
single$valued or multi$valued
Attributes can be shown on E% models
&hey appear inside ovals and are attached to their entity.
'ote that entity types can have a large number of attributes... If all are
shown then the diagrams would be confusing. (nly show an attribute if
it adds information to the E% diagram) or clarifies a point.
Q. Describe the following concepts in the context of oins?
a. Keys :- A key is an attribute (also known as column or field) or a
combination of attribute that is used to identify records. The purpose of the
key is to bind data together across tables without repeating all of the data in
every table.
(I) Super Key An attribute or a combination of attribute that is used to
identify the records uniquely is known as Super Key. A table can have many
Super Keys.
(II) Candidate Key t can be defined as minimal Super Key or irreducible
Super Key. n other words an attribute or a combination of attribute that
identifies the record uniquely but none of its proper subsets can identify the
records uniquely.
(III) Primary Key A !andidate Key that is used by the database designer for
unique identification of each row in a table is known as "rimary Key. A
"rimary Key can consist of one or more attributes of a table.
(IV) Foreign Key A foreign key is an attribute or combination of attribute in
one base table that points to the candidate key (generally it is the primary key)
of another table. The purpose of the foreign key is to ensure referential
integrity of the data i.e. only values that are supposed to appear in the
database are permitted.
(V) Composite Key f we use multiple attributes to create a "rimary Key
then that "rimary Key is called !omposite Key.
(VI) !ternate Key Alternate Key can be any of the !andidate Keys e#cept
for the "rimary Key.
(VII) Se"ondary Key The attributes that are not even the Super Key but can
be still used for identification of records (not unique) are known as Secondary
Key.
#. Per$orming a %oin :- A S$% JOIN clause combines records from two or
more tables in a database.
&'(
t creates a set that can be saved as a table or
used as is. A JOIN is a means for combining fields from two tables by using
values common to each. A)S standard S$% specifies four types of JOINs*
INNER+ OUTER+ LEFT+ and RIGHT. n special cases+ a table (base table+ view+ or
,oined table) can JOIN to itself in a self-,oin.A programmer writes a JOIN
predicate to identify the records for ,oining. f the evaluated predicate is true+
the combined record is then produced in the e#pected format+ a record set or
a temporary table.
All subsequent e#planations on ,oin types in this article make use of the
following two tables. The rows in these tables serve to illustrate the effect of
different types of ,oins and ,oin-predicates. n the following tables the
DepartmentID column of the Department table (which can be designated as
Department.DepartmentID) is the primary key+ while Employee.DepartmentID is a
foreign key.
". &istin"t and E!iminating &up!i"ates:- every field in one record is identical
to every field in a different record+ i.e. a duplicate is where there is no way of
telling two or more records apart. f you ,ust need to remove records which are
similar (i.e. one or more fields are identical but there are one or more fields
which are different) then instead refer to how to delete similar records.
To check that you have duplicate records in your table do the following*
select count(.) from MyTable
and
select distinct . from MyTable
/nfortunately there is no way in S$% to delete one of these duplicates without
deleting all of them. They are identical after all+ so there is no S$% query that
you could put together which could distinguish between them.
0hat you can do is to copy all the distinct records into a new table*
select distinct .
into NewTable
from MyTable
This query will create a new table ()ewTable in my e#ample) containing all
the records in the original table but without any records being duplicated. t will
therefore preserve a single copy of those records which were duplicated.
Q. Describe the following nor!ali"ation techni#ues?
a)T'ird (orma! Form:- The normal forms (abbrev. )1) of relational database
theory provide criteria for determining a table2s degree of vulnerability to
logical inconsistencies and anomalies. The higher the normal form applicable
to a table+ the less vulnerable it is to inconsistencies and anomalies. 3ach
table has a 4highest normal form4 (5)1)* by definition+ a table always meets
the requirements of its 5)1 and of all normal forms lower than its 5)16 also
by definition+ a table fails to meet the requirements of any normal form higher
than its 5)1.
The normal forms are applicable to individual tables6 to say that an entire
database is in normal form n is to say that all of its tables are in normal
form.3very non-prime attribute is non-transitively dependent on every
candidate key in the table.
#))oy"e-Codd (orma! Form:- )ewcomers to database design sometimes
suppose that normali7ation proceeds in an iterative fashion+ i.e. a ')1 design
is first normali7ed to 8)1+ then to 9)1+ and so on. This is not an accurate
description of how normali7ation typically works. A sensibly designed table is
likely to be in 9)1 on the first attempt6 furthermore+ if it is 9)1+ it is
overwhelmingly likely to have an 5)1 of :)1. Achieving the 4higher4 normal
forms (above 9)1) does not usually require an e#tra e#penditure of effort on
the part of the designer+ because 9)1 tables usually need no modification to
meet the requirements of these higher normal forms. 3very non-trivial
functional dependency in the table is a dependency on a superkey.
Q. Describe $arious integrity rules with a rele$ant exa!ple?
t is important that data adhere to a predefined set of rules+ as determined
by the database administrator or application developer. As an e#ample of
data integrity+ consider the tables employees and departments and the
business rules for the information in each of the tables.
Types o$ &ata Integrity
This section describes the rules that can be applied to table columns to
enforce different types of data integrity.
(u!! *u!e
A null is a rule defined on a single column that allows or disallows inserts or
updates of rows containing a null (the absence of a value) in that column.
+ni,ue Co!umn Va!ues
A unique value defined on a column (or set of columns) allows the insert or
update of a row only if it contains a unique value in that column (or set of
columns).
Primary Key Va!ues
A primary key value defined on a key (a column or set of columns) specifies
that each row in the table can be uniquely identified by the values in the key.
*e$erentia! Integrity *u!es
A rule defined on a key (a column or set of columns) in one table that
guarantees that the values in that key match the values in a key in a related
table (the referenced value).;eferential integrity also includes the rules that
dictate what types of data manipulation are allowed on referenced values and
how these actions affect dependent values. The rules associated with
referential integrity are*
;estrict* <isallows the update or deletion of referenced data.
Set to )ull* 0hen referenced data is updated or deleted+ all associated
dependent data is set to NULL.
Set to <efault* 0hen referenced data is updated or deleted+ all
associated dependent data is set to a default value.
!ascade* 0hen referenced data is updated+ all associated dependent
data is correspondingly updated. 0hen a referenced row is deleted+ all
associated dependent rows are deleted.
Comp!e- Integrity C'e".ing
!omple# integrity checking is a user-defined rule for a column (or set of
columns) that allows or disallows inserts+ updates+ or deletes of a row based
on the value it contains for the column (or set of columns).
Integrity Constraints &es"ription
An integrity constraint is a declarative method of defining a rule for a column
of a table. =racle supports the following integrity constraints*
NOT NULL constraints for the rules associated with nulls in a column
UNIQUE key constraints for the rule associated with unique column values
RI!"R# $E# constraints for the rule associated with primary identification
values
FOREIGN $E# constraints for the rules associated with referential integrity.
=racle supports the use of FOREIGN $E# integrity constraints to define the
referential integrity actions+ including*
o /pdate and delete )o Action
o <elete %"&%"DE
o <elete &ET NULL
Q. Discuss the correspondences between the E% !odel constructs and the relational !odel
constructs. Show how each E% !odel construct can be !apped to the relational !odel, and
discuss any alternati$e !appings?
*e!ationa! &ata /ode!:
The model uses the concept of a mathematical relation-which looks somewhat
like a table of values-as its basic building block+ and has its theoretical basis in
set theory and first order predicate logic.
The relational model represents the database a collection of relations. 3ach
relation resembles a table of values or+ to some e#tent+ a >flat? file of records.
0hen a relation is thought of as a table of values+ each row in the table
represents a collection of related data values. n the relation model+ each row
in the table represents a fact that typically corresponds to a real-world entity or
relationship. The table name and column names are used to help in
interpreting the meaning of the values in each row. n the formal relational
model terminology+ a row is called a tuple+ a column header is called an
attribute+ and the table is called a relation. The data type describing the types
of values that can appear in each column is represented by domain of
possible values.
3; @odel*
An entity-re!ations'ip mode! (E*/) is an abstract and conceptual
representation of data. 3ntity-relationship modeling is a database modeling
method+ used to produce a type of conceptual schema or semantic data
model of a system+ often a relational database+ and its requirements in a top-
down fashion. <iagrams created by this process are called entity-
re!ations'ip diagrams+ E* diagrams+ or E*&s.
The first stage of information system design uses these models during the
requirements analysis to describe information needs or the type of information
that is to be stored in a database. n the case of the design of an information
system that is based on a database+ the conceptual data model is+ at a later
stage (usually called logical design)+ mapped to a logical data model+ such as
the relational model6 this in turn is mapped to a physical model during physical
design. 0e create a relational schema from an entity-relationship(3;)
schema.
n the case of the design of an information system that is based on a
database+ the conceptual data model is+ at a later stage (usually called logical
design)+ mapped to a logical data model+ such as the relational model6 this in
turn is mapped to a physical model during physical design. Sometimes+ both
of these phases are referred to as 4physical design4. Key elements of this
model are entities+ attributes+ identifiers and relationships.
Corresponden"e #et0een E* and *e!ationa! /ode!s:
3; @odel ;elational @odel
3ntity type >3ntity? relation
'*' or '*) relationship type 1oregin key
@*) relationship type >;elationship? relation and two foreign
keys
n ary relationship type >;elationship? relation and n foreign
keys
Simple attributes Attributes
!omposite attributes Set of simple component attributes
@ultivalued attributes ;elation and foreign key
Aalue set <omain
Key attribute "rimary key or secondary key
/apping o$ regu!ar entity types:
1or each regular entity type 3 in the 3; schema+ create a relation ; that
includes all the simple attributes of 3. nclude only the simple component
attributes of a composite attribute. !hoose one of the key attributes of 3 as
primary key for ;. f the chosen key of 3 is composite+ the set of simple
attributes that form it will together the primary key of ;.
f multiple keys were identified for 3 during the conceptual design+ the
information describing the attributes that form each additional key is kept in
order to specify secondary (unique) keys of relation ;. Knowledge about keys
is also kept for inde#ing purpose and other types of analyses.
0e create the relations 3@"%=B33+ <3"A;T@3)T+ and ";=C3!T in to
correspond to the regular entity types 3@"%=B33+ <3"A;T@3)T+ and
";=C3!T. The foreign key and relationship attributes+ if any+ are not include
yet6 they will be added during subsequent steps. These+ include the attributes
S/"3;3)= and <)= of 3@"%=B33+ @D;)= and @D;STA;T<AT3 of
<3"A;T@3)T+ and <)/@ of ";=C3!T. 0e choose 3)=+ <)/@E3;+ and
")/@E3; as primary keys for the relations 3@"%=B33+ <3"A;T@3)T+
and ";=C3!T+ respectively. Knowledge that <)A@3 of <3"A;T@3)T and
")A@3 of ";=C!3T are secondary keys is kept for possible use later in the
design.
The relation that is created from the mapping of entity types are sometimes
called entity relations because each tuyple represents an entity instance.
Q. Discuss the $arious reasons that lead to the occurrence of null $alues in relations in detail?
3ach value in a tuple is an atomic value6 that is+ it is not divisible into
components within the framework of the basic relational model. 5ence+
composite and multivalued attributes are not allowed. This model is
sometimes called the flat relational model. @uch of the theory behind the
relational model was developed with this assumption in mind+ which is called
the first normal form assumption. 5ence+ multivalued attributes must be
represented by separate relations+ and composite attributes are represented
only by their simple component attributes in the basic relational model.
An important concept is that of nulls+ which are used to represent the values
of attributes that may be unknown or may not apply to a tuple. A special value+
called null+ is used for these cases. n general+ we can have several meanings
for null values+ such as 4value unknown+4 4value e#ists but is not available+4 or
4attribute does not apply to this tuple.4 t is possible to devise different codes
for different meanings of null values. ncorporating different types of null
values into the relational model operations has proven difficult and is outside
the scope of our presentation.
Q. Explain the E&% to relational !apping with a suitable exa!ple?
1or each regular entity type 3 in the 3; schema+
F create a relation ; that includes all the simple attributes
of 3
F include only simple component attributes of composite
attribute
F choose one of the key attributes of 3 as primary key
for ;
G 3#. 3mployee+ <epartment+ "ro,ect relations
F primary key *
G 3mployee(SS))+ <epartment(<)/@E3;)+
"ro,ect(")/@E3;.
/pon completion of this module+ you will be introduced to the following
The use of high-level conceptual data models to support database
design.
The basic concepts associated with the 3ntityF;elationship (3;) model+
a high-level conceptual data model.
A diagrammatic technique for displaying an 3; model.
5ow to identify problems called connection traps+ which may occur
when creating an 3; model.
The limitations of the basic 3; modeling concepts and the requirements
to model more comple# applications using enhanced data modeling
concepts.
The main concepts associated with the 3nhanced 3ntityF;elationship
(33;) model called speciali7ationHgenerali7ation and categori7ation.
Q. Explain the following database operations with one #uery exa!ple for each?
a) Insert:insert statements have the following form:
I'*E%& I'&( table (column1) +column2, ... ,) -A./E* (value1)
+value2, ...,)
!he number of columns and values must be the same. "f a column is not specified, the
default value for the column is used. !he values specified (or implied) by the IN&ERT
statement must satisfy all the applicable constraints (such as primary keys, %HE%$
constraints, and NOT NULL constraints). "f a synta# error occurs or if any constraints are
violated, the new row is not added to the table and an error returned instead.
E#ample:
IN&ERT INTO phone'(oo) *name+ n,m(er- ."LUE& */John Doe/+
/000-1212/-3
#) &e!ete:- !he DELETE statement follows the synta#:
DELETE FRO! table_name $WHERE condition%
Any rows that match the 4HERE condition will be removed from the table. "f the 4HERE
clause is omitted, all rows in the table are removed. !he DELETE statement does not
return any rows& that is, it will not generate a result set.
E#ecuting a DELETE statement can cause triggers to run that can cause deletes in other
tables. 'or e#ample, if two tables are linked by a foreign key and rows in the
referenced table are deleted, then it is common that rows in the referencing table
would also have to be deleted to maintain referential integrity.
(elete rows from mytable using a sub)uery in the where condition:
DELETE FRO! myta(le 4HERE id IN *&ELE%T id FRO!
myta(le2-3
") +pdate:- An *+, -.(A!E statement changes the data of one or more
records in a table. Either all the rows can be updated, or a subset may be chosen using
a condition.
!he UD"TE statement has the following form:
UD"TE table/name &ET column/name 0 value $, column/name 0 value ...%
$4HERE condition%
'or the UD"TE to be successful, the user must have data manipulation privileges
(UD"TE privilege) on the table or column, the updated value must not conflict with all
the applicable constraints (such as primary keys, uni)ue inde#es, %HE%$ constraints ,
and NOT NULL constraints).
*et the value of column C1 in table T to 1, only in those rows where the value of
column C2 is 2a2.
UD"TE T &ET %1 5 1 4HERE %2 5 /a/3
Q. Explain the functions and ad$antages of a D'(S o$er a traditional file syste!?
A <E@S is a set of software programs that controls the organi7ation+ storage+
management+ and retrieval of data in a database. <E@Ss are categori7ed
according to their data structures or types. The <E@S accepts requests for
data from an application program and instructs the operating system to
transfer the appropriate data. The queries and responses must be submitted
and received according to a format that conforms to one or more applicable
protocols. 0hen a <E@S is used+ information systems can be changed more
easily as the organi7ation2s information requirements change. )ew categories
of data can be added to the database without disruption to the e#isting
system.
d1antages o$ a &)/S:-
@anagement of distributed data with different levels of transparency.
ncrease reliability and availability.
3asier e#pansion.
;eflects organi7ational structure I database fragments are located in
the departments they relate to.
%ocal autonomy I a department can control the data about them (as
they are the ones familiar with it.)
"rotection of valuable data I if there were ever a catastrophic event
such as a fire+ all of the data would not be in one place+ but distributed
in multiple locations.
mproved performance I data is located near the site of greatest
demand+ and the database systems themselves are paralleli7ed+
allowing load on the databases to be balanced among servers. (A high
load on one module of the database won2t affect other modules of the
database in a distributed database.)
3conomics I it costs less to create a network of smaller computers
with the power of a single large computer.
@odularity I systems can be modified+ added and removed from the
distributed database without affecting other modules (systems).
;eliable transactions - <ue to replication of database.
5ardware+ =perating System+ )etwork+ 1ragmentation+ <E@S+
;eplication and %ocation ndependence.
!ontinuous operation.
Q. Explain the purpose of Data (odeling. )hat are the basic constructs of E&% Diagra!s?
&ata mode!ing in is the process of creating a data model by applying formal
data model descriptions using data modeling techniques.
<ata modeling is the act of e#ploring data-oriented structures. %ike other
modeling artifacts data models can be used for a variety of purposes+ from
high-level conceptual models to physical data models.
<ata modeling is the formali7ation and documentation of e#isting processes
and events that occur during application software design and development.
<ata modeling techniques and tools capture and translate comple# system
designs into easily understood representations of the data flows and
processes+ creating a blueprint for construction andHor re-engineering.
)asi" Constru"ts o$ E-* /ode!ing:
The 3; model views the real world as a construct of entities and association
between entities. The basic constructs of 3; modeling are entities+ attributes+
and relationships.
3ntity*
An entity may be defined as a thing which is recogni7ed as being capable of
an independent e#istence and which can be uniquely identified. An entity is an
abstraction from the comple#ities of some domain. 0hen we speak of an
entity we normally speak of some aspect of the real world which can be
distinguished from other aspects of the real world.
An entity may be a physical ob,ect such as a house or a car+ an event such as
a house sale or a car service+ or a concept such as a customer transaction or
order. Although the term entity is the one most commonly used+ following
!hen we should really distinguish between an entity and an entity-type. An
entity-type is a category. An entity+ strictly speaking+ is an instance of a given
entity-type. There are usually many instances of an entity-type. Eecause the
term entity-type is somewhat cumbersome+ most people tend to use the term
entity as a synonym for this term.
3ntities can be thought of as nouns. 3#amples* a computer+ an employee+ a
song+ a mathematical theorem.
*e!ations'ip:
A relationship captures how two or more entities are related to one another.
;elationships can be thought of as verbs+ linking two or more nouns.
3#amples* an owns relationship between a company and a computer+ a
supervises relationship between an employee and a department+ a performs
relationship between an artist and a song+ a proved relationship between a
mathematician and a theorem.
ttri#utes:
3ntities and relationships can both have attributes. 3#amples* an employee
entity might have a Social Security Number (SS)) attribute6 the proved
relationship may have a date attribute.
Q. Explain the three&le$el architecture of a D'(S with a labeled diagra!?
(ata are actually stored as bits, or numbers and strings, but it is difficult to work with
data at this level.
"t is necessary to view data at different levels of abstraction.
*chema:
0escription of data at some level. Each level has its own schema.
3e will be concerned with three forms of schemas:
physical)
conceptual) and
e1ternal.
Q. )hat are the ad$antages of *ndexes in a Database? Explain with the exa!ple?
Inde-es in a &ata#ase: A data#ase inde- is a data structure that improves
the speed of data retrieval operations on a database table at the cost of
slower writes and increased storage space. nde#es can be created using one
or more columns of a database table+ providing the basis for both rapid
random lookups and efficient access of ordered records.
Advantages of nde#es*
The classical e#ample for the need of an inde# is if there is a table similar to
this*
!;3AT3 TAE%3 test' (
id integer+
content varchar
)6
and the application requires a lot of queries of the form
S3%3!T content 1;=@ test' 053;3 id J constant6
=rdinarily+ the system would have to scan the entire test' table row by row to
find all matching entries. f there are a lot of rows in test' and only a few rows
(possibly 7ero or one) returned by the query+ then this is clearly an inefficient
method. f the system were instructed to maintain an inde# on the id column+
then it could use a more efficient method for locating matching rows. 1or
instance+ it might only have to walk a few levels deep into a search tree.
A similar approach is used in most books of non-fiction* Terms and concepts
that are frequently looked up by readers are collected in an alphabetic inde#
at the end of the book. The interested reader can scan the inde# relatively
quickly and flip to the appropriate page+ and would not have to read the entire
book to find the interesting location. As it is the task of the author to anticipate
the items that the readers are most likely to look up+ it is the task of the
database programmer to foresee which inde#es would be of advantage.
The following command would be used to create the inde# on the id column+
as discussed*
!;3AT3 )<3K test'LidLinde# =) test' (id)6
The name test'LidLinde# can be chosen freely+ but you should pick
something that enables you to remember later what the inde# was for.
To remove an inde#+ use the <;=" )<3K command. nde#es can be added
to and removed from tables at any time.
8) Aariable !ost
2) Fi-ed Cost
t is that portion of the total cost which remains constant irrespective of
output up to the capacity limit. t is called as a period cost as it is concerned
with period. t depends upon the passage of time. t is also referred to as non-
variable cost or stand by cost or capacity cost. t tends to be unaffected by
variations in output. These costs provide conditions for production rather than
costs of production. They are created by contractual obligations and
managerial decisions. ;ent of premises+ Ta#es and insurance+ staff salaries
are e#amples for fi#ed cost.
3) Varia#!e Cost:
This cost varied according to the output in other words+ it is a cost which
changes according to the changes in output. t tends to vary in direct
proportion to output. f the output is decreased+ variable cost will also
decrease. t is concerned with output of product. Therefore+ it is called as a
product cost. f the output is doubled+ variable cost will also be doubled. 3.g.
direct material+ direct labour+ direct e#penses and variable overheads are
variable costs.
4) Semi-Varia#!e Cost:
This is also referred to as semi-fi#ed or partly variable cost. t remains
constant up to a certain level and registers change afterwards. These costs
vary in some degree with volume but not in direct or same proportion. Such
costs are fi#ed only in relation to specified constant conditions. 1or e#ample+
repairs and maintenance of machinery+ telephone charges+ maintenance of
building+ supervision+ professional ta# etc. are semi-variable costs.
Q. )hat is a relationship type? Explain the differences a!ong a relationship instance, a
relationship type, and a relationship set?
There are three type of relationships
') =ne to one
8) =ne to many
9) @any to many
Say we have table' and table8
1or one to one relationship+ a record(row) in table' will have at most one
matching record or row in table8
.e. it mustnMt have two matching records or no matching records in table8.
1or one to many+ a record in table' can have more than one record in table8
but not vice versa
%etMs take an e#ample+
Say we have a database which saves information about Duys and whom they
are dating.
0e have two tables in our database Duys and Dirls
Duy id Duy name
' Andrew
8 Eob
9 !raig
Dirl id Dirl name
' Dirl'
8 Dirl8
9 Dirl9
5ere in above e#ample Duy < and Dirl < are primary keys of their respective
table.
Say Andrew is dating Dirl'+ Eob F Dirl8 and !raig is dating Dirl9.
So we are having a one to one relationship over there.
So in this case we need to modify the Dirls table to have a Duy id foreign key
in it.
Dirl id Dirl name 5uy id
' Dirl' 2
8 Dirl8 3
9 Dirl9 4
)ow let say one guy has started dating more than one girl.
i.e. Andrew has started dating Dirl' and say a new DirlN
That takes us to one to many relationships from Duys to Dirls table.
)ow to accommodate this change we can modify our Dirls table like this
Dirl d Dirl )ame Duy d
' Dirl' '
8 Dirl8 8
9 Dirl9 9
N DirlN 2
)ow say after few days+ comes a time where girls have also started dating
more than one boy i.e. many to many relationships
So the thing to do over here is to add another table which is called Cunction
Table+ Associate Table or linking Table which will contain primary key
columns of both girls and guys table.
%et see it with an e#ample
Duy id Duy name
' Andrew
8 Eob
9 !raig
Dirl id Dirl name
' Dirl'
8 Dirl8
9 Dirl9
Andrew is now dating Dirl' and Dirl8 and
)ow Dirl9 has started dating Eob and !raig
so our 6un"tion ta#!e will look like this
Duy < Dirl <
' '
' 8
8 8
8 9
9 9
t will contain primary key of both the Dirls and Eoys table.
A relationship type ; among n entity types 3'+ 38+ O+ 3n is a set of
associations among entities from these types. Actually+ ; is a set of
relationship instances ri where each ri is an n-tuple of entities (e'+ e8+ O+ en)+
and each entity e, in ri is a member of entity type 3,+ 'P,Pn. 5ence+ a
relationship type is a mathematical relation on 3'+ 38+ O+ 3n+ or alternatively
it can be defined as a subset of the !artesian product 3'# 38# O #3n . 5ere+
entity types 3'+ 38+ O+ 3n defines a set of relationship+ called relationship
sets.
;elationship instance* 3ach relationship instance ri in ; is an association of
entities+ where the association includes e#actly one entity from each
participating entity type. 3ach such relationship instance ri represent the fact
that the entities participating in ri are related in some way in the corresponding
miniworld situation. 1or e#ample+ in relationship type 0=;KSL1=;
associates one 3@"%=B33 and <3"A;T@3)T+ which associates each
employee with the department for which the employee works. 3ach
relationship instance in the relationship set 0=;KSL1=; associates one
3@"%=B33 and one <3"A;T@3)T.
0e create the relations 3@"%=B33+ <3"A;T@3)T+ and ";=C3!T in to
correspond to the regular entity types 3@"%=B33+ <3"A;T@3)T+ and
";=C3!T. The foreign key and relationship attributes+ if any+ are not include
yet6 they will be added during subsequent steps. These+ include the attributes
S/"3;3)= and <)= of 3@"%=B33+ @D;)= and @D;STA;T<AT3 of
<3"A;T@3)T+ and <)/@ of ";=C3!T. 0e choose 3)=+ <)/@E3;+ and
")/@E3; as primary keys for the relations 3@"%=B33+ <3"A;T@3)T+
and ";=C3!T+ respectively. Knowledge that <)A@3 of <3"A;T@3)T and
")A@3 of ";=C!3T are secondary keys is kept for possible use later in the
design.
The relation that is created from the mapping of entity types are sometimes
called entity relations because each tuyple represents an entity instance.
Q. )rite about+ A, *ntegrity %ules
3.2 Integrity *u!es:
These are the rules which a relational database follows in order to stay
accurate and accessible. These rules govern which operations can be
performed on the data and on the structure of the database. There are three
integrity rules defined for a relational databse+which are*-
&istin"t *o0s in a Ta#!e - this rule says that all the rows of a table
should be distinct to avoid in ambiguity while accessing the rows of that
table. @ost of the modern database management systems can be
configured to avoid duplicate rows.
Entity Integrity ( Primary Key or part o$ it "annot #e nu!!) - this rule
says that 2null2 is special value in a relational database and it doesn2t
mean blank or 7ero. t means the unavailability of data and hence a 2null2
primary key would not be a complete identifier. This integrity rule is also
termed as entity integirty.
*e$erentia! Integrity - this rule says that if a foreign key is defined on a
table then a value matching that foreign key value must e#ist as th e
primary key of a row in some other table.
!he following are the integrity rules to be satisfied by any relation.
4 5o 6omponent of the .rimary 7ey can be null.
4 !he (atabase must not contain any unmatched 'oreign 7ey values. !his is
called the referential integrity rule.
-nlike the case of .rimary 7eys, there is no integrity rule saying that no
component of the foreign key can be null. !his can be logically e#plained with the
help of the following e#ample:
6onsider the relations Employee and Account as given below.
Employee
Emp# EmpName Empity EmpAcc#
8191 *hekhar :ombay 1;9991
819; Ra< .une 1;999;
819= *harma 5agpur 5ull
819> ?ani :hopal 1;999=
Account
A# OpenDate BalAmt
1;9991 =9Aug1@@A B999
1;999; ;@Cct1@@A 1;99
1;999= 91Dan1@@@ =999
1;999> 9>Ear1@@@ B99
EmpAccF in Employee relation is a foreign key creating reference from Employee
to Account. Gere, a 5ull value in EmpAccF attribute is logically possible if an
Employee does not have a bank account. "f the business rules allow an employee to
e#ist in the system without opening an account, a 5ull value can be allowed for
EmpAccF in Employee relation.
"n the case e#ample given, 6ustF in Crd/Aug cannot accept 5ull if the business
rule insists that the 6ustomer 5o. needs to be stored for every order placed.
Data structure using
Q. De!onstrate with your own progra!!ing exa!ple the usage of structures within an array?
Dust as arrays of basic types such as integers and floats are allowed in 6, so are arrays
of structures. An array of structures is declared in the usual way:
! struct personal"data my"struct"array#!$$%&
!he members of the structures in the array are then accessed by statements such as the
following:
!he value of a member of a structure in an array can be assigned to another variable,
or the value of a variable can be assigned to a member. 'or e#ample, the following
code assigns the number 1@H> to the year/of/birth member of the fourth element of
my/struct/array:
! my"struct"array#'%(year"o)"birt* + !,-.&
Example:-
6in7l,de 8stdio.h9
str,7t matri: ;
int ro<s3
int 7ols3
int ==>al3
? a 5 ; .ro<s5@+ .7ols51+
.>al 5 *int=A@B-; *intA1B-;1?+
*intA1B-;2?+
*intA1B-;@? ? ?+
( 5 ; .ro<s5@+ .7ols5C+
.>al 5 *int=A@B-; *intACB-;1+ 2+ @+ C?+
*intACB-;0+ D+ E+ F?+
*intACB-;G+1H+11+12? ? ?3
>oid print'matri:* 7har =name+ str,7t matri: =m -;
Ior* int ro<5H3ro<8m-9ro<s3ro<JJ -
Ior* int 7ol5H37ol8m-97ols37olJJ -
printI* KLsALiBALiBM LiNnK+ name+ ro<+ 7ol+ m-9>alAro<B
A7olB -3
p,ts*KK-3
?
int main*-;
print'matri:* KaK+ Oa -3
print'matri:* K(K+ O( -3
?
Q. Describe the usage of pointers in functions with a suitable exa!ple?
;egarding their synta#+ there are two different types of function pointers* =n
the one hand there are pointers to ordinary ! functions or to static !QQ
member functions. =n the other hand there are pointers to non-static !QQ
member functions. The basic difference is that all pointers to non-static
member functions need a hidden argument* The this-pointer to an instance of
the class. Always keep in mind* These two types of function pointers are
incompatible with each other.
Since a function pointer is nothing else than a variable+ it must be defined as
usual. n the following e#ample we define three function pointers named
pt2Function+ pt2Member and pt2ConstMember. They point to functions+ which
take one float and two char and return an int. n the !QQ e#ample it is
assumed+ that the functions+ our pointers point to+ are (non-static) member
functions of TMyClass.
int *=pt2F,n7tion-*Iloat+ 7har+ 7har- 5 NULL3
iI*pt2F,n7tion 9H-;
if(pt81unction JJ R<ot)
printf(4"ointer points to <otSn4)6 T
else
printf(4"ointer not initiali7edUUSn4)6
Q. Explain *nsert-Delete a node at the rear, front end fro! circular singly lin.ed list?
A sing!y !in.ed "ir"u!ar !ist is a linked list where the last node in the list
points to the first node in the list. A circular list does not contain )/%%
pointers.
0ith a circular list+ a pointer to the last node gives easy access also to the first
node+ by following one link. Thus+ in applications that require access to both
ends of the list (e.g.+ in the implementation of a queue)+ a circular structure
allows one to handle the structure by a single pointer+ instead of two.
A circular list can be split into two circular lists+ in constant time+ by giving the
addresses of the last node of each piece. The operation consists in swapping
the contents of the link fields of those two nodes. Applying the same operation
to any two nodes in two distinct lists ,oins the two list into one. This property
greatly simplifies some algorithms and data structures+ such as the quad-edge
and face-edge.
The simplest representation for an empty "ir"u!ar list (when such a thing
makes sense) is a null pointer+ indicating that the list has no nodes. 0ith this
choice+ many algorithms have to test for this special case+ and handle it
separately. Ey contrast+ the use of null to denote an empty !inear list is more
natural and often creates fewer special cases.
Step '* To insert an item :V at the front of the list+ obtain a free node temp
from the availability list and store the item in info field. This can be
accomplished using the following statements
TempJgetnode()6
Temp-WinfoJitem6
Step 8* !opy the address of the first node(i.e. last-Wlink) into link field of newly
obtained node temp and the statement to accomplish this task is
Temp-W linkJlast-Wlink
Step 9* 3stablish a link between the newly created node temp and the last
node. This is achieved by copying the address of the node temp into link field
of last node. The corresponding code for this is
%ast-WlinkJtemp6
Step N* The new node is made as the last node using the statement*
;eturn temp6
These steps have designed by assuming the list already e#ists.
1unction to insert an item at the rear end of the list.
)=<3 insertLrear(int item+ )=<3 last)
X
)=<3 temp6
TempJgetnode()6
Temp-WinfoJitem6
f(lastJJ)/%%)
%astJtemp6
3lse
3mp-WlinkJlast-Wlink6
%ast-WlinkJtemp6
;etrun temp6
T
Insert a node at t'e $ront end:
!onsider the list contains N nodes and a pointer variable last contains address
of the last node.
Step '* To insert an item :V at the front of the list+ obtain a free node temp
from the availability list and store the item in info field. This can be
accomplished using the following statements
TempJgetnode()6
Temp-WinfoJitem6
Step 8* !opy the address of the first node(i.e. last-Wlink) into link field of newly
obtained node temp and the statement to accomplish this task is
Temp-WlinkJlast-Wlink.
Step 9* 3stablish a link between the newly created node temp and the last
node. This is achieved by copying the address of the node temp into link field
of last node. The corresponding code for this is
%ast-WlinkJtemp6
)ow+ an item is successfully inserted at the front of the list. All these steps
have been designed by assuming the list is already e#isting. f the list is
empty+ make temp itself as the last node and establish a link between the first
node and the last node. ;epeatedly insert the items using the above
procedure to create a list.
1unction to insert an item at the front end of the list.
)=<3 insertLfront(int item+ )=<3 last)
X
)=<3 temp6
TempJgetnode()6
Temp-WinfoJitem6
f(lastJJ)/%%)
%astJtemp6
3lse
temp-WlinkJlast-Wlink6
%ast-WlinkJtemp6
;eturn last6
T
Q. *llustrate the / progra! to represents the Stac. *!ple!entation on 010 and 02S3 operation?
YincludeZstudio.hW
YincludeZconio.hW
Ydefine @a# :
nt Staff &@a#(+ topJ-'6
Aoid display()
X
f ((topJJ-' [[ (topJJV))
X
"rintf(>Sn stack is fullSn?)6
T
3lse
X
"rintf(>Sn stack elements areSn?)6
1or(int iJtop-'6iWJV6i--)
T
T
void push()
X
int ele6
char ch6
it(top-J-')
topJV6
do
X
f (topWJ:)
X
"rintf(>Sn stack is full?)6
Ereak6
T
3lse
X
!lrscr()6
"rintf(>Sn enter the element to be inseartedSn?)6
Scanf(>\d?+ Rele)6
Staff(topQQ)Jele
display()6
T
"rintf(>Sn <o u want to add more elements*]Sn?)6
Scanf(>Sn\c?+ Rch)6
T
0hile ((chJJMyM [[(chJJMBM))6
T
void pop()
X
f ((topJJ-')[[(topJJV)
X
"rintf(>Snstack is under flowSn?)6
T
3lse
X
"rintf(>\d is deleted fro stackSn?+Staff(--top(?)6
display()6
T
T
Aoid main()
X
clrscr()6
char c6
int choice6
do
X
cirscr()6
printf(>Sn enter the choiceSn?)6
printf(>'-WpushSn?)6
printf(>8-popSn?)6
scant(>\d?+ Rchoice)6
if(choiceJJ')
push()6
elshif(choiceJJ8)
pop()6
else
printf(>Sin valid choice?)6
printf(>Sn do u want to continue*]?)6
scanf(>Sn\c?+ Rc)6
T
0hileX(cJJMyM)[[(cJJMBM))6
T
Q. )ith the help of a suitable nu!erical exa!ple, describe the following concepts of a 'inary
Search Tree?
) na!ysis o$ )ST :- carry out an Analysis of this method to determine its
time comple#ity. Since there are no >for? loops+ we can not use summations to
e#press the total number of
operations. %et us e#amine the operations for a specific case+ where the
number of
elements in the array n is ^N.
0hen nJ ^N EinarySearch is called to reduce si7e to nJ98
0hen nJ 98 EinarySearch is called to reduce si7e to nJ'^
0hen nJ '^ EinarySearch is called to reduce si7e to nJ_
0hen nJ _ EinarySearch is called to reduce si7e to nJN
0hen nJ N EinarySearch is called to reduce si7e to nJ8
0hen nJ 8 EinarySearch is called to reduce si7e to nJ'
int )inarySear"' (int 7 89 int n9 int K)
:
int ;<=9 /id9 *< n-2>
0'i!e (;?<*)
:
/id < (; @*)A3>
i$ ( K< <7/id8 )
return /id>
e!se i$ ( K B 7/id8 )
; < /id @ 2>
e!se
* < /id 2 >
C
return 2 >
C
)) Insertion o$ (odes into a )ST :- To insert a node into a EST
'. find a leaf st the appropriate place and
8. connect the node to the parent of the leaf.
T*EE-I(SE*T (T9 D)
y ` )%
# ` root &T(
while # a )% do
y ` #
if key &7( Z key&#(
then # ` left&#(
else # ` right&#(
p&7( ` y
if y J )%
then root &T( ` 7
else if key &7( Z key &y(
then left &y( ` 7
else right &y( ` 7
%ike other primitive operations on search trees+ this algorithm begins at the
root of the tree and traces a path downward. !learly+ it runs in =(h) time on a
tree of height h.
Q. )rite a progra! in / showing the i!ple!entation of stac. operations using structures
Sta". operations:-
"ush and pop are the operations that are provided for insertion of an element
into the stack and the removal of an element from the stack.
E-amp!e:-
6in7l,de 8stdio.h9
6in7l,de 8stdli(.h9
6in7l,de Ksta7).hK
6deIine siPe @
>oid main*-
X
int top+element3
int stack&si7e(6
init*Otop-3
while(Ufull(Rtop+si7e))X
element 5 rand*-3
printf(Kp,sh element Ld into sta7)NnK+element)6
p,sh*sta7)+Otop+element-3
Qet7har*-3
?
printf(Ksta7) is I,llNnK)6
<hile*Rempty*Otop--;
element J pop(stack+Rtop)6
printI*4pop element \d from stackSn4+element-3
Qet7har*-3
T
printI*4stack is emptySn4-3
Qet7har*-3
T
Q. )rite a progra! to perfor! a binary search on an unsorted list of n integers?
Program E-amp!e:-
YincludeZstdio.hW
YincludeZconio.hW
YincludeZmath.hW
int main()
X
int a&8V(J XVT6
int n+ i+ ,+ temp6
int .beg+ .end+ .mid+ target6
printf(4 enter the total integers you want to enter (make it less then 8V)*Sn4)6
scanf(4\d4+ Rn)6
if (n WJ 8V) return V6
printf(4 enter the integer array elements*Sn4 )6
for(i J V6 i Z n6 iQQ)
X
scanf(4\d4+ Ra&i()6
T
for(i J V6 i Z n-'6 iQQ)
X
for(, J V6 , Z n-i-'6 ,QQ)
X
if (a&,Q'( Z a&,()
X
temp J a&,(6
a&,( J a&,Q'(6
a&,Q'( J temp6
T
T
T
printf(4 the sorted numbers are*4)6
for(i J V6 i Z n6 iQQ)
X
printf(4\d 4+ a&i()6
T
beg J Ra&V(6
end J Ra&n(6
mid J beg QJ nH86
printf(4Sn enter the number to be searched*4)6
scanf(4\d4+Rtarget)6
while((beg ZJ end) RR (.mid UJ target))
X
if (target Z .mid)
X
end J mid F '6
n J nH86
mid J beg QJ nH86
T
else
X
beg J mid Q '6
n J nH86
mid J beg QJ nH86
T
T
if (.mid JJ target)
X
printf(4Sn \d foundU4+ target)6
T
else
X
printf(4Sn \d not foundU4+ target)6
T
getchar()6
getchar()6
return V6
T
Q. )rite note on+ a,Ele!entary Data Structures b,1rdered list c,4in.ed list d,Queue e, Slac.
f,'inary tree g,3ash tables
a) E!ementary &ata Stru"tures:
=rgani7ing the data for processing is an essential step in the development of
a computer program. 1or many applications+ the choice of the proper data
structure is the only ma,or decision involved in the implementation* once the
choice has been made+ the necessary algorithms are simple. 1or the same
data+ some data structures require more or less space than others6 for the
same operations on the data+ some data structures lead to more or less
efficient algorithms than others. The choices of algorithm and of data structure
are closely intertwined+ and we continually seek ways to save time or space
by making the choice properly.
3lementary data structures such as sta".s9 ,ueues9 !ists9 and 'eaps will be
the >of-the-shelf? components we build our algorithm from. There are two
aspects to any data structure
-The abstract operations which it supports.
-The implementation of these operations.
#) Erdered !ist:
A list in which the order matters to the application. Therefore+ for e#ample+ the
implementer cannot scramble the order to improve efficiency. An ordered list
is a list in which the order of the items is significant. 5owever+ the items in an
ordered list are not necessarily sorted. !onsequently+ it is possible to change
the order o items and still have a valid ordered list.
!onsider a list of the titles of the chapters in this book. The order of the items
in the list corresponds to the order in which they appear in the book. 5owever+
since the chapter titles are not sorted alphabetically+ we cannot consider the
list to be sorted. Since it is possible to change the order of the chapters in
book+ we must be able to do the same with the items of the list. As a result+
we may insert an item into an ordered list at any position.
A searchable container is a container that supports the following additional
operations*
insert
-used to put ob,ects into a the container6
0it'dra0
-used to remove ob,ects from the container6
$ind
-used to locate ob,ects in the container6
is/em#er
-used to test whether a given ob,ect instance is in the container.
") ;in.ed !ist:
A linked list is an ordered collection of items from which items may be
deleted and inserted in any places. A data structure in which each
element contains a pointer to the ne#t element+ thus forming a linear list.
Apart from singles linked we still have t the following
types of linked lists* doubly linked list+ ordered linked
list+ circular list.
%inked lists are commonly used when the length of the list is not known in
advance andHor when it is frequently necessary to insert andHor delete in the
middle of the list.
&ou#!y-!in.ed 1s. sing!y-!in.ed !ists-
n a doubly-linked list+ each node points to the ne#t node and also to the
previous node. n a singly-linked list+ each node points to the ne#t node but
not back to the previous node.
Cir"u!ar !ist -
A linked list in which the last node points to the first node. f the list is doubly-
linked+ the first node must also point back to the last node.
d) Fueue:
An ordered list in which insertion always occurs at one end and deletion
always occurs at the other end.
The following operations can be applied to a queue*
InitQueue(Queue* creates an empty queue6
Join(!tem* inserts an item to the rear of the queue6
Leave(Queue* removes an item from the front of the queue6
isEmpty(Queue* returns true is the queue is empty.
e) Sta".:
A stack is a list in which all insertions and deletions are made at one end+
called the top. The last element to be inserted into the stack will be the first to
be removed. Thus stacks are sometimes referred to as ;ast In First Eut
(%1=) lists.
The following operations can be applied to a stack*
InitStack(Stac"* creates an empty stack6
Push(!tem* pushes an item on the stack6
Pop(Stac"* removes the first item from the stack6
Top(Stac"* returns the first item from the stack wHo removing it6
isEmpty(Stac"* returns true is the stack is empty6
$) )inary tree:
3ach element in a binary tree is stored in a 4node4 class (or struct). 3ach node
contains pointers to a left child node and a right child node. n some
implementations+ it may also contain a pointer to the parent node. A tree may
also have an ob,ect of a second 4tree4 class (or struct) which as a header for
the tree. The 4tree4 ob,ect contains a pointer to the root of the tree (the node
with no parent) and whatever other information the programmer wants to
squirrel away in it (e.g. number of nodes currently in the tree).
n a binary tree+ elements are kept sorted in left to right order across the tree.
That is+ if ) is a node+ then the value stored in ) must be larger than the value
stored in left-child()) and less than the value stored in right-child()). Aariant
trees may have the opposite order (smaller values to the right rather than to
the left) or may allow two different nodes to contain equal values.
g) Gas' ta#!es:
A 'as' ta#!e or 'as' map is a data structure that uses a hash function to
map identifying values+ known as keys (e.g.+ a person2s name)+ to their
associated values (e.g.+ their telephone number). Thus+ a hash table
implements an associate array. The hash function is used to transform the key
into the inde# (the hash) of an array element (the slot or buc"et) where the
corresponding value is to be sought.
deally+ the hash function should map each possible key to a unique slot
inde#+ but this ideal is rarely achievable in practice (unless the hash keys are
fi#ed6 i.e. new entries are never added to the table after it is created). nstead+
most hash table designs assume that hash collisionsIdifferent keys that map
to the same hash valueIwill occur and must be accommodated in some way.
n a well-dimensioned hash table+ the average cost (number of instructions)
for each lookup is independent of the number of elements stored in the table.
@any hash table designs also allow arbitrary insertions and deletions of key-
value pairs+ at constant average (indeed) cost per operation.
n many situations+ hash tables turn out to be more efficient than search trees
or any other table lookup structure. 1or this reason+ they are widely used in
many kinds of computer software+ particularly for associate arrays+ database
inde#ing caches and sets.
2A-A 3%(G%A!!I'G
Q. Discuss the following with suitable exa!ple progra!s for each+ A, Data Types in a$a ',
5ariables in a$a
/a0a Data 1ypes:
(ata type defines a set of permitted values on which the legal operations can be
performed. "n <ava, all the variables needs to be declared first i.e. before using a
particular variable, it must be declared in the program for the memory allocation
process. ,ike
int pedal 0 1&
2rimiti0e Data 1ypes: !he primitive data types are predefined data types, which
always hold the value of the same data type, and the values of a primitive data type
donIt share the state with other primitive values. !hese data types are named by a
reserved keyword in Dava programming language.
!here are eight primitive data types supported by Dava programming data types
supported by Dava programming:
byte
byte b 0 B&
short
short s 0 ;&
long
long ln 0 H>J&
float
float f 0 19B.JB&
float f 0 B999.1;&
double
double d 0 JJHH.J9&
char
char caps 0 IcI&
boolean
boolean result J true6
Data
1ype
De)ault
3alue
()or
)ields)
Si4e (in
bits)
Minimum 5ange Ma6imum 5ange
byte 9
Cccupy
A bits in
memory
1;A K1;H
short 9
Cccupy
1J bits
in
memory
=;HJA K=;HJH
int 9
Cccupy
=; bits
in
memory
;1>H>A=J>A K;1>H>A=J>H
long 9,
Cccupy
J> bits
in
memory
@;;==H;9=JAB>HHBA9A
K@;;==H;9=JAB>HHBA9H
float 9.9f
Cccupy
=;bit
"EEE
HB>
floating
point
1.>91;@A>J>=;>A1H9H
e>B
=.>9;A;=>JJ=AB;AAJ9eK=A
double 9.9d
Cccupy
J>bit
"EEE
HB>
floating
point
>.@>9JBJ>BA>1;>JB>>
e=;>d
1.H@HJ@=1=>AJ;=1BH9eK=9
Ad
char
ILu9999
I
Cccupy
1Jbit,
unsigne
d
-nicode
characte
r
9 to JB,B=B
boolea
n
'alse
Cccupy
1 bit in
memory
5A 5A
"n Dava a reference data type is a variable that can contain the reference or an
address of dynamically created ob<ect. !his type of data type is not predefined like
primitive data type. !he reference data types are arrays, classes and interfaces that
are made and handle according to a programmer in a <ava program which can hold
the three kinds of values as:
array type
MM .oints to an array instance
class type
MM .oints to an ob<ect or a class instance
interface type
MM .oints to an ob<ect and a method, which is implemented to the corresponding
interface
class type:
As you know that Dava is an ob<ectoriented programming language where an
ob<ect is a variable, associated with methods that is described by a class. !he name
of a class is treated as a type in a <ava program, so that you can declare a variable
of an ob<ecttype, and a method which can be called using that ob<ect type
variable.
3henever a variable is created, a reference to an ob<ect is also created using the
name of a class for its type i.e. that variable can contain either null or a reference to
an ob<ect of that class. "t is not allowed to contain any other kinds of values. *uch
type is called reference types in Dava. !he ob<ect becomes an instance when the
memory is allocated to that ob<ect using new keyword. "n addition, array types are
reference types because these are treated as ob<ects in Dava. 'or e#ample:
class 'ruit N
f6olor()N....O
f*iPe()N....O
O&'ruit mango&
'ruit banana&
...
"n the given e#ample the 'ruit is a class that has the reference variables as mango
Q banana through which we can call
the behaviors associated with that class as mango.f6olor()& within the main
method of the super class.
Array !ype:
An array is a special kind of ob<ect that contains values called elements. !he <ava
array enables the user to store the values of the same type in contiguous memory
allocations. !he elements in an array are identified by an integer inde# which
initially starts from 9 and ends with one less than number of elements available in
the array. All elements of an array must contain the same type of value i.e. if an
array is a type of integer then all the elements must be of integer type. "t is a
reference data type because the class named as Array implicitly e#tends
<ava.lang.Cb<ect. "n the first statement, an array variable 2a2 is declared of integer
data type that holds the memory spaces according to the siPe of int. !he inde# of
the array starts from a$9% and ends with a$@%. !hus, the integer value can be
assigned for each or a particular inde# position of the array.
"n the second statement, the array 2b2 is declared of string data type that has the
enough memory spaces to directly hold the three string values. !hus each value is
assigned for each inde# position of the array.
Dava provides an another kind of reference data type or a mechanism to support
multiple inheritance feature called an interface. !he name of an interface can be
used to specify the type of a reference. A value is not allowed to be assign to a
variable declared using an interface type until the ob<ect implements the specified
interface.
3hen a class declaration implements an interface, that class inherits all of the
variables and methods declared in that interface. *o the implementations for all of
the methods declared in the interface must be provided by that class. 'or e#ample,
Dava provides an interface called Action,istener whose method named
action.erformed() is used to handle the different kind of event . Dava also provides
a class called !hread that implements Runnable interface.
!hus the following assignment can be allowed:
;unnable r6
r J new Thread()6
!he Dava programming language defines the following kinds of variables:
"nstance ?ariables (5on*tatic 'ields) !echnically speaking, ob<ects store their
individual states in 2nonstatic fields2, that is, fields declared without the static
keyword. 5onstatic fields are also known as instance variables because their
values are uni)ue to each instance of a class (to each ob<ect, in other words)& the
current*peed of one bicycle is independent from the current*peed of another.
6lass ?ariables (*tatic 'ields) A class variable is any field declared with the
static modifier& this tells the compiler that there is e#actly one copy of this variable
in e#istence, regardless of how many times the class has been instantiated. A field
defining the number of gears for a particular kind of bicycle could be marked as
static since conceptually the same number of gears will apply to all instances. !he
code static int numRears 0 J& would create such a static field. Additionally, the
keyword final could be added to indicate that the number of gears will never
change.
,ocal ?ariables *imilar to how an ob<ect stores its state in fields, a method will
often store its temporary state in local variables. !he synta# for declaring a local
variable is similar to declaring a field (for e#ample, int count 0 9&). !here is no
special keyword designating a variable as local& that determination comes entirely
from the location in which the variable is declared S which is between the
opening and closing braces of a method. As such, local variables are only visible to
the methods in which they are declared& they are not accessible from the rest of the
class.
.arameters TouIve already seen e#amples of parameters, both in the :icycle
class and in the main method of the 2Gello 3orldU2 application. Recall that the
signature for the main method is public static void main(*tring$% args). Gere, the
args variable is the parameter to this method. !he important thing to remember is
that parameters are always classified as 2variables2 not 2fields2. !his applies to
other parameteraccepting constructs as well (such as constructors and e#ception
handlers) that youIll learn about later in the tutorial.
Gaving said that, the remainder of this tutorial uses the following general
guidelines when discussing fields and variables. "f we are talking about 2fields in
general2 (e#cluding local variables and parameters), we may simply say 2fields2. "f
the discussion applies to 2all of the above2, we may simply say 2variables2. "f the
conte#t calls for a distinction, we will use specific terms (static field, local
variables, etc.) as appropriate. Tou may also occasionally see the term 2member2
used as well. A typeIs fields, methods, and nested types are collectively called its
members.
Naming
Every programming language has its own set of rules and conventions for the kinds
of names that youIre allowed to use, and the Dava programming language is no
different. !he rules and conventions for naming your variables can be summariPed
as follows:
*ubse)uent characters may be letters, digits, dollar signs, or underscore
characters. 6onventions (and common sense) apply to this rule as well. 3hen
choosing a name for your variables, use full words instead of cryptic abbreviations.
(oing so will make your code easier to read and understand. "n many cases it will
also make your code selfdocumenting& fields named cadence, speed, and gear, for
e#ample, are much more intuitive than abbreviated versions, such as s, c, and g.
Also keep in mind that the name you choose must not be a keyword or reserved
word.
"f the name you choose consists of only one word, spell that word in all
lowercase letters. "f it consists of more than one word, capitaliPe the first letter of
each subse)uent word. !he names gearRatio and currentRear are prime e#amples
of this convention. "f your variable stores a constant value, such as static final int
5-E/REAR* 0 J, the
Q. 3ow do you i!ple!ents inheritance in 6a$a?
In'eritan"e in %a1a: nheritance is a compile-time mechanism in Cava that
allows you to e#tend a class (called the base
class or superclass) with another class (called the derived class or subclass).
n Cava+
In'eritan"e is used $or t0o purposes:
2. C!ass in'eritan"e - create a new class as an e#tension of another class+
primarily for the purpose of code reuse. That is+ the derived class inherits the
public methods and public data of the base class. Cava only allows a class to
have one immediate base class+ i.e.+ single class inheritance.
3. Inter$a"e in'eritan"e - create a new class to implement the methods
defined as part of an interface for the purpose of sub typing. That is a class
that implements an interface >conforms to? (or is constrained by the type of)
the interface. Cava supports multiple interface inheritance. n Cava+ these two
kinds of inheritance are made distinct by using different language synta#. 1or
class inheritance+ Cava uses the keyword e#tends and for interface inheritance
Cava uses the keyword implements.
public class derived-class-name e#tends base-class-name X
HH derived class methods e#tend and possibly override
HH those of the base class
T
public class class-name implements interface-name X
HH class provides an implementation for the methods
HH as specified by the interface
T
3#ample of class inhertiance
package @y"ackage6
class Ease X
private int #6
public int f() X ... T
protected int g() X ... T
T
class <erived e#tends Ease X
private int y6
public int f() X H. new implementation for Ease.f() .H T
public void h() X y J g()6 ... T
T
Q. )hat are the difference between an interface and an abstract class?
Ans:
'n abstract class is a class that lea$es one or more method
imlementations unseci!ied by
declaring one or more methods abstract. 'n abstract method has
no body (i.e.& no imlementation). '
subclass is re-uired to o$erride the abstract method and ro$ide
an imlementation. 4ence& an
abstract class is incomlete and cannot be instantiated& but can
be used as a base class.
abstract ublic class abstract1base1class1name 5
66 abstract class has at least one abstract method
ublic abstract return1tye abstract1method1name ( !ormal1
arams )+
... 66 other abstract methods& ob7ect methods& class methods
8
ublic class deri$ed1class1name e#tends abstract1base1class1
name 5
ublic return1tye abstract1method1name (!ormal1arams)
5 stmt1list+ 8
... 66 other method imlementations
8
"t would be an error to try to instantiate an ob7ect o! an abstract
tye%
abstract1class1name ob7 9 new abstract1class1name()+ 66 E::/:;
That is& oerator new is in$alid when alied to an abstract class.
'n inter!ace is a seci!ication& or contract& !or a set o!
methods that a class that imlements the inter!ace must con!orm
to in terms o! the tye signature o!
the methods. The class that imlements the inter!ace ro$ides an
imlementation !or each method&
7ust as with an abstract method in an abstract class.
.o& you can think o! an inter!ace as an abstract class with all
abstract methods. The inter!ace itsel!
can ha$e either ublic& ackage& ri$ate or rotected access
de!ined. 'll methods declared in an
inter!ace are imlicitly abstract and imlicitly ublic. "t is not
necessary& and in !act considered
redundant to declare a method in an inter!ace to be abstract.
0ou can de!ine data in an inter!ace& but it is less common to do
so. "! there are data !ields de!ined in
an inter!ace& then they are imlicitly de!ined to be%
< ublic.
< static& and
< !inal
"n other words& any data de!ined in an inter!ace are treated as
ublic constants.
=ote that a class and an inter!ace in the same ackage cannot
share the same name.
3ethods declared in an interace cannot be declared !inal. >hy?
"nter!ace declaration
"nter!ace names and class names in the same ackage must be
distinct.
ublic inter!ace inter!ace1name 5
66 i! any data are de!ined& they must be constants
ublic static !inal tye1name $ar1name 9 constant1e#r+
66 one or more imlicitly abstract and ublic methods
return1tye method1name ( !ormal1arams )+
8
>hen to use an "nter!ace $s when to use an abstract class%
4a$ing re$iewed their basic roerties& there are two rimary
di!!erences between inter!aces and
abstract classes%
< an abstract class can ha$e a mi# o! abstract and non1abstract
methods& so some de!ault
imlementations can be de!ined in the abstract base class. 'n
abstract class can also ha$e static
methods& static data& ri$ate and rotected methods& etc. "n
other words& a class is a class& so it
can contain !eatures inherent to a class. The downside to an
abstract base class& is that since their
is only single inheritance in @a$a& you can only inherit !rom one
class.
< an inter!ace has a $ery restricted use& namely& to declare a set
o! ublic abstract method
singatures that a subclass is re-uired to imlement. 'n inter!aces
de!ines a set o! tye
constraints& in the !orm o! tye signatures& that imose a
re-uirement on a subclass to imlement
the methods o! the inter!ace. .ince you can inherit multile
inter!aces& they are o!ten a $ery
use!ul mechanism to allow a class to ha$e di!!erent beha$iors in
di!!erent situations o! usage by
imlementing multile inter!aces.
"t is usually a good idea to imlement an inter!ace when you
need to de!ine methods that are to be
e#licitly o$erridden by some subclass. "! you then want some o!
the methods imlemented with
de!ault imlementations that will be inherited by a subclass& then
create an imlementation class
!or the inter!ace& and ha$e other class inherit (e#tend) that class&
or 7ust use an abstract base class
instead o! an inter!ace.
Q. )rite a progra! to perfor! the basic arith!etic operations+ a, Addition b, Subtraction c,
(ultiplication d, Di$ision 2se 7 different !ethods for the abo$e and in$o.e the! as
necessary fro! the !ain8, !ethod?
class Arithmetic
X
public static void main(String args&()
X
int aJ_V+bJ8V6
System.out.println(4Addition is 4Q(aQb))6
System.out.println(4Subtraction is 4Q(a-b))6
System.out.println(4@ultiplication is 4Q(a.b))6
System.out.println(4<ivision is 4Q(aHb))6
System.out.println(4@odulus is 4Q(a\b))6
T
T
Q. )rite a$a progra! to con$ert the %upees to Dollars
'ns%
imort 7a$a.util..canner+
ublic class rueescon$ersion 5
ublic static $oid main(!loat[] args) 5
.ystem.out.rintln(*Enter ruees*)+
double rueesAr+
i! (rueesArB1) 5
double dollar 9 ruesAr6CD.E+
.ystem.out.rintln(*the con$erted $alue !rom ruees to dollars
is%*dollar)+
8
else
.ystem.out.rintln(*Try again*)+
88