Sunteți pe pagina 1din 106

DEPARTMENT OF COMPUTER SCIENCE

CO7101 Java & Databases For Bioinformatics


Course Notes 2014 Dr. S. Kerrigan

Foreword
These notes are to accompany the module CO7101. They contain material that goes beyond the core knowledge of this course. For more motivation and background please attend the lectures. These notes are detailed. Thus, while they should be useful and have been checked carefully, there may be some errors. Please do let me know about any typos or other mistakes which you find. If you have any other (constructive) comments, please tell me about them. If you are to do well in this course, YOU MUST ATTEND THE LECTURES. They will give you additional examples, highlight key issues which may not appear quite as important from the notes as in fact the issues are, and give guidance towards what you need to know for the examinations. You should note especially that with a course of this nature, notation, definitions and ideas can differ even among the experts. The lectures will clarify many of the more woolly areas. It is recommended you purchase the following books to accompany these notes:1. An Introduction to Object-Oriented Programming with Java, 5th Edition by C. Thomas Wu (Otani), Naval Postgraduate School 2. Database Systems: A Practical Approach to Design, Implementation and Management, 5th Edition, Thomas M. Connolly, Carolyn E. Begg

BeforeDatabases:FileBasedApproach toInformationSystems(upto1980s)

CO7101:Java&DatabasesFor Bioinformatics
RelationalDatabases1: Dr.StuartKerrigan
Material in this Unit by Dr. Nick Measor, Dr. Stephan Reiff-Marganiec and Dr. Naila Rhaman
CO7101: Java & Databases For Bionformatics 1

Acollectionofapplicationprogramsthatperform servicesfortheenduserssuchasansweringqueries andproductionofreports. Eachprogramdefinesandmanagesitsowndata, sowemayhavedataredundancy,inconsistency andduplication.


2

LibraryExample

Traditionalfileapproach
Libraryuserfile:
informationabouteachlibraryuser.

Cataloguefile:
informationaboutbooksinthelibrary.

Library needs to manage: the book catalogue book loans book reservations recall of overdue loans catalogue inquiries membership ...

Loansfile:
informationabouteachbookonloanandtheperson whoisborrowingthebook.

Reservationsfile:
informationabouteachbookreservedandtheperson whoisreservingthebook.

Thefiles
Library users Catalogue Loans

Exampleoffile:Thelibraryusers
D. Andrews 14 High Street Oadby Leicester LE2 5HE tel: 274 4893 loan-status: Adult
57-AD-97

D. Andrews d 14 High Street Oadby Leicester LE2 5HE tel: 274 4893 loan-status: Adult

57-AD-97

Reservations
Libraryusers

Traditionalfilebasedapproach
Reservation Information Loan Information Catalogue Inquiry Overdue Letters

Anotherapproach asinglefile
Whynotputalltheinformationinasingletable suchasanExcelspreadsheet?

Reservation Process

Loan Process

Catalogue Inquiry q y Process

Overdue Loans Process


Name Address Telephone Status Book title Book author ISBN Date borrowed

Reservations file

Loans file

Catalogue file

Library-users file And so on with further cells supplying all the inform

NOTE: The processes must relate data between the files when necessary
7 8

Duplicationofinformationinthesingle fileapproach

Summaryoffilebasedsystem disadvantages
Separationofdata Duplicationofdata:wasteful,lossofdataintegrity. Datadependence difficulttochangethestructure ofdata,unresponsivetoupdates,extensions, redevelopment: d l hi high hd development l cost Incompatiblefileformats Fixedqueries,difficulttodoadhocqueries Lowreliability,security,integrity

Name D. Andrews D. Andrews

Address 14 High Street 14 High Street

Telephone 274 4893 274 4893

Status Adult Adult

Book title Donatello War and Peace

Book author Green halgh Tolstoy

ISBN 1234567 4561234

Date borrowed 12/04/ 2006 18/05/ 2006

10

Thesolution useadatabase
A shared collection of logically related data (and a description of this data) designed to meet the information needs of an organisation. Importantpointstoremember: shared collection selfdescribing logicallyrelated:
entities attributes relationships

DefinitionofDBMS
A software system that enables users to define, create and maintain the database and provides a controlled access to this database.

aDBMSprovidesthefollowingfacilities: DataDefinitionLanguage:datatypesandstructures DataManipulationLanguage:querylanguage(e.g.SQL) Controlledaccesstothedatabase



11

asecuritysystem aconcurrencycontrolsystem anintegritysystem arecoverycontrolsystem


12

DatabaseAdvantages
consistentandstructuredmodelofdata efficientelectronicfilingcabinet:noneedto controldata ad dhoc h queries i easytoupdate,changestructure concurrency:sharingdata improvedsecurity

Themainidea

Model the world


13 14

Users modelofa library


System rules 1. A copy of a book can only be lent to one person at a time. 2. A person may borrow several books at a time. 3. Each person has a status in the library which determines such things as loan period, max. books on loan, overdue fees.
15

Modellingtheworld
My model model

applications

information available the h same?

database

information desired database design data model

Start

16

EntityRelationshipModeloftheLibrary
Catalogue isbn title 0..* date publisher 1 CopyOf Reserves 0..* Book copy# accession-date 0..* IsonLoan 0..1 0..* Library-user user# name address tel HasStatus 0..* 1 Status id status-details 0..* res-date Writtenby 0..* Author name author-details

Implementers modelofthe library


The relation schemas:

Book(copy#, isbn, accession_date) primary key: copy# foreign key: isbn references Catalogue(isbn) Library-user(user#, name, address, tel, status) primary key: user# foreign key: status references Status(id) Loan(copy#, user#, date) primary key: copy#, user# foreign key: copy# references Book(copy#) foreign key: user# references Library-user(user#) Catalogue(isbn, title, publisher, date) primary key: isbn Reservation(user#, isbn, date ) primary key: user#, isbn foreign key: user# references Library-user(user#) foreign key: isbn references Catalogue(isbn) Written-by(isbn, name) primary key: isbn, name foreign key: isbn references Catalogue(isbn) foreign key: name references Author(name)

Status(id, details ) primary key: id Author(name, details) primary key: name

loan-date
17

18

Objectives
CO7101:Java&DatabasesFor Bioinformatics
RelationalDatabases2: TheStoryofLarryTheLion Dr.StuartKerrigan
Theterminologyoftherelationalmodel
Candidate,primaryandforeignkeys

Howtouserelationstomodel
entities ii relationshipsbetweenentities

Integrityrulesforrelationalmodel Queries

CO7101: Java & Databases For Bionformatics

19

20

DefinitionofDataModel
An integrated collection of concepts for describing data, relationships between data, and constraints on the data.
Therearethreecomponentsofeachdatamodel: databases,terminology astructuralpart rulesforconstructingdatabases asetofintegrityrulestoensuredataaccuracy amanipulativepart definesthetypeofoperationsthat areallowedonthedatabase

PastandPresentofRM
TherelationalmodelwasoriginallydescribedbyE.F. Coddinhis1970paper Arelationalmodelofdataforlargeshareddata banks

Thereareobjectbased,relational,andotherdatamodels.Herewe considertherelationalmodel.

21

22

History
Threeprojectsthatstarteditallinlate1970s
SystemR,byIBMinlate1970s
StructuredQueryLanguage(SQL)developed commercialproducts:SQL/DSandORACLE

Entities
Anentityisa
thing object concept

INGRES, G S,Uni. U of o California a o aatBerkeley e e ey


relationalDBMSIngres

PeterleeRelationalTestVehicle,IBMUK
queryprocessing,optimization,functionalextensions

intherealworld
Can be distinguished from other objects.

CommerciallyavailablePCversionsofRDBMSs
AccessandFoxProfromMicrosoft ParadoxandVisualdBasefromBorland
23

24

Attributes
Anattributeisapropertyofanentity Anobjectcanbedescribedbyasetof properties:
One O mayuniquely i l id identify tif anobject bj t(k (key) ) Othersmayadd(useful)information

ModellingEntitiesintheRealWorld

entity

represented by a name and a set of attributes

25

26

Terminology
Asetofentitiesofthesametypeis representedasatable(alsocalledrelation) Eachrow inthetablerepresentsanentity Each hcolumn l representsanattribute ib Anatomicplaceinatableiscalledacell

DifferentTerminology
User Relational Model Relation Programmer

Table

Row Column
27

Tuple Attribute

File or Array Record Field


28

ARelationAboutFilmStars
Star
name Marlon Brando Harrison Ford Dustin Hoffman Robert Redford Meryl Streep yob 1924 1942 1937 1937 1949 sex Male Male Male Male Female country USA USA USA USA USA

PropertiesofRelations
Relationshavenames Eachcelloftherelationcontainsoneatomicvalue Eachattribute(column)hasadistinctname Valuesofattributescomefromthesamedomain Theorderofattributesisirrelevant Thenumberofcolumns(attributes)iscalleddegree Eachtuple(row)isdistinct Theorderoftuplesisnotsignificant,theoretically Thenumberofrows(tuples)iscalledcardinality

29

30

Keys

Identify?
What is meant by identify? Real World Model a set of values will take you to a unique object (entity) (entity). a set of values will take you to a unique row (tuple).

a1

a2

a3

a4

Really the same: an object in the real world is modelled by a row in a table.

uniquely identifies entity


31 32

Keys
identifies a unique Larry row in a table key identifies an object in the world

Superkeys
Asuperkey isasetofoneormoreattributes thatuniquelyidentifiesanentitywithina relation Superkeys p y always y exist j justtakeall attributes Forexample,
row is modelling the object

name,weightandageinAnimal familyandfoodinDiet typeinFood


34

Larry Lion
33

CandidateKeys
LetR bearelationschema(relationname followedbyalistofattributenames).A subsetI oftheattributenamesofR iscalleda candidatekey if:
Notwodistincttuplesoftherelationcantakethe samevaluesonI (Uniqueness)(inotherwords,I is asuperkey) NopropersubsetofI satisfiestheaboverule (Irreducibility)
35

PrimaryKeys
Theprimarykey isthecandidatekeythatisselected toidentifytuplesuniquelywithintherelation Relationshipsbetweendifferentkeys:
Therecanbemanysuperkeys.Someofthesuperkeysare candidatekeys.Oneofthecandidatekeysistheprimary key. Acandidatekeyisasuperkeysuchthatnopropersubset ofitisasuperkeywithintherelation

36

Example

Thezoohasanotherproblem

registration

make

model

colour

Car(registration, make, model, colour) The zoo obtained a new animal Larry the Leopard
Underline: primary key
37 38

PrimaryKey
Nameusedasprimarykey Butwecannothavetwoanimalswiththe sameprimarykey! which Larry? y Possible ibl solutions: l i
changeLarry'sname keybecomesname+family introduceanewartificialkey surrogate key
39

Relationships
Anassociationbetweentwoormoreentities Identified/describedbytwoormorekey attributes
Entity Type Star cast_as role Relationship Entity Type Film

similar problems, what happens if another leopard called Larry arrives?

40

RelationshipsRepresentedbyTables
Given the Film Star table and the Film table, an example of a relationship between these tables is the Role relation (table): Role Name HarrisonFord HarrisonFord Marlon Brando Film StarWars RaidersoftheLost Ark LastTangoInParis Cast_As HanSolo IndianaJones Paul

Tables
Atablemodels:
objectsintherealworld relationshipsbetweenobjects(entities)

In I all llcasesat table bl i iscalled ll darelation l ti

42

RelationSchemaDefinition
Relation schema is a set of attribute names and their domains. Attribute names name nationality yob Player(name, nationality, yob) Domains CHARACTER(25) CHARACTER(10) SMALLINT

ExampleofRelation
A set of tuples for relation Player (Tom Watson , USA, (Jack Nicklaus, ( , USA, , (Severiano Ballesteros, Spain, (Raymond Floyd, USA, 1949) 1940) ) 1957) 1942)

Values of attribute name


43

Taken from domain CHARACTER(25)


44

ABetterDefinitionofRelation
Givenarelationschema,arelation ortable definedforthatschemaisafinitesetoftuples suchthat:
Eachtuplecontainsasmanyvaluesasthereare attributenamesintherelationschema. Eachvalueisdrawnfromthedomainwithwhich itsattribute(column)typeisassociated. Recall:

ForeignKeys
Theremaybemorethanonecandidatekey Wemaychooseaparticularoneandcalledittheprimary key

Aforeignkey isanattribute(orasetofattributes) thatmatchesthecandidatekeyofsomerelation Examples:keeperattributeintheAnimaltable,or supervisorintheManagedbytable

45

46

Examples
Animal name Larry Ernie Sydney ... Keeper family weight age 4 3 6 lion 500 elephant 4000 snake 1000

foreign key keeper 112 724 134

RelationalIntegrity
Relationalintegrity isasetofruleswhich ensurethatthedataisaccurate Therulescontain:
Domainconstraints(wehavealreadymetthese constraints) Entityintegrityrule Referentialintegrityrule

personnel_no 112 724 134 ...

name Jones Thomas Brown

age 34 42 25

Beforewedefinethelasttworules,westudy theconceptofnulls
47 48

Nulls
Nullrepresentsavalueforanattributethatis currentlyunknownoritisnotapplicable. Nullisnot thesameas
numericvaluezero stringofspaces

EntityIntegrity
Recall:Entitiesaremodelledbytables.Eachtable hasaprimarykey. EntityIntegrity: In a table table, no cell under a primary key column can be null. Forexample,intheAnimaltablenorecordcanhave anullinthenamecolumn;andintheFoodtable theremaybenonullsinthetype(ofFood)column

NotallRDBMSusenulls.Ifwedontusenulls,then weneedtousefalsedatatorepresentmissingor nonapplicabledata.Forexample,usenumber1in thefieldoftypetext.


49

50

ReferentialIntegrity
If a foreign key exist in a table, either the foreign key value must match a candidate key value of some row in its home table, or the foreign key value must be null. For example, we cannot have a record in the Animal table with 700 in the keeper cell, unless there is a keeper 700 in the Keeper table. But, we can have an animal with null value under keeper: the new arrival (Larry the Leopard) has not yet been assigned to a particular keeper.
51

Queries
Howtosearchforspecificdatainthedatabase?
Example:listallanimalseatingbunswithweightbetween 20and200kg,inascendingorderoftheirage

DBMSsupportsflexiblequeries ofthedata Q QBE(Q (Query yby yexample): p ) avisualway yofspecifying p y ga query SQL(StructuredQueryLanguage):alanguagefor specifyingqueriestoarelationaldatabase
defactostandard UseEnglishwords,e.g.SELECT,INSERT,WHERE

52

QBEandSQL
QBEcanberegardedasagraphicalfrontendto SQL Theyarenonprocedurallanguages:youspecifywhat youwant,nothow togetit Someoperations:
Updatedata Searchdataaccordingtosomecriteria Displayresultsincertainorder Aggregatefunctions(max,sum,)

Summary
Arelationaldatabaseconsistsofnothingbut relationsrepresentedastables Atablecanrepresenteitheranentitysetora relationshipbetweenentities Eachtablehasapredefinedandtimeinvariant format thisisspecifiedbytherelationschema Eachtableishomogeneous eachcolumncontains onlyvaluesfromaspecifieddomain

Inthepracticals,youwilllearnhowtouseQBEin Access
53

54

Summary:Terminology
arealworldobject/concept acollectionofentities apropertyofanentity atablewithcolumnsandrows arowin i atable t bl anassociationbetweentwoor moreentities Database asetoftablesforentitysetsand relationships Rel.Databaseacollectionofnormalized tables
55

Entity Entityset Attribute Relation T l Tuple Relationship

CO7101Java&Databases
EntityRelationshipDiagrams Dr.StuartKerrigan

CO7101 Java & Databases

56

Objectives
Theuseofconceptualmodelstosupport databasedesign BasicconceptsofEntityRelationship(ER) model:entities, entities attributes, attributes relationships Typesofrelationships DiagrammatictechniquefordisplayingER models

TheDatabaseDesignProcess
Step1:Constructaconceptualmodel (typicallyERmodel)tocapturepreciselythe realworldproblem Step2:Designdatabasetablestorepresent theERmodel Step3:ImplementthetablesinaDBMS WewillnowstartStep1
57 58

ConceptualModelling
Theprocessofconstructingamodelforcertain informationthatisindependentofimplementation issuessuchas
ThetypeofDBMS Applicationprograms Programminglanguage Otherphysicalconsiderations

TheEntityRelationship(ER)Model
TheERmodelisahighlevelconceptualmodel proposedbyP.P.Chenin1976inthepaper
TheEntityRelationshipmodel towardsaunifiedviewof data

PurposeofERmodel:
Supportusersunderstandingofinformation Abstractfromtechnicaldetailsofdatabasedesign BeindependentofDBMSandhardwareissues

Theconceptualmodelshouldbeacompleteand accuraterepresentationoftherequiredinformation
59

60

10

EntityRelationshipModelling
EntityRelationshipmodelling:identifywhat informationwewanttodescribe,and structurethatinformationinasensibleway Howdowedothis?
identifyentities identifyattributes identifyrelationships betweenentities
The basic concepts of ER modelling

Entities
Anentity issomethingthatmakessenseinan applicationcontext:
atangibleand/orvisiblething somethingthatmaybeapprehendedintellectually somethingtowardwhichthoughtoractionis directed somethingaboutwhichinformationneedstobe recorded

61

62

EntitiesandTheirRepresentation

Entitiesvs.EntityTypes
Entitytype:anobjectoraconceptthatis identifiedbyusersashavinganindependent existence
Examples:car,employee,sale

concept

of a car

instance

of a car

Entity:aninstanceofanentitytypethatis uniquelyidentifiable
Examples:
JohnSmith,L1328,1HighStreet,... XTX456ANissanBluebird,1023,1234,...

Car(reg#,make,model)

XTX456A Nissan Bluebird

63

64

Attributes
Anattribute isanabstractionofasingle characteristicorpropertyofanentityora relationshiptype Entitiesareidentifiedbytheirproperties,i.e. bysetsofvaluesheldbyattributes Attributedomainisasetofvaluesthatmaybe assignedtoanattribute
65

AttributeValuesforaCar

Attributes registration# make model

MVI 321 BMW 316


66

11

FindingandClassifyingAttributes
Namingattributes:usedtouniquelyidentify anentity
Usuallydontchange Whatuniquely q yidentify ythisobject j fromother similarobjects(sameentityset)?

Simplevs.CompositeAttributes
Simpleattribute:composedofasingle component,withanindependentexistence Compositeattribute:composedofmultiple components eachwithanindependent components, existence
Forexample,Address:containsnumber,street, town,...components.

Descriptiveattributes:provideintrinsic informationabouttheentity
whatpropertiesdistinguishthisentity(from otherentitytypes)?
67

68

Single vs.MultivaluedAttributes
Attributesareeithersingle ormultivalued dependingonthenumberofvaluestheyhold
Examples:
Tel_No:onemayhavemorethanonetelephonenumber Gender:onecanonlyhaveonegender Type_of_food:adishmayconsistofseveraltypesoffood:protein, carbohydrates,...

DerivedAttributes
DerivedAttribute:anattributewhosevalueis derivablefromthevaluesofotherattributes, notnecessarilyinthesameentity
Examples:
AgeisderivablefromDoB Total_Staff(of,say,theDepartmententity)canbe calculatedbycountingStaffentities

Whatisthedifferencebetweencompositeandmulti valuedattributes?
69

70

ERDiagrams:EntitiesandAttributes
Entity name
Employee NI#[PK] name fi t firstname lastname dob /age skills[1..3]

Relationships
There are relationships between entities: XBS 456 N Ford Zodiac My car P#351 John Smith 1 Hi High h Street St t Leicester

Primary key Composite attribute Derived attribute Multi-valued attribute


71

P#351 owns XBS 456 N

Attributes

Relationship: an association of entities, where the association includes one entity from each participating entity type
72

12

RepresentingRelationships

Relationship:Notation
Entity_type_name_1 attribute-1 attribute-2 relationship Entity_type_name_2 attribute_3 attribute_4

Example:
Car reg#[PK] make model owns Owner personnel-no[PK] name street town

Staff RelatedTo

Next_of_Kin

73

74

Relationship:SomeTerms
Degree ofarelationship:thenumberofparticipating entitiesinarelationship
binary ternary quaternary unary(recursive)
Example:SupervisesbetweentheentitiesKeeperandKeeper

StructuralConstraintsonRelationships
Therearecardinality andparticipation constraints Cardinalityratio (ormultiplicity):describesthe numberofpossiblerelationshipsforeach participatingentity Forbinaryrelationships,cardinalityratiosare
onetoone onetomany manytoone manytomany

Relationshipsmaybegivenrolenames toindicate thepurposethateachparticipantplaysina relationship


75

76

KindsofRelationship 1
OnetoOne
Everywarehousehasnomorethanonemanager EverymemberofStaffcanmanageatmostone warehouse
Staff 0..1
Manages

OnetoOneRelationships
a1 a2 a3 b1 b2 b3

Warehouse 0..1

77

78

13

KindsofRelationship 2
ManytoOne
Everyemployeeworksatnomorethanone warehouse Everywarehousehasseveral(>=0)employees workinginit
Employee 0..*
Works_in

ManytoOneRelationships
a1 a2 a3 a4 a5
79 80

b1 b2 b3

Warehouse 0..1

KindsofRelationship 3
OnetoMany
Eachmanagersupervisesseveralemployees Everyemployeeissupervisedbyonlyone manager
Manager 0..1
Manages

OnetoManyRelationships
b1 a1 a2 b2 b3 b4 b5
81 82

Employee

a3
0..*

KindsofRelationship 4
ManytoMany
Eachstudenttakesseveral(>=0)modules Eachmoduleistakenbyanumber(>=0)of students
Student 0..*
Takes

ManytoManyRelationships

a1 a2 a3

b1 b2 b3 b4

Course 0..*
a4

83

84

14

SomeExamples
Whatisthecardinalityratiooftheserelationships?
Entitysets:Males,Females Relationship:ismarriedto Entity:Animals,Families Relationship:belongsto Entity:Books,Users Relationship:isreservedby

ParticipationConstraints
Determinewhethertheexistenceofanentity dependsuponitbeingrelatedtoanotherentity throughtherelationship. Ifanentitysexistencerequirestheexistenceofan associatedentityinaparticularrelationship,then participationistotal.Otherwise,itispartial. Totalandpartialparticipationareoftenreferredtoas mandatory andoptional,respectively.

85

86

MembershipClass 1
Mandatory(total)bothsides:
Astudentmustattendatleastonelecture Alecturemustbeattendedbyatleastone student
Student 1..*
Attends

MembershipClass 2
Mandatoryonesideandoptionaltheother side:
Astudentmustattendatleastonelecture Alectureneednotbeattendedbyanystudents
Student 0..*
Attends

Lecture 1..*

Lecture 1..*

Student membership is mandatory. Lecture membership is mandatory.


87

Student membership is mandatory. Lecture membership is optional.


88

MembershipClass 3
Optionalbothsides:
Astudentneednotattendanylectures Alectureneednotbeattendedbyanystudents
Student 0..*
Attends

Strongvs.WeakEntityTypes
Strongentitytype:anentitytypethatisnot dependentontheexistenceofanotherentitytype foritsprimarykey
Forexample,Staff,Library_User, ... Hasitsownprimarykey

Lecture 0..*

Weakentitytype:anentitytypethatisdependent ontheexistenceofsomeotherentitytypeforits primarykey


Forexample,Next_of_Kin,Appointment,...(seenextslide) Hasnoprimarykeyofitsown

Student membership is optional. Lecture membership is optional.


89

90

15

WeakEntities:inDiagrams
Notethetotalparticipation(why?)
Employee Employee_id[PK] 1..1
Client

Summary
ERmodelanddiagrams
Entities,attributesandrelationships

has
0..*

Dependent Name

Weak entities

Typesofrelationships
Cardinality: C di li onetoone,onetomany,manyto one,manytomany Participation:total/partial

Client_id[PK]

made
1..1 0..*

Appointment Date Time

91

92

Revision:ThecomponentsofaDB

CO7101Java&Databases
Normalization:WhenThereIs Something FishyInYourDatabases Dr.StuartKerrigan
CO7101 Java & Databases 93

Data

Database a abase Management System

LimitationsofFFDBs
SUPPLIER Viglen Opus Opus Viglen Opus

ExampleDatabases
SUPPLIER ADDRESS 23 Main St. 5 High St. 5 High St. 23 Main St. 5 High St. SUPPLIER PHONE 234345 343434 343434 234345 343434 GOODS SUPPLIED 2 586 PCs 6 486 PCs 1 printer 4 586 PCs 2 486 PCs DATE SUPPLIED 23/3/97 12/12/96 3/4/97 12/1/97 12/3/97 INVOICE NUMBER 3456483 4566578 4566683 3456210 4566602

Flatfiledatabasesaresuitableforstorage tasksifdataissimple,orifthereisnottoo muchofit. Ifdatastoredistoocomplex,thentheflat filedatabasebreaksdown itexhibitsa numberofanomalies.

STUDENT Smith, A. Smith, A. Bloggs, F. Bloggs, F. Bloggs, F.

STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1

LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell

DEPT. CompSci CompSci CompSci CompSci Chem

ROOM BEN LT5 PH LTA BEN LT5 PH LTA CLT

TIME 2.00 1.00 2.00 1.00 12.00

TITLE Information Technology Information Technology Databases for Dummies Spreadsheets for Idiots

AUTHOR Smith & Jones Smith & Jones Bloggs Macpherson

PUBLISHER Collins Collins Longmans Collins

YEAR 1990 1996 1993 1994

ISBN 1-23445-345 1-23445-319 2-34542-422 4-34589-445

PRICE 20.00 25.00 15.00 18.00

16

UpdateAnomaly

Example UpdateAnomaly
SUPPLIER Viglen Opus Opus Viglen Opus SUPPLIER ADDRESS 23 Main St. 5 High St. 5 High St. 23 Main St. 5 High St. SUPPLIER PHONE 234345 343434 343434 234345 343434 GOODS SUPPLIED 2 586 PCs 6 486 PCs 1 printer 4 586 PCs 2 486 PCs DATE SUPPLIED 23/3/97 12/12/96 3/4/97 12/1/97 12/3/97 INVOICE NUMBER 3456483 4566578 4566683 3456210 4566602

Ifdataappearsmorethanonceinthe database,thenifoneitemofthedatais altered,wemustalterall theinstancesof thatdata.

SUPPLIER Viglen Opus Opus Viglen Opus

SUPPLIER ADDRESS 23 Main St. 59 High St. 5 High St. 23 Main St. 5 High St.

SUPPLIER PHONE 234345 343434 343434 234345 343434

GOODS SUPPLIED 2 586 PCs 6 486 PCs 1 printer 4 586 PCs 2 486 PCs

DATE SUPPLIED 23/3/97 12/12/96 3/4/97 12/1/97 12/3/97

INVOICE NUMBER 3456483 4566578 4566683 3456210 4566602

InsertionAnomaly

Example InsertionAnomaly
STUDENT Smith, A. Smith, A. Bloggs, F. Bloggs, F. Bloggs, F. STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1 LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell DEPT. CompSci CompSci CompSci CompSci Chem ROOM BEN LT5 PH LTA BEN LT5 PH LTA CLT TIME 2.00 1.00 2.00 1.00 12.00

Ifnewinformationisavailable,wemaynot beabletoenterthedatauntilwehavedata forallfields.

STUDENT Smith, A. Smith, A. Bloggs, F. Bloggs, F. Bloggs, F. .

STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1 Chem2

LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell Dr. Clapper

DEPT. CompSci CompSci CompSci CompSci Chem Chem

ROOM BEN LT5 PH LTA BEN LT5 PH LTA CLT

TIME 2.00 1.00 2.00 1.00 12.00

DeletionAnomaly

Example DeletionAnomaly
STUDENT Smith, A. Smith, A. Bloggs, F. Bloggs, gg F. Bloggs, F. STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1 LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell DEPT. CompSci CompSci CompSci CompSci p Chem ROOM BEN LT5 PH LTA BEN LT5 PH LTA CLT TIME 2.00 1.00 2.00 1.00 12.00

Ifwedeletesomeinformationfromthe database,wemayaccidentallyremove additionaldata whichwewishtokeep.

IfwedeleteBloggs fromtheChem1coursewelose ouronlyrecordthatDr.Bellteachesthisclassinthe Chem DepartmentRoomCLTat12.00. Notveryintelligent.

17

FunctionalDependency
Alltheseanomaliesoccurbecause somefieldsarefunctionallydependent ononeanother. e.g.all llrecords d showing h i Dr. D Kerrigan K i will ill showhisDepartmentasComputer Science,andsoon.

FunctionalDependency
Apropertythatexistsbetweenfields
thatthevalueinonefielddeterminesthevalue thatcanbecontainedintheotherfield

E E.g. g ifyouknowthevalueofthefirstattribute youcanfindthevalueofasecondattribute

ExampleofFD
A B

RealLifeExampleofFD
A B

If I know the value of A I can find the value of B

StudentID

StudentName

If I know the StudentID I can find the corresponding StudentName

RealLifeExampleofFD
A B

RealLifeExampleofFD
A B

StudentID

StudentName

StudentID [PK]

StudentName

Dateof Birth If I know the StudentID I can find the corresponding StudentName and the corresponding Date Of Birth

Dateof Birth In good database design all non-key fields should be dependant solely on all parts of the primary key.

18

CompositePrimaryKeys
ClientID [PK] PropertyID [PK] ClientID [PK] Comments PropertyID [PK] In good database design all non-key fields should be dependant solely on all parts of the primary k Dateof Birth

TransitiveDependency
A B

TransactionID

CustomerName

SalesRep

If I know the TransactionID I can find the Customers Name. Once I know the Customers Name I can find the SalesReps Name

TransitiveDependency
A B

TheSolution MultipleTables
Wemustextractsomeofthedata fieldsfromthelist(ortable)andcreate asecondtable(ormore). Ourapplicationmustnowbeableto handlemultipletables,andperform queriesetc.acrossmultipletables.

TransactionID

CustomerName

SalesRep

If I know the TransactionID I can find the Customers Name. Once I know the Customers Name I can find the SalesReps Name

ConvertingaDatabase

Normalisation
FirstnormalformaccordingtoCodd

Ifwehaveanexisting flatfiledatabase,we canconvertitintoawellbehaved relationaldatabaseviaastepbystep processknownasnormalisation.

Allfieldsmustcontainatomic data. Codd definesanatomicvalueasone that"cannotbedecomposedinto smallerpiecesbytheDBMS(excluding certainspecialfunctions).

19

Example 1NFAccordingtoCodd Arefieldsatomic?


Name [PK] Dr. StuartKerrigan Prof. Klaus Himmelheim M Peter Mr. P t Venkman V k Office F25 D22 ECTO1 Phone Number1 3333 211 3332 Phone Number2 4452 NULL 3432 Phone Number3 34421 NULL NULL Dr. Prof. Mr. Title [CPK]

Example 1NFAccordingtoCodd Arefieldsatomic?


First Name [CPK] Stuart Klaus Peter Surname [CPK] Kerrigan Himmelheim Venkman Office Phone Number1 3333 211 3332 Phone Number2 4452 NULL 3432 Phone Number3 34421 NULL NULL F25 D22 ECTO1

WhyisthisexampleNOTin1NF?

Namewasnotatomic couldbe furtherdecomposed. Notecompositeprimarykey.

Example 1NF
STUDENT Smith, A. Smith, G. Bloggs, F. Bloggs, gg T. Bloggs, F. STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1 LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell DEPT. CompSci CompSci CompSci CompSci p Chem ROOM BEN LT5 PH LTA BEN LT5 PH LTA BEN LT5 TIME 2.00 1.00 2.00 1.00 1.00

RepeatingColumns
These3columnsrepeatastheyare storingthesameinformation
Phone Number1 3333 211 3332 Phone Number2 4452 NULL 3432 Phone Number3 34421 NULL NULL

SURNAME Smith Smith Bloggs Bloggs Bloggs

INITIAL A. G. F. T. F.

STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1

LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell

DEPT. CompSci CompSci CompSci CompSci Chem

ROOM BEN LT5 PH LTA BEN LT5 PH LTA BEN LT5

TIME 2.00 1.00 2.00 1.00 1.00

Example 1NF AccordingtoDate


RemoveRepeatingColumns
Title [CPK] Dr. Prof. Mr. First Name [CPK] Stuart Klaus Peter Surname [CPK] Kerrigan Himmelheim Venkman Office Phone Number1 3333 211 3332 Phone Number2 4452 NULL 3432 Phone Number3 34421 NULL NULL F25 D22 ECTO1

Normalisation
Secondnormalform Mustbe1NF. Automatically2NFifnocomposite primarykey. Eachnonkeyattributeintablemustbe functionallydependentuponthewhole primarykey.

Phone
Phone Number[PK] 3333 4452 34421 211 3332 3432 StaffID [FK] 1 1 1 2 3 3

Staff
StaffID [PK] 1 2 3 Title First Name Stuart Klaus Peter Surname Office

Dr. Prof. Mr.

Kerrigan Himmelheim Venkman

F25 D22 ECTO1

20

Example 2NF
Viewing
ClientNo [Comp PK] CR56 CR56 CR56 CR62 CR76 PropertyNo [CompPK] PA14 PG36 PG4 PA14 PG4 ViewDate 24May01 28Apr01 y01 26May 14May01 20Apr01 Comment toosmall NULL NULL nodining room tooremote FirstName Annie Annie Annie John Ivor LastName Bradock Bradock Bradock Wayne Taper City Detroit Edinburgh London Detroit London ClientNo [CompPK ForeignKey] CR56 CR56 CR56 CR62 CR76

Example 2NF
PropertyNo [CompPK ForeignKey] PA14 PG36 PG4 PA14 PG4 ViewDate 24May01 28Apr01 26May01 14May01 20Apr01 Comment toosmall NULL NULL nodiningroom tooremote

Notethecompositeprimarykey(i.e.keyconsists of2fields) Eachnonkey attributeintablemustbe functionallydependentupontheentireprimary key. Isthisso?

ClientNo [PK] CR56 CR62 CR76

FirstName Annie John Ivor

LastName Bradock Wayne Taper

PropertyNo [PK] PA14 PG36 PG4

City Detroit Edinburgh London

Nowin2nd NormalForm

Normalisation
Thirdnormalform Mustbe2NF. Allthenonkeyfieldsmustbe dependentontheprimarykey.
OrderNo [PK] 1 2 3 4 5

Example 3NF
Customer Acme StuCorp Acme Acme StuCorp Contact Person Dave Fred Dave Dave Fred Total 20 20000 15 123 0.50

OrderNo servesastheprimarykey. Customerandtotalamountaredependentontheorder number thisdataisspecifictoeachorder. However,thecontactpersonisdependentuponthe customer. Thereisreallya11relationshipbetweenCustomerand ContactPerson.

Example 3NF
OrderNo [PK] 1 2 3 4 Customer Acme StuCorp Acme Acme Total 20 20000 15 123 Contact Customer [PK &Foreign Person Key] Acme StuCorp Dave Fred
SURNAME Smith Smith Bloggs Bloggs l Bloggs INITIAL A. A. F. F F. F.

Example 3NF
Student. No. pk 765432 765432 776829 776829 776829 COURSE CO1019 CO1005 CO1019 CO1005 Chem1 LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan D S Dr. Solanki l ki Dr. Bell DEPT. CompSci CompSci CompSci C CompSci S i Chem ROOM BEN LT5 PH LTA BEN LT5 PH LTA BEN LT5 TIME 2.00 1.00 2.00 1 00 1.00 1.00

Createtablestorepresentrelations a11relationship betweenCustomerandContactPerson.

21

Example Convertingto3NF
STUDENT Smith, A. Smith, A. Bloggs, F. Bloggs, F. Bloggs, F. STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1 LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell DEPT. CompSci CompSci CompSci CompSci Chem ROOM BEN LT5 PH LTA BEN LT5 PH LTA BEN LT5 TIME 2.00 1.00 2.00 1.00 1.00

2NFand3NF
Difference betweenthe secondandthird normalformsofa normalized database?
"Thekey, thewholekey, 2NF andnothingbut 3NF thekey, sohelpmeCodd."

SURNAME INITIAL Smith A Bloggs F

STUDENT No STUDENT. No. 765432 776829

LECTURER Dr. Kerrigan Dr. Solanki Dr. Bell

COURSE CO1019 CO1005 Chem1

STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1

COURSE CO1019 CO1005 Chem1

ROOM BEN LT5 PH LTA BEN LT5

TIME 2.00 1.00 1.00

Beyond3NF
BoyceCodd normal form(BCNF) RaymondF.BoyceandCodd (1974) Everynontrivialfunctional dependencyinthetableisa dependencyonasuperkey Everynontrivial multivalued dependencyin thetableisadependency onasuperkey Everynontrivialjoin dependencyinthetableis impliedbythesuperkeys of thetable Everyconstraintonthe tableisalogical consequenceofthetable's domainconstraintsandkey constraints Tablefeaturesnonontrivial joindependenciesatall (withreferenceto generalizedjoinoperator)

Beyond3NF
Firstnormalform(1NF) Codd (1970),Date(2003) Tablefaithfully representsarelation,dataisatomicandhasnorepeatinggroups Secondnormalform(2NF) Codd (1971) Nononprimeattributeinthe tableisfunctionallydependentonapart(propersubset)ofacandidate key Thirdnormalform(3NF) Codd (1971) Everynonprimeattributeis nontransitivelydependentoneverykeyofthetable BoyceCodd normalform(BCNF) BoyceandCodd (1974) Everynon trivialfunctionaldependencyinthetableisadependencyonasuperkey Fourthnormalform(4NF) Fagin(1977) Everynontrivialmultivalued dependencyinthetableisadependencyonasuperkey Fifthnormalform(5NF) Fagin(1979) Everynontrivialjoin dependencyinthetableisimpliedbythesuperkeys ofthetable Domain/keynormalform(DKNF) Fagin(1981) Everyconstraintonthe tableisalogicalconsequenceofthetable'sdomainconstraintsandkey constraints Sixthnormalform(6NF) Date,Darwen,andLorentzos (2002) Table featuresnonontrivialjoindependenciesatall(withreferenceto generalizedjoinoperator)

Fourthnormalform (4NF)

Fagin(1977)

Fifthnormalform(5NF) Fagin(1979)

Domain/keynormal form(DKNF)

Fagin(1981)

Sixthnormalform(6NF)

ChrisDate,HughDarwen,and NikosLorentzos (2002)

SUMMARY

Flatfiledatabasescanhandleonly
simple andsmallscaledata,otherwise anomalies occur Relationaldatabasescanhandlecomplex andlargeamountsofdata Normalisationisusedtoensureefficient relationships

Relationships&Functional p y Dependency
Dr.StuartKerrigan

22

ASimpleBinaryRelationship
Peopleownmanyhouses. Somepeopleownnohouses. Somehousesareunowned. Somehouseshavemany peopleinthem.

ASimpleBinaryRelationship
Peopleownmanyhouses. Somepeopleownnohouses. Somehousesareunowned. Somehouseshavemany peopleinthem.

ASimpleBinaryRelationship
Peoplecanliveinmany houses. Somepeopleliveinnohouses. Some S h housesareempty. Somehouseshavemany peopleinthem.

ASimpleBinaryRelationship
Peoplecanliveinmany houses. Somepeopleliveinnohouses. Some S houses h areempty. Somehouseshavemany peopleinthem.

ASimple?Relationship
Somestaffmanage1ormore staffmembers. Somestaffdonotmanage otherstaffmembers. members Astaffmemberhasatmost onemanager

ASimple?Relationship
Managementstaffmanage1 ormorestaffmembers. Somestaffdonotmanage otherstaffmembers. members Astaffmemberhasatmost onemanager
manages

23

FunctionalDependency
Apropertythatexistsbetweenfields
thatthevalueinonefielddeterminesthevalue thatcanbecontainedintheotherfield
A

ExampleofFD
B

E E.g. g ifyouknowthevalueofthefirstattribute youcanfindthevalueofasecondattribute

If I know the value of A I can find the value of B

RealLifeExampleofFD
A B

RealLifeExampleofFD
A B

StudentID

Student Name

StudentID

Student Name Dateof Birth

If I know the StudentID I can find the corresponding StudentName

If I know the StudentID I can find the corresponding StudentName and the corresponding Date Of Birth

RealLifeExampleofFD
A B

CompositePrimaryKeys
ClientID [PK] PropertyID [PK] ClientID [PK] Comments PropertyID [PK] In good database design all non-key fields should be dependant solely on all parts of the primary k Dateof Birth

StudentID [PK]

StudentNa me Dateof Birth

In good database design all non-key fields should be dependant solely on all parts of the primary key.

24

TransitiveDependency
A B

TransitiveDependency
A B

Transactio nID

Customer Name

SalesRep

Transactio nID

CustomerN ame

SalesRep

If I know the TransactionID I can find the Customers Name. Once I know the Customers Name I can find the SalesReps Name.

If I know the TransactionID I can find the Customers Name. Once I know the Customers Name I can find the SalesReps Name.

SQLComponents:DDL,DML,&DCL

CO7101:Java&DatabasesFor Bioinformatics
SQL1: SimpleDataDefinitionandSelectStatements Dr.StuartKerrigan

SQLisatransformorientedlanguage SQLisanonprocedurallanguage:specifywhatinfoyourequirerather thanhowyouaccessthedata SQLisaverylargeandpowerfullanguage,buteverytypeofSQL statementfallswithinoneofthreemaincategories(orsublanguages): g g ( (DDL) )forcreating gaDB, ,defining g&controlling g DataDefinitionLanguage accesstodata e.g.CREATE,DROP,ALTER DataManipulationLanguage (DML)toaccessaDBbyretrievingand updatingdata e.g.SELECT,INSERT,UPDATE,DELETE DataControlLanguage (DCL)foradministeringaDB e.g.GRANT,DENY,USE

CO7101: Java & Databases For Bionformatics

147

148

SQL StructuredQueryLanguage
SQLwasdevelopedatIBMaround1975... Structuredprogramming? No! StructuredEnglishQueryLanguage(from 'SEQUEL')whichimplementsrelationalalgebra SQLisadeclarativelanguage sayswhatnothow SQLisanabstract&portableinterfacetoRDBMS DifferentversionsofSQLslightlydifferentsyntax WeusemySQL Onlystandarddblanguagetogainwide acceptance
149

SQLSyntax
SQLusesreservedkeywords&userdefinednames
CREATE TABLE Staff ( StaffNo INTEGER, Salary FLOAT, Lname VARCHAR(20) );

Thismeanscreateatablecalledstaffwiththefollowing fields:
StaffNoasanInteger SalaryasaFlat Lnameasatextfieldwith20characters INSERT INTO Staff VALUES (32, 25000.0, 'Smith');

Thismeansinsertintoourstafftablearowwiththe followingfields:
StaffNoof32 Salaryof25000.0 Lastnameof'Smith'
150

25

SQLSyntax
SQLusesreservedkeywords&userdefinednames
CREATE TABLE Staff ( StaffNo INTEGER, Salary FLOAT, Lname VARCHAR(20) ); INSERT INTO Staff VALUES (32, 25000.0, 'Smith');

RelationalTablesCanAnswer ManyQueries
Student Enrolment Course

Byconvention,keywordsareuppercase,thoughmostSQL dialectsarecaseinsensitive; Userdefinednamesmustbeenteredexactlyasintables Textdata d is i enclosed l dusing i single i l quotes('') Roundbrackets() areusedtogrouprelateditems Commas, separateitemsinalist Statementsareterminatedwithasemicolon(';') |indicateschoice;literals:nonnumericrequiresinglequotes, e.g.,VALUES('Bob',4);[]indicatesoptionality

Howmanycoursesarethere&whataretheir names? WhichstudentsareenrolledforJava? Howmanystudentstake3ormorecourses?


152

151

DataDefinitionLanguage(1)
TheSQLsyntaxforCREATETABLE is
CREATE TABLE table_name ( Column1name data_type_for_column_1, Column2name data_type_for_column_2, ... )
ColumnType yp int float boolean Description p Acceptsintegervaluesonly Acceptsfloatvaluesonly AcceptsaTRUEorFALSEvalue Syntax y tinyint,int float boolean varchar(charlimit value),for example varchar(20)is stringoflength20 date
153

DataDefinitionLanguage
StaffNo Fname Lname Position Salary

Howwouldyoucreatethefollowingtable? Firstdecidewhattypeoffieldtouseforeachfield StaffNo thisisobviouslyaninteger Fname,Lname,Positionaretextfields Salary thiscouldbedebatable.Let's Let smakeitafloat.


CREATE TABLE Staff (StaffNo INTEGER, Fname VARCHAR(20), Lname VARCHAR(20), Position VARCHAR(20), Salary FLOAT);

mySQLdescriptionofthistableisasfollows:

varchar

Acceptsanysymbol,character,ornumber

date

Date(YYYYMMDD), e.g.20090223

154

DataDefinitionLanguage
Forgotthedomainsofyourtable? Usethecommand DESCRIBEtable_name e.g.DESCRIBEStaff;

BuiltinDataTypes(Domains)in MySQL
SQLsupportsmanydatatypes(vendorsoftenalso haveowndialects):
CHARACTER(CHAR),CHARACTERVARYING(VARCHAR) NUMERIC,DECIMAL(DEC),INTEGER(INT),SMALLINT FLOAT,REAL,DOUBLEPRECISION DATE,TIME,TIMESTAMP BOOLEAN,BIT BINARYLARGEOBJECT(BLOB),etc.

Sometypeshaveanassociatedsize.e.g.CHAR(5)

155

156

26

SQLusesreservedkeywords&userdefinednames CREATE TABLE Staff ( StaffNo INTEGER, Salary FLOAT, Lname VARCHAR(20)); Thismeanscreateatablecalledstaffwiththefollowing fields:
StaffNo asanInteger SalaryasaFlat Lname a e asatext e field e dwith20 0characters c a ac e s

SQLSyntax

SQLSyntax
Staff
StaffNo 222 322 261 260 555 444 Fname Head Mark Julie Julie Dogollan Trinity Lname Honcho Jones Walters Walters Body Wells Position CEO Manager Director Tax Shelter Cleaner Porter Salary 35000 20000 40000 20000 500 200

Nowwewanttoadddatatoourtable. INSERT INTO Staff VALUES (32, 25000.0, 'Smith'); Thismeansinsertintoourstafftablearowwiththe followingfields:
StaffNo of32 Salaryof25000.0 Lastnameof'Smith'
157

Howwouldyouinsertthevaluesintothetable?

INSERT INTO Staff VALUES (222,'Head','Honcho','CEO',35000); INSERT INTO Staff VALUES (322,'Mark','Jones','Manager',35000); INSERT INTO Staff VALUES (261,'Julie','Walters','Director',40000); INSERT INTO Staff VALUES (260,'Julie','Walters','Tax Shelter',20000); INSERT INTO Staff VALUES (555,'Dogollan','Body','Cleaner',500); INSERT INTO Staff VALUES (444,'Trinity','Wells','Porter',200);
158

SQLSyntax
Supposewedontknowalltheinformation? e.g.weknowapersonslastname,positionandsalarybutnot theirstaffnumberorfirstname? INSERT INTO Staff (Lname, Position, Salary) VALUES ('Peters','Cleaner',30); LeavestheunknownfieldsasNULL.Canputtheseinlater
StaffNo 222 322 261 260 555 444 NULL Fname Head Mark Julie Julie Dogollan Trinity Lname Honcho Jones Walters Walters Body Wells
Bionformatics

SimpleQueriesUsingSELECT
SELECT * FROM Staff;

Staff
StaffNo 222 322 261 260 555 444 Fname Head Mark Julie Julie Dogollan Trinity Lname Honcho Jones Walters Walters Body Wells Position CEO Manager Director Tax Shelter Cleaner Porter Salary 35000 20000 40000 20000 500 200

Position CEO Manager Director Cleaner Porter

Salary 35000 20000 40000 500 200 30


159

Tax Shelter 20000

Here,asterisk*actsasa'wildcard' thatmeansSELECTallthefieldsFROMthestafftable Outputsatable(soSELECTisaclosed operation)


160

NULLCO7101: Java Peters & Databases For Cleaner

SimpleQueriesUsingSELECT
TheSELECTstatementretrievesdataandformatsoutput SELECTisthemostfrequentlyusedSQLstatement Performsrelationalalgebra'sselection,projectionandjoin operationsinasinglestatement

SELECT
SELECTfieldslist FROMtablelist WHEREcondition; tableslist Alistoftablenamesyouwishtoselectfrom. fieldslistAlistoffieldsfromthetablesintableslist;canalso specify if distinct di i (no ( duplicates) d li )orall ll(*) condition filtersrowssubjecttosomecondition SELECT Fname FROM Staff; SELECT Fname, Lname FROM Staff WHERE Salary > 15000;
161 162

SELECT * FROM Staff;


InEnglishthismeansselectalltherowsfromthestafftable.

27

SelectingSpecificColumns
Specificcolumnscanbeoutputbygivingtheir names:
SELECT Fname FROM Staff;
Fname Head Mark Julie Julie Dogollan Trinity Lname Honcho Jones Walters Walters Body Wells

SelectingSpecificColumns
Specificcolumnscanbeoutputbygivingtheir names:
SELECT Lname, Position, Salary FROM Staff;
Position CEO Manager Director Tax Shelter Cleaner Porter Salary 35000 20000 40000 20000 500 200

InEnglishthismeans:
Selectthefirstnames(Fname)fieldforalltherowsFROM 163 thestafftable

NB.musthaveacomma(',')betweencolumnnames InEnglishthismeans:
Selectthelastnames(Lname),positions(Position)and 164 Salaries(Salary)fieldsofalltherowsfromthestafftable

SelectingSpecificColumns
UseWHEREtospecifyacondition:
SELECT Fname, Lname, Salary FROM Staff WHERE Salary > 15000;
Fname Head Mark Julie

SelectingDistinctRows
UseDISTINCTtogetonlyone occurrenceofvalues
SELECT DISTINCT Fname, Lname FROM Staff;
Lname Honcho Jones Walters Body Wells

Dogollan Trinity

InEnglishmeans:
Selectthefirstnames(Fname),positions(Position)and Salaries(Salary)foralltherowsFROMthestafftable WHEREthesalaryismorethan15000
165

InEnglishthismeans:
Selectuniqueoccurrencesofthefirstnames(Fname)and lastnames(Lname)FROMthestafftable(i.e.no2Julie Walters) Whataboutthisquery?Howmanyrowswouldweget? SELECT DISTINCT Fname, Salary FROM Staff; 166

SelectingSpecificRows&Columns
comparison operators:
< less than > greater than = equal to <= less than or equal to >= greater than or equal to != not equal to lesser than or greater than

SelectingSpecificRows&Columns
canalsotestforrange(BETWEEN,NOTBETWEEN),
SELECT Fname, Lname, Salary FROM Staff WHERE Salary BETWEEN 0 AND 10000;

setmembership(IN('Manager'),NOTIN), patternmatch
SELECT * from Staff WHERE Lname LIKE 'W%'; W% ; SELECT * from Staff WHERE Lname NOT LIKE 'W%';

alsouseAND,ORand NOT
167

whethernull(ISNULL,ISNOTNULL) Condition'Salary>20000'iscalledapredicate Foreachrow,ifpredicateistrue,rowisoutput

168

28

Computed/DerivedFields
Canalsocomputeourownfields MonthlySalaryisacomputedfield itisSalarydividedby12
SELECT Fname,Lname,Salary/12 as MonthlySalary FROM Staff;

Computed/DerivedFields

FullNameisacomputedfieldconcatenatingtwofields.
SELECT concat(Fname concat(Fname,' ',Lname) Lname) as FullName FROM Staff;

WhennewfieldsarecalculatedwecannamethemusingAS

169

170

Computed/DerivedFields

BuildingUpComplexPredicates
Predicatesevaluatetoeithertrueorfalse PredicatescanbecombinedusingAND,OR,andNOT Usebracketstoavoidambiguity Thenexttwostatementsaredifferent:

1.SELECT * FROM Staff WHERE (Position = 'Manager') Manager ) OR (Position = 'Assistant' AND Salary > 10000); 2.SELECT * FROM Staff WHERE(Position = 'Manager' OR Position = 'Assistant) AND NOT (Salary <= 10000);

171

Ineachcase,wholeWHEREclauseistrueorfalse NULLisnotequivalentto''or<>,can'ttestequality;useIS
172

OtherTypesofPredicate
OtherpredicatesincludeBETWEEN,IN,andLIKE Buttheystillevaluatetoeithertrueorfalse
SELECT * FROM Staff WHERE (Salary BETWEEN 10000 AND 40000) AND (Position IN ('CEO','Director','Cleaner')) AND (Fname LIKE 'H_ _ _' OR Lname LIKE 'W%');

Answer
SELECT * FROM Staff WHERE (Salary BETWEEN 10000 AND 40000) AND (Position IN ('CEO','Director','Cleaner')) AND (Fname LIKE 'H_ _ _' OR Lname LIKE 'W%');

'_'matchesexactlyonecharacter '%'matcheszeroormorecharacters
Sowhatdoesthisquerymatch?
SELECTallthefieldsFROMthestafftableWHERE thesalaryisbetween10000and40000and thepositioniseitherCEO,DirectororCleanerand thefirstnamebeginswithHandhas3charactersfollowingitorthe lastnamebeginswithW. 174

173

29

Conclusion
SQListhestandardquerylanguageforRDBMS ThreemaincategoriesofSQL
DDL,DataDefinitionLanguage DML,DataManipulationLanguage DCL, DCL DataControlLanguage

CO7101:Java&DatabasesFor Bioinformatics
SQL2: More on SELECT then UPDATE, DELETE Dr.StuartKerrigan

CREATE,ALTERandDROPtablesusingDDL. SELECTbelongstoDML SELECTretrieves&displaysdatafromthe database WecontinuetoexploreDML


CO7101: Java & Databases For Bionformatics 175

CO7101: Java & Databases For Bionformatics

176

PreviouslyonCO1019:
CanCREATEtablesinamySQLdatabase CanINSERTINTOtablesinamySQLdatabase CanuseSELECTto
Retrievedatafromalltherowsandcolumns(wholetable) SELECT * FROM Staff; Retrievedatafromalltherowsandselectcolumns SELECT Fname, Lname FROM Staff; Retrievedatafromselectrowsandcolumns SELECT Fname, Lname FROM Staff WHERE Salary > 10000; Computederivedfieldvalues SELECT Salary/12 as monthySal FROM Staff;
CO7101: Java & Databases For Bioinformatics

Inthislectureyouwilllearn
Calculateaggregatederiveddata GROUPBYandORDERBYinSELECT statements Modifyrowdata Deleterowdata Deleteentiretables NULLvaluesindatabases Howtocombinequeryresultsusingset unions
CO7101: Java & Databases For Bioinformatics 178

177

SQLAggregateFunctions
Wedonotwanttojustretrievedata Wealsowanttosummarisedata UseinSELECTlistandHAVINGclauseonly Aggregatefunctionscomputesummarization(or aggregation)ofdata&returnavalue DISTINCTeliminatesduplicatesfirst Aggregatefunctionsoveracolumn

SUM,MIN,MAX,AVG
Findtheminimum,maximum,average andsumofstaffsalary
SELECT MIN(salary) AS minSalary, MAX(salary) AS maxSalary, AVG(salary) AS avgSalary, SUM(salary) AS sumSalary, CO COUNT(salary) ( l ) AS S countSalary S l FROM Staff;

SUM sumscolumnvalues(numericfieldsonly) AVG averagescolumnvalues(numericfieldsonly) MIN givesmincolumnvalue MAX givesmaxcolumnvalue COUNT givesnumberofvaluesincolumn
CO7101: Java & Databases For Bioinformatics 179 180

CO7101: Java & Databases For Bioinformatics

30

GROUPBY
Aggregatefunctionshelpustosummarisethewhole column(s)ofdataintoonerow. Sometimeswewanttogroupdatabeforeapplying aggregatefunctions
Thisgivesus'subtotals'ratherthan'overalltotal'

GROUPBY Example
Findthetotalsalariesofeachpersononpayrollbyaddingsalaries fromdifferentjobs.Groupbytheirfirstname. SELECT Fname, Lname, SUM(Salary) AS TotalSalary FROM Staff GROUP BY Fname, Lname;

GROUPBYisusedtoachievethat CloselytiedtoSELECT;canonlyhavecolumnnames, aggregatefunctions,constants,acombinationofthese AllcolumnsinSELECTlistmustappearinGROUPBY clauseunlessthey'reinanaggregatefunction WHEREconditionappliedbeforeGROUPBY


CO7101: Java & Databases For Bioinformatics 181 CO7101: Java & Databases For Bioinformatics 182

HAVING
UsewithGROUPBYtorestrictoutput;filtersgroupsrather thanrows(WHERE);conditionhasaggregatefn
SELECT branchNo, Count(staffNo) AS myCount, SUM(salary) AS mySum FROM MoreStaff GROUP BY branchNo HAVING COUNT(staffNo)>1;
StaffNo SA9 SG14 SG37 SG5 SL21 SL41 Fname Mary David Ann Susan John Julie Lname Howe Ford Beech Brand White Lee

SELECT GroupBy
SELECTfieldslist FROMtablelist WHEREcondition; GROUPBYcolumnList[HAVINGcondition] ORDERBYcolumnList GROUPBYfiltersgroupsofrows Workoutaggregatefunctionsforeachgroupingrouped columns

MoreSta ffPosition
Assistant Supervisor Assistant Manager Manager Assistant

Sex F M F F M F

DOB 19Feb70 24Mar58 11Oct60 03Jun40 01Oct45 13Jun65

Salary

BranchNo

9000 B007 18000 B003 12000 B003 24000 B003 30000 B005 90000 B005

Query
branchNo B003 B005 myCount 3 2 mySum 54000 120000
CO7101: Java & Databases For Bionformatics 184

SELECT OrderBy
SELECTfieldslist FROMtablelist WHEREcondition; GROUPBYcolumnList [HAVINGcondition] ORDERBYcolumnList ORDERBYsortsresults canbeASCending orDESCending SELECT * FROM Staff A Z ORDER BY salary DESC; SELECT * FROM Staff ORDER BY Fname ASC; SELECT * FROM Staff Z A ORDER BY Lname ASC, Fname ASC, Position DESC;

UPDATEQueries
UPDATEtablelist SETfield1=value1 field2=value2 WHEREcondition;(WHEREisoptional)
UPDATE Staff SET Fname ='Dilbert'; S all Sets llFirst Fi Names N to'Dilbert' 'Dilb 'in i the h Staff S fftable. bl UPDATE Staff SET Position='Chief Executive Officer' WHERE Position = 'CEO'; SetsPositionsof'CEO'to'ChiefExecutiveOfficer'intheStafftable. UPDATE Staff SET Salary = 10000 WHERE Salary < 10000; SetsSalaryto10000whereSalaryislessthan10000intheStafftable.
185 CO7101: Java & Databases For Bionformatics 186

CO7101: Java & Databases For Bionformatics

31

UPDATEQueries
Changingspecificvaluesinatable:
UPDATE Staff SET Salary = 1.05*Salary WHERE Position = 'Director';

DELETEQueries
DELETEFROMtablelist WHEREcondition;

UPDATEtheSTAFFtablebymultiplyingthesalaryby 1.05wherethePositionisDirector

Deletingallrowsofatable:
DELETE FROM Staff;

Deletingspecificrowsofatable:
DELETE FROM Staff WHERE Fname = 'Julie' AND Lname = 'Walters';

CompletelyremovingatableisaDDL(data definitionlanguage)operation:
DROP TABLE Staff;
CO7101: Java & Databases For Bioinformatics 187 CO7101: Java & Databases For Bioinformatics 188

WhyDoDBSystemsAllowNULLs?
ANULLvaluecanbeusedtorepresentseveralsituations: Don'tcare;Don'tknow;Don'tknowyet;Usedtoknow! SQLhasspecialrulesandlogictohandleNULLs:
SELECT*FROMStaffWHEREFnameISNULL;

ANullExample
Staff_With_Room s Lname Position
Honcho Jones Walters Walters Body Wells CEO Manager Director Tax Shelter Cleaner Porter

StaffNo 222 322 261 260 555 444

Fname Head Mark Julie Julie

Salary 35000 20000 40000 20000 500 200

Room F5 F30 F1 NULL NULL Cellar

NB.WHEREColname='NULL' NULL doesnotwork!Can't Can ttest equalityonsomethingthatdoesn'texist!ISisnotthesameas = Canalsosay:WHEREColnameISNOTNULL NULLscanbeuseful,difficult,ordangerous UseNULLswisely!

Dogollan Trinity

CO7101: Java & Databases For Bioinformatics

189

CombiningResultsTables
Requirements:tablesneedtohavesamestructuresothey'reunion compatible Sometimesitsusefultobeabletocombinequeryresultsusingset operations:

SetOperationsinSQL
Syntax: (SELECT ...) UNION (SELECT ...); Forsetoperations,thetablesmustbeunioncompatible i.e.havethesamenumberandtypesofcolumns (SELECT city FROM Branch WHERE city IS NOT NULL) UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL);

RUS R S (a) Union S R

RS

R-S

R S (b) Intersection (c) Difference (Excep

CO7101: Java & Databases For Bioinformatics

191

CO7101: Java & Databases For Bioinformatics

192

32

Rememberthisdata?
Staff
StaffNo 222 322 261 260 555 444 Fname Head Mark Julie Julie Dogollan Trinity Lname Honcho Jones Walters Walters Body Wells Position CEO Manager Director Tax Shelter Cleaner Porter Salary 35000 20000 40000 20000 500 200

UnionCompatible?
Staff2
StaffNo 523 211 260 Fname Redwood Bilbo Julie Lname Mark Baggins Walters Position CEO Hobbit Tax Shelter Salary 20000 12000 20000

CREATE TABLE Staff2 (StaffNo INTEGER, Fname VARCHAR(20), Lname VARCHAR(20), Position VARCHAR(20), Salary FLOAT); INSERT INTO Staff2 VALUES (222,'Redwood','Mark','CEO',20000), (322,'Bilbo','Baggins','Hobbit',12000), (260,'Julie','Walters','Tax Shelter',20000); (SELECT * FROM Staff) UNION (SELECT * FROM Staff2);

ResultsofourUnion
StaffNo 222 322 261 260 555 444 523 211 Fname Head Mark Julie Julie Dogollan Trinity Redwood Bilbo Lname Honcho Jones Walters Walters Body Wells Mark Baggins Position CEO Manager Director Tax Shelter Cleaner Porter CEO Hobbit Salary 35000 20000 40000 20000 500 200 20000 12000

ResultsofourUnion

UnionCompatible?
Staff3
StaffNo 123 212 260

UnionCompatible?
Staff3
Branch ENG1 SCO1 FRA1 StaffNo 123 212 260 Fname Gilbert Lenny Julie Lname Laycock Henry Walters Position Engineer Morale Officer Tax Shelter Salary 35000 20000 20000 Branch ENG1 SCO1 FRA1

Fname Gilbert Lenny Julie

Lname Laycock Henry Walters

Position Engineer Morale Officer Tax Shelter

Salary 35000 20000 20000

CREATE TABLE Staff3 (StaffNo INTEGER, Fname VARCHAR(20), Lname VARCHAR(20), Position VARCHAR(20), Salary FLOAT, BRANCH VARCHAR(20)); INSERT INTO Staff3 VALUES (123,'Gilbert','Laycock','Engineer',20000, 'ENG1'), (322,'Lenny','Henry','Morale',20000), (260,'Julie','Walters','Tax Shelter',20000); (SELECT * FROM Staff) UNION (SELECT * FROM Staff3);

(SELECT * FROM Staff) UNION (SELECT * FROM Staff3); Won'twork why? (SELECT * FROM Staff) UNION (SELECT StaffNo, Fname, Lname, Position, Salary FROM Staff3);

33

UnionExample
RUS R S (a) ( ) Union S R S (b) ( ) Intersection (c) ( ) Difference (Exce ( R R S

IntersectandExcept
RUS R S (a) ( )Union S (b) ( )Intersection (c) ( )Difference( (Exce R

Coveredunions,butwhatabout IntersectionsandDifferences?

Coveredunions,butwhataboutIntersectionsandDifferences. SQLkeywordsareINTERSECT andEXCEPT e.g. (SELECT * FROM Staff) INTERSECT (SELECT * FROM Staff2); (SELECT * FROM Staff) EXCEPT(SELECT * FROM Staff2); SadlynotsupportedinMySQL.Thereareworkaroundsonthe internet(useGoogle) buttheseusesubqueries!

IntersectExample
SELECT DISTINCT * FROM Staff WHERE EXISTS (SELECT * FROM Staff2 WHERE Staff.StaffNo = Staff2.StaffNo AND Staff.Fname = Staff2.Fname AND Staff.Lname = Staff2.Lname AND Staff.Position = Staff2.Position AND Staff Salary = Staff2 Staff.Salary Staff2.Salary); Salary); SELECT DISTINCT * FROM Staff WHERE NOT EXISTS (SELECT * FROM Staff2 WHERE Staff.StaffNo = Staff2.StaffNo AND Staff.Fname = Staff2.Fname AND Staff.Lname = Staff2.Lname AND Staff.Position = Staff2.Position AND Staff.Salary = Staff2.Salary); Moreon(simpler?)subqueries nexttime!

Conclusion
NowunderstandcompleteSELECTsyntax Canuseaggregatefunctions UPDATEandDELETEqueries UnderstandwhentouseNULLsindatabase design. CannowperformsimpleUNIONSbetween tables

CO7101: Java & Databases For Bionformatics

202

PreviouslyonCO1019:
CO7101:Java&DatabasesFor Bioinformatics
SQL3: Subqueries and Multiple Tables Dr.StuartKerrigan
CREATEtables,INSERTdataintotableandSELECTdataoutof table UseAggregatefunctions UPDATEdataandDELETEdatafromtable
ALLONONETABLEONLY!

CreateaUnionbetweentwoidenticalqueriesofdifferent tables

CO7101: Java & Databases For Bionformatics

203

CO7101: Java & Databases For Bioinformatics

204

34

UsingSubqueries NestedSELECTs
StaffNo 222 322 261 260 555 444 401 322 Fname Head Mark Julie Julie Dogollan Trinity Taffy Gareth Lname Honcho Jones Walters Walters Body Wells Truman Whirlwind Position CEO Manager Director Tax Shelter Cleaner Porter Manager Manager Salary 35000 20000 40000 20000 500 200 30000 32500

IfweknowthataSELECTstatementwillproduceasinglevalueor rowwecanusethisvaluedirectlyinasimplepredicate. Thissubquerymustappearinbrackets(); ORDERBYcan'tappearinasubquery; mostsubqueriescan'thavemorethan1tableinSELECTlist Canappearafterarelationaloperator,functionorsetoperatorin WHERE SELECT&HAVINGclauses WHERE, Example:findallmembersofstaffwhoearnmorethanthe managers: SELECT * FROM Staff WHERE Salary > (SELECT Salary FROM Staff WHERE Position ='Manager'); Doesn'tworkwhenweintroducemultiplemanagers!

CO7101: Java & Databases For Bioinformatics

206

SubqueriesThatGiveaListofValues
IftheSELECTstatementisexpectedtoproducealistofvalues, wecanusetheIN,ANY,ALLorEXISTSkeywordstooperateon thelist. Example:findthosemembersofstaffwhoarenotmanagers butearnmorethanany managers:
SELECT * FROM Staff WHERE Position <> 'Manager' g AND Salary > ANY (SELECT Salary FROM Staff WHERE Position = 'Manager'); ANY:PredicateistrueifitmatchesANYvalueinthelist e.g.statementistrueifstaffisnotamanagerandhasahighersalary thananymanager. SELECT * FROM Staff WHERE Position <> 'Manager' AND Salary > SOME (SELECT Salary FROM Staff WHERE Position ='Manager'); SOME:Synonymforany(i.e.youcanuseSOMEorANYinterchangably)
CO7101: Java & Databases For Bioinformatics 207

SubqueriesThatGiveaListofValues
SELECT * FROM Staff WHERE Position <> 'Manager' AND Salary > ALL (SELECT Salary FROM Staff WHERE Position ='Manager'); ANY:PredicateistrueifitmatchesALLvalueinthelist e.g.statementistrueifstaffisnotamanagerandhasa highersalarythanALLthemanagers. SELECT * FROM Staff WHERE position IN ('Manager', 'Supervisor'); IN:Predicateistrueifthetestelementisinthelist;(i.e.if positionisINthesetofvalueswesupply Manageror Supervisor)

CO7101: Java & Databases For Bioinformatics

208

SubqueriesThatGiveaListofValues
SELECT staffNo, fName, lName, position FROM Staff s WHERE EXISTS (SELECT * FROM Branch b WHERE s.branchNo=b.branchNo AND city='London'; EXISTS:Predicateistrueiflistisnonempty(i.e.itexists); p itistrueifonly yforusewith sointheaboveexample subqueries.

QueryingMultipleTables
How do we list all the properties that a given client has viewed? PropertyForR Could start with an example - e.g. client CR56 ... ent
PropertyNo PA14 PG16 PG21 PG36 PG4 Street City Postcode AB7 5SU G12 9AX G12 G32 4QX G11 9QX Type Rooms Rent OwnerNo StaffNo 16 Holhead 5 Novar Dr 18 Dale Rd 2 Manor Rd 6 Lawrence St Aberdeen Glasgow Glasgow Glasgow Glasgow House Flat House Flat Flat 6 4 5 3 3 650 450 600 375 350 CO46 CO93 CO87 CO93 CO40 SA9 SG14 SG37 SG37 B007 B003 B003 B003 B003

BranchNo

PL94

6 Argyll St

London

NW2

Flat

400

CO87

SL41

B005

Client
ClientNo CR56 CR62 CR74 CR76 Fname Aline Mary Mike John Lname Stewart Tregear Ritchie Kay TelNo 0141-848-1825 01224-196720 01475-392178 0207-774-5632 PrefType Flat Flat House Flat MaxRent 350 600 750 425

Viewing
ClientNo CR56 CR56 PropertyNo PA14 PG36 ViewDate 24-May-01 28-Apr-01 Comment too small

CR56

PG4

26-May-01

CR62 CR76

PA14 PG4

14-May-01 20-Apr-01

no dining room too remote

CO7101: Java & Databases For Bioinformatics

209

CO7101: Java & Databases For Bioinformatics

210

35

PropertyQuery FirstAttempt
Firstattempt:Listthepropertynumbersviewedbyclient number'CR56':
SELECTPropertyNo FROMViewing WHEREClientNo='CR56';

PropertyQuery SecondVersion
SELECT DISTINCT Viewing.PropertyNo, Street, City, ViewDate FROM Viewing, PropertyForRent WHERE ClientNo = 'CR56' AND Viewing.PropertyNo = PropertyForRent.PropertyNo;
cols)

Butwe'dliketoseetheclientname&propertydetails Sowe'llneedtoaccessClientandPropertyForRentfor namesetc etc... Toobtaininfofrom>1table:subqueriesorjoins;forresult tabletocontaincolumnsfrom>1table:join.


Recallsubqueries:SELECT*FROMStaffWHEREbranchNo= (SELECTbranchNoFROMBranchWHEREstreet= '163MainSt');

(matching

WenowhavetwotablenamesintheFROMclause NoteuseofTable.ColumnName"toavoidambiguityin columnnames(i.e.bothViewingandPropertyForRent haveaPropertyNo column)


CO7101: Java & Databases For Bioinformatics 212

CO7101: Java & Databases For Bioinformatics

211

PropertyQuery ThirdVersion
SELECT DISTINCT Fname, Lname, Street, City, ViewDate FROM Viewing, PropertyForRent, Client WHERE Viewing.ClientNo = 'CR56' AND Viewing.PropertyNo = PropertyForRent.PropertyNo AND Viewing.ClientNo = Client.ClientNo;

PropertyQuery FourthVersion
Usersshouldn'thavetoknowaboutinternalkeys...
SELECT DISTINCT Fname, Lname, Street, City, ViewDate FROM Viewing, PropertyForRent, Client WHERE Fname = 'Aline' AND Lname = 'Stewart' AND Viewing.PropertyNo = PropertyForRent.PropertyNo; AND Viewing.ClientNo = Client.ClientNo;

ThetwoAND"clausesarecalledjoincriteria
Noteforlater:primarykey=parent&foreignkey=child:thisis parent/childrelationship,oronetomany(1:*),e.g. PropertyForRent/Viewing;moreinfoonrelationalalgebracanbe foundin!!.

CO7101: Java & Databases For Bioinformatics

213

CO7101: Java & Databases For Bioinformatics

214

UsingTableAliases
Tablealiasescanhelpreduceamountoftyping Thefollowingisidenticaltothepreviousquery:
SELECT C.Fname, C.Lname, P.Street, P.City, V.ViewDate FROM Viewing V, PropertyForRent P, Client C WHERE C.Fname = 'Aline' AND C.Lname = 'Stewart' AND V.PropertyNo = P.PropertyNo AND V.ClientNo = C.ClientNo;

SimpleJoins
SELECTc.clientNo,fName,lName,propertyNo FROMClientc,Viewingv WHEREc.clientNo=v.clientNo;implicitjoin SELECTc.clientNo,fName,lName,propertyNo FROMClientc JOINViewingvONc.clientNo=v.clientNo;>2clientNocols SELECTc.clientNo,fName,lName,propertyNo gUSINGclientNo; ;explicit p j join FROMClientJOINViewing SELECTc.clientNo,fName,lName,propertyNo FROMClientNATURALJOINViewing;(onlyjoinsmatchedrows) 3tablequery: SELECTc.clientNo,c.fName,c.lName,p.propertyNo FROMClientc,Viewingv,PropertyForRentp WHEREc.clientNo=v.clientNoANDv.propertyNo=p.propertyNo; ORDERBYstillworks,justspecifytable.colName Specifytable.colNowhencolNoappearsin>1table;canalsodothistobeclearer
CO7101: Java & Databases For Bioinformatics 216

Tablealiaseshelpreducetheriskoftypingmistakes Butshouldn'ttheDBMSknowhowtomatchkeysfor us?Onlyiftheyappearin1table

CO7101: Java & Databases For Bioinformatics

215

36

CrossJoins(CartesianProducts)
CartesianProduct:ajoinwithnoWHEREclause, selectseverythingfrombothtables(most generaljoin) SELECT*FROM Left,Right; mySQLallows: SELECT*FROM LeftCROSSJOINRight; Usefulfor: queryoptimisation datamining Innerjoinsaretypeofcrossjoin
Innerjoin(atypeofcrossjoin)onlyreturnsrowswhich meetspecifiedcriteria, canbeequijoins(atypeoftheta joinwhichusesonly=),ornaturaljoins(atypeof equijoinwhichselectsrowsw/commonvalues); Outer joinreturnsmatching &unmatching rows

NaturalJoins
NaturaljoinsimplementrelationshipsintheRelationalmodel Theyareatypeofequijoinwhichselectsrowswithcommonvalues betweentables TheDBMSwillknowwhichcolumnsarekeycolumns Thefollowingqueriesareequivalent:
SELECT C.Fname, C.Lname, P.Street, P.City, V.ViewDate FROM Client C NATURAL JOIN (Viewing V NATURAL JOIN PropertyForRent P) WHERE C.Fname = 'Aline' AND C.Lname = 'Stewart'; and SELECT C.Fname, C.Lname, P.Street, P.City, V.ViewDate FROM Viewing V, PropertyForRent P, Client C WHERE C.Fname = 'Aline' AND C.Lname = 'Stewart' AND V.PropertyNo = P.PropertyNo AND V.ClientNo = C.ClientNo;

MostDBMSssupport4tablejoins,ormore...
CO7101: Java & Databases For Bioinformatics

CO7101: Java & Databases For Bioinformatics

217

218

mySQLSyntaxforJoins
mySQLallowsjoinstobewrittenindifferentways: Naturaljoins:
SELECT * FROM Left NATURAL JOIN Right; SELECT * FROM Left JOIN Right USING ColNam;

ThetaJoins
Thetajoin"isatypeofinnerjoin(onlyreturnsrowswhich meetspecifiedcriteria)whichhaveamoregeneralWHERE predicatethanequijoins(whichonlymatchonequality):
SELECT L.*, R.*, ... FROM Left L, Right R WHERE L.LeftCol R.Rightcol;

Ifnotjoiningonkeys,givejoinconditionexplicitly:
SELECT*FROMLeftJOINRight ONLeft.ColNam=Right.ColNam;

Youcandoimplicitjoins Whichisbest? Makeupyourownmind,butbeawarewith howtheyrelatetoeachother

maybeoneof=;!=;<>;<;>;<=;>= If is=,itsanequijoin If is=andmatchesonkeycolumnsitsanaturaljoin Ifalloutputcolumnsarefromonetable,itsasemijoin (equivalenttoasubquery)

CO7101: Java & Databases For Bioinformatics

219

CO7101: Java & Databases For Bioinformatics

220

ExampleofaThetaJoin
Forallclients,listthepropertiesthateachclientcan affordtorent:
SELECTC.ClientNo,P.PropertyNo FROMClientC,PropertyForRentP WHEREC.MaxRent C MaxRent>=P P.rent; rent;

SelfJoins
Sometimesitisusefultojoinatabletoitself(must usealiases)
ALTERTABLEStaffADDCOLUMNBossNoCHAR(5); SELECTS.LnameASPerson,B.LnameasBoss ,StaffB FROMStaffS, WHERES.BossNo=B.StaffNo;

TheDBMScouldimplementthetajoinsby:

Firstformingacrossjointogive... Anintermediate(Cartesianproduct)table.. ThenapplyingWHEREclausetofindmatchingrows Noticethattherelationis>=not=
221

CO7101: Java & Databases For Bioinformatics

CO7101: Java & Databases For Bioinformatics

222

37

OuterJoins (Selectingunmatchedrows)
Innerjoin(atypeofcrossjoin)onlyreturnsrowswhichmeetspecified criteria,canbeequijoins(atypeofthetajoinwhichusesonly=),or naturaljoins(atypeofequijoinwhichselectsrowsw/commonvalues); Outerjoinreturnsmatching&unmatchingrows Example:Listthebranchofficesandpropertiesinthesamecity,along withanyunmatchedbranches:
SELECTB.BrNo,P.PropNo FROMPropForRent PRIGHTJOINBranchB ONB.City=P.City;

RightOuterJoins&FullOuterJoins
Inasimilarmanner,canuseRIGHTJOINandFULL JOIN(meaningfullouterjoin):
SELECTB.BrNo,P.PropNo FROMBranchBFULLJOINPropertyForRentP ONB.City B Cit =P.City; P Cit

NB.NotallDBMSs(e.g.MicrosoftAccess)supportouterjoins

CO7101: Java & Databases For Bioinformatics

223

CO7101: Java & Databases For Bioinformatics

224

TypesofJoin

Thetajoin innerjoinusingasimpleWHEREpredicate Equijoin aspecialcaseofthetajoin(=predicate) Naturaljoin specialcaseofequijoin(matchkeys) Semijoin thetajointhatoutputsfromjustonetable Selfjoin joiningatabletoitself Outerjoin mayincludeunmatchedrows;left/right/full Innerjoin ajointhatonlyincludesmatchedrows Crossjoin Cartesianproducts(nopredicates);mostgeneral

TypesofJoin
Explicitjoin usesthekeywordJOIN, ImplicitjoindoesnotusethekeywordJOIN
specifiesacrossjoin WHEREclausemayapplyadditionalfilterpredicates filterpredicatesfunctioncomparablytojoinpredicatesinthe explicitnotation. notation

Whydoweneedtodistinguishsomanydifferenttypesof join? Querieswithdifferentjoinsareoftenoptimised differently... Lotsofonlineresources,e.g., http://www.w3schools.com/sql/,www.wikipedia.org, etc.TheWebisyourfriend.


CO7101: Java & Databases For Bioinformatics 226

CO7101: Java & Databases For Bioinformatics

225

PreviouslyonCO1019
CO7101:Java&DatabasesFor Bioinformatics
SQL4: ImplementingRelationshipsUsingKeys&UsingNatural Joins Dr.StuartKerrigan

Queriesinvolvingmultipletables Differenttypesofjoin
NaturalJoinuseskeysspecifiedintable

Relationships
1*relationships 11relationships **relationships

CO7101: Java & Databases For Bionformatics

227

CO7101: Java & Databases For Bionformatics

228

38

Inthislectureyouwilllearn
SQLdatatypes&relatedscalarfunctions Howtodeclare primarykeys foreignkeys unique i i indexed d dcolumns l AndhowtoensureMySQLmaintainstheintegrity constraints Howintegrityconstraintscanaffectrowoperations

SQL'sIntegrityEnhancement Features(IEF)
Realdatabasesareoftenveryactivewith100sof userssimultaneouslyqueryingandupdatingtheDB. Sodatabaseintegrityisimportant IEFsallowtheDBdesignertospecify&enforce:

domainconstraints requireddata entityintegrity referentialintegrity enterpriseconstraints(businessrules)

229

230

CreatingTables DataDefinition
CREATETABLEisusedtodefinerelationaltables Definesthedatatypeforeachcolumn Alsodefinesrulesforhowdataisinsertedanddeleted
CREATE TABLE Staff (StaffNo VARCHAR(5), Lname VARCHAR(20), Salary FLOAT, HireDate DATE);

BuiltinDataTypes(Domains)inMySQL
SQLsupportsmanydatatypes(vendorsoftenalso haveowndialects):

CHARACTER(CHAR),CHARACTERVARYING(VARCHAR) NUMERIC,DECIMAL(DEC),INTEGER(INT),SMALLINT FLOAT,REAL,DOUBLEPRECISION DATE,TIME,TIMESTAMP BOOLEAN,BIT BINARYLARGEOBJECT(BLOB),etc.

VARCHAR,FLOAT,andDATEareexamplesofdomains Alsosomerulesareimpliedhere
StaffNoisupto5characterslong, Lnameis20characterslong

Sometypeshaveanassociatedsize.e.g.CHAR(5)

Domainsspecifytype&rangeofalloweddatavalues
231 232

RequiredData &MoreDomainConstraints
NOTNULLmeansrowcannotcontainnulls Example: CREATE TABLE Staff ( StaffNo VARCHAR(5) NOT NULL, Lname VARCHAR(20) NOT NULL, Salary FLOAT CHECK (Salary BETWEEN 50 and 20000), HireDate DATE); StaffNo&Lnamearerequired maynotbeNULL DomainConstraints:specifieswhatsokincol/table CHECKgivesadomainconstraintforSalary Updates&insertionswillfailifconstraintsnotsatisfied

ScalarFunctions
Scalarfunctionsmaybeusedtoconvert/manipulatedata values(rememberaggregates:MIN,MAX,etc.) Example:
SELECTSUBSTRING(Lname,1,3), CONVERT(INTEGER Salary), EXTRACT(YEARFROMHireDate) FROMStaff;

Result SMI 12075 1990

MySQLsupportsmanyscalarfunctions

234

39

EntityIntegrity PrimaryKeys
Reminder:theprimarykeyofeachrowinatablemust beuniqueandnonnull. Example:TheprimarykeyoftheViewingtableis composedoftwoattributes(compositekey): CREATE TABLE Viewing ( ClientNo VARCHAR(5) NOT NULL, PropertyNo VARCHAR(5) NOT NULL, PRIMARY KEY (ClientNo, PropertyNo)) ENGINE=INNODB; Theprimarykeyofthistableisacompositekey SQLwillrejectoperationsthatwouldviolateprimarykey uniqueness
235

EntityIntegrity PrimaryKeys
PrimarykeyoftheGuesttableinahoteldatabaseis oneattribute: CREATE TABLE Guest (GuestNumber INT NOT NULL, FirstName VARCHAR(15), LastName VARCHAR(15), PRIMARY KEY (GuestNumber)) ENGINE=INNODB; ENGINE=INNODBrequiredtohandleallkeys. Whataboutforeignkeys? Whataboutuniqueforeignkeysfor11relationships

236

ReferentialIntegrity ForeignKeys
Foreignkeylinksachildtabletoparenttable.If nonnull,shouldmatcharowofparenttable. SQLhaskeywordsforthis:
CREATE TABLE Room( RoomName VARCHAR(20) NOT NULL, , GuestNumber INT NOT NULL, FOREIGN KEY (GuestNumber) REFERENCES Guest(GuestNumber), PRIMARY KEY (RoomName)) ENGINE=INNODB;

PopulateTables
Guest
Guest Number
(Primary Key)

FirstName

Last Name Hope Gall Example Running

1 2 3 4

Bob Tim Anne Gilmore

SQLwillrejectoperationsthatwouldviolate referentialintegrity
237

INSERT INTO Guest VALUES (1,'Bob','Hope'), (2,'Tom', 'Gall'), (3,'Anne','Example'), (4,'Gilmore','Running');


CO7101: Java & Databases For Bionformatics 238

PopulateTables
Room NameRoom
(Primary Key)

Guest Number
(ForeignKey)

Guest FirstName Guest Number


(Primary Key)

Last Name Hope Gall Example Running

UsingaNaturalJoin
SELECT RoomName, FirstName, LastName FROM Guest NATURAL JOIN Room;

OakleyRoom Samhayne Room Wood Room StoatRoom EagleRoom

1 1 2 3 4

1 2 3 4

Bob Tim Anne Gilmore

INSERT INTO Guest VALUES (1,'Bob','Hope'), (2,'Tom', 'Gall'), (3,'Anne','Example'), (4,'Gilmore','Running'); INSERT INTO Room VALUES ('Oakley Room',1), ('Samhayne Room',1),('Wood Room',2),('Stoat CO7101: Java & Databases For 239 Room',3), ('Eagle Room',4); Bionformatics

Room

0..* 1..1

Guest
240

CO7101: Java & Databases For Bionformatics

40

UNIQUEValues
UNIQUE(cols ) Example:
CREATE TABLE Room( RoomName VARCHAR(20) NOT NULL, GuestNumber INT NOT NULL, UNIQUE (GuestNumber), FOREIGN KEY (G (GuestNumber) tN b ) REFERENCES G Guest t (GuestNumber), PRIMARY KEY (RoomName)) ENGINE=INNODB; Room
Room Name
(Primary Key)

RepopulateTables
Guest
Guest Number
(ForeignKey)

Guest Number
(Primary Key)

FirstName

Last Name Hope Gall Example Running

OakleyRoom Samhayne Room Wood Room StoatRoom EagleRoom

1 1 2 3 4

1 2 3 4

Bob Tim Anne Gilmore

1guestmustoccupy1room sono WhathappensifweremoveNOTNULLon GuestNumber?

GuestNumber mustbeunique thislinewouldviolate integrity


241 CO7101: Java & Databases For Bionformatics 242

RepopulateTables
Room
Room Name
(Primary Key)

Relationships
Last Name Hope Gall Example Running

Guest
Guest Number
(ForeignKey)

Guest Number
(Primary Key)

FirstName

SELECT RoomName, FirstName, LastName FROM Guest NATURAL JOIN Room;

OakleyRoom Wood Room StoatRoom EagleRoom

1 2 3 4

1 2 3 4

Bob Tim Anne Gilmore

INSERT INTO Guest VALUES (1,'Bob','Hope'), (2,'Tom','Gall'), (3,'Anne','Example'), (4,'Gilmore','Running'); INSERT INTO Room VALUES ('Oakley CO7101: Java & Databases For Room',1), ('Wood Room',2), ('Stoat Bionformatics Room',3), ('Eagle Room',4); Room
243

0..1 1..1

Guest
244

CO7101: Java & Databases For Bionformatics

RelationshipswithoutNotNull
CREATE TABLE Room( RoomName VARCHAR(20) NOT NULL,GuestNumber INT, UNIQUE (GuestNumber), FOREIGN KEY (GuestNumber) REFERENCES Guest (GuestNumber), PRIMARY KEY (RoomName)) ENGINE=INNODB;

RepopulateTables
Room
Room Name
(Primary Key)

Guest
Guest Number
(ForeignKey)

Guest Number
(Primary Key)

FirstName

Last Name Hope Gall Example Running

OakleyRoom Wood Room StoatRoom EagleRoom HauntedRoom

1 2 3 4 NULL

1 2 3 4

Bob Tim Anne Gilmore

0..1 0...1 Room Guest

INSERT INTO Guest VALUES (1,'Bob','Hope'), (2,'Tom','Gall'), (3,'Anne','Example'), (4,'Gilmore','Running'); INSERT INTO Room VALUES ('Oakley Room',1), ('Wood Room',2), ('Stoat Room',3), ('Eagle Room',4) , ('Haunted Room,NULL);
CO7101: Java & Databases For Bionformatics 246 245

CO7101: Java & Databases For Bionformatics

41

Relationships
SELECT RoomName, FirstName, LastName FROM Guest NATURAL JOIN Room;

Relationships
SELECT RoomName, FirstName, LastName FROM Room LEFT JOIN Guest ON Guest.GuestNumber=Room.GuestNumber;

Room

1 0..1

Guest
247

Room

1 0..1

Guest
248

CO7101: Java & Databases For Bionformatics

CO7101: Java & Databases For Bionformatics

Relationships
SELECT RoomName, FirstName, LastName FROM Guest RIGHT JOIN Room ON Guest.GuestNumber=Room.GuestNumber;

Relationships
MySQL onlysupports onetomanyorone 0..* 0..* toonerelationships Room Guest Implementmanyto manyrelationshipsvia is in MySQL athirdtable represented Twoonetomany by relationshipsA>AB andB>AB. Thelogicalprimary Room 0..* 0..1 Guest keyforABisformed Room Allocation (B) fromthetwoforeign (A) 0..1 0..* (AB) keys
249 CO7101: Java & Databases For Bionformatics 250

Room

1 0..1

Guest

CO7101: Java & Databases For Bionformatics

RedesigningTables
CREATE TABLE Guest (GuestNumber INT NOT NULL,FirstName VARCHAR(15),LastName VARCHAR(15),PRIMARY KEY (GuestNumber)) ENGINE=INNODB; CREATE TABLE Room(RoomName VARCHAR(20) NOT NULL,PRIMARY KEY (RoomName))ENGINE=INNODB; CREATE TABLE RoomAllocation(RoomName VARCHAR(20) NOT NULL, GuestNumber INT NOT NULL, FOREIGN KEY (GuestNumber) REFERENCES Guest (GuestNumber), FOREIGN KEY (RoomName) REFERENCES Room (RoomName), PRIMARY KEY (GuestNumber, RoomName)) ENGINE=INNODB; Room Room
Name
(Primary Key)

RepopulateTables
RoomAllocation
RoomName
(Composite Primary Key andForeignKey)

Guest
Guest Number
(Primary Key)

GuestNumber
(Composite Primary KeyandForeignKey)

First Name Bob Tanya Anne

Last Name Hope Hope Example

OakleyRoom StoatRoom EagleRoom

OakleyRoom OakleyRoom StoatRoom EagleRoom

1 2 3 3

1 2 3

Room (A)

Room Allocation
0..1 0..*

0..* 0..1

(AB)

Guest (B)
251

INSERT INTO Guest VALUES (1,'Bob','Hope'),(2,'Tanya', 'Hope'),(3,'Anne','Example'); INSERT INTO Room VALUES ('Oakley Room'),('Stoat Room'),('Eagle Room'); INSERT INTO RoomAllocation VALUES ('Oakley Room',1), ('Oakley Room',2),('Stoat Room',3),('Eagle Room',3);
CO7101: Java & Databases For Bionformatics 252

CO7101: Java & Databases For Bionformatics

42

Relationships
SELECT FirstName, LastName, Room.RoomName FROM Guest NATURAL JOIN (Room NATURAL JOIN RoomAllocation);

ReferentialIntegrity andReferentialActions
Question:ifakeyattributeintheparenttableismodified,whatshould happeninthechildtable? SQLprovides4alternativereferentialactions: ONUPDATE&ONDELETEspecifyreferentialactionswhichdetermines whathappenswhenanattempttoUPDATEorDELETEacandidatekeyina parenttablewhichhasmatchingrowsinchildtable: FOREIGNKEY(Key)REFERENCESTable[ONDELETE|UPDATEAction]
CASCADE applychangestochildrows(couldtrickledown) SETNULLDEFAULT setchildkeystoNULL SET setchildkeystoDEFAULTvalue NOACTION rejecttheoperation(default)

Supposearoomsnameischanged.Whatisthemostappropriateaction? Supposearoomisdeleted.Whatisthemostappropriateaction?
0..* 0..*

Room
CO7101: Java & Databases For Bionformatics

Guest
253 254

ReferentialIntegrity andReferentialActions
CREATE TABLE RoomAllocation(RoomName VARCHAR(20) NOT NULL,GuestNumber INT NOT NULL,FOREIGN KEY (GuestNumber) REFERENCES Guest (GuestNumber) ON UPDATE CASCADE,FOREIGN KEY (RoomName) REFERENCES Room (RoomName) ON UPDATE CASCADE,PRIMARY KEY (GuestNumber, RoomName)) ENGINE=INNODB;

ReferentialIntegrity andReferentialActions
INSERT INTO Room VALUES ('Oakley Room'),('Stoat Room'),('Eagle Room'); INSERT INTO RoomAllocation VALUES ('Oakley Room',1),('Oakley Room',2),('Stoat Room',3),('Eagle Room',3); UPDATE Room SET RoomName = 'Condor Condor Room' Room WHERE RoomName = 'Oakley Room'; Room
Room Name
(Primary Key)

Room
Room Name
(Primary Key)

RoomAllocation
RoomName
(Composite Primary Key andForeignKey)

RoomAllocation
RoomName
(Composite Primary Key andForeignKey)

GuestNumber
(Composite Primary KeyandForeignKey)

GuestNumber
(Composite Primary KeyandForeignKey)

OakleyRoom StoatRoom EagleRoom

OakleyRoom OakleyRoom StoatRoom EagleRoom255

1 2 3 3

OakleyRoom StoatRoom EagleRoom

OakleyRoom OakleyRoom StoatRoom EagleRoom256

1 2 3 3

ReferentialIntegrity andReferentialActions
INSERT INTO Room VALUES ('Oakley Room'),('Stoat Room'),('Eagle Room'); INSERT INTO RoomAllocation VALUES ('Oakley Room',1),('Oakley Room',2),('Stoat Room',3),('Eagle Room',3); UPDATE RoomAllocation SET RoomName = 'Condor Condor Room' WHERE RoomName = 'Oakley Room'; Room
Room Name
(Primary Key)

ReferentialIntegrity andReferentialActions
INSERT INTO Room VALUES ('Oakley Room'),('Stoat Room'),('Eagle Room'); INSERT INTO RoomAllocation VALUES ('Oakley Room',1),('Oakley Room',2),('Stoat Room',3),('Eagle Room',3); UPDATE RoomAllocation SET RoomName = 'Condor Condor Room' WHERE RoomName = 'Oakley Room'; Room
Room Name
(Primary Key)

RoomAllocation
RoomName
(Composite Primary Key andForeignKey)

RoomAllocation
RoomName
(Composite Primary Key andForeignKey)

GuestNumber
(Composite Primary KeyandForeignKey)

GuestNumber
(Composite Primary KeyandForeignKey)

CondorRoom StoatRoom EagleRoom

OakleyRoom OakleyRoom StoatRoom EagleRoom257

1 2 3 3

CondorRoom StoatRoom EagleRoom

CondorRoom CondorRoom StoatRoom EagleRoom258

1 2 3 3

43

EnterpriseConstraints (BusinessRules)
Sometimes,realworldbusinessrulesinvolve constraintsthatrefertomorethanonetable.Its usefultodefineenterpriseconstraintsjustonce. Example:Amemberofstaffmaymanagenomore than100properties:
CREATE ASSERTION StaffNotOverLoaded CHECK (NOT EXISTS (SELECT StaffNo FROM PropertyForRent GROUP BY StaffNo HAVING COUNT (*) > 100)); CREATE TABLE PropertyForRent ( ... CONSTRAINT StaffNotOverLoaded);

DatabaseSchemasEvolveOverTime
Ideally,adatabaseiscreatedonceandthenusedfor manyyears...BUT Thedatamodelmaybeimproved(integrity, performance)... New N f featuresmaybe b added dd din i newreleases l ... Enterpriserulesmaychange... Therefore,SQLprovidesmanyoptionsforchanging tables: SeeALTERTABLEintheMySQLDocumentation

259

260

SummarySoFar...
DBsareactiveoralive contentsalwayschanging ThestructureofaDBcanalsoevolveovertime... DBcontentsshouldalwaysbeconsistent integrity ANSISQLprovidesseveralIntegrityEnhancementFeatures (IEFs) IEF=>domainconstraints,entity/referentialintegrity, businessrules... IEFsimplyadditionaldesignchoicesfornewDBs OneDBMScanmanagemultipleDBs notionofschemas& privileges

CO7101:Java&DatabasesFor Bioinformatics
SQL5:ViewsandtheDataControlLanguage Dr.StuartKerrigan

261

CO7101: Java & Databases For Bionformatics

262

PreviouslyonCO1019
DataDefinitionLanguage
CREATE DATABASE, DROP DATABASE etc. CREATE TABLE, ALTER TABLE, DROP TABLE

Inthislectureyouwilllearn
theprinciplesofobject(tables,etc.)ownership& privileges whatvirtualtables(views)areandwhytheyare useful how h views i aredefined d fi d&someconstraints i onviews i howviewscanbeimplemented&someprocessing issues howviews&privilegesmaybecombinedtoprovide accesscontrol

DataManipulationLanguage
SELECT, UPDATE, DELETE, INSERT

WhataboutDataControlLanguage?
263

264

44

TheImportanceofViews&Privileges
DBMSsareprimarilyusedinorganisations,andinlarge organisations,DBMSsareusedbyarangeofstaff:
directors,managers,analysts,engineers,personnel,secretarial,etc.

SQL'sAccessControlModel
AccessControlinSQLissimilartomultiuseroperating systems(e.g.Unix,Windows,...) AusersuppliesanAuthorisationIdandpasswordtothe DBMS TheDBMSopensasession fortheuser TheDBMSrunsSQLstatementsonbehalfoftheuser The Th userb becomesth theownerof fanyobjects bj t he h creates t Bydefault,onlytheownermayaccesshisobjects Theownermaygrantandrevokeaccessprivilegestoother users Thisisdiscretionaryaccesscontrol Mandatoryaccesscontrol:strictlyorderedclassificationlevel ofdbobjects&usersaregivenclearancelevels(not supportedbySQL)
266

Consequently,accesstodataindifferenttablesmayneedto becontrolledto:
provideaccesstoauthorisedusers restrictaccesstounauthorisedusers(security)whatcouldhappenif adbwashacked?! enforcebusinessrulesorgovernmentregulations

Views&privilegescanhelpimplementaccesscontrol...

265

GrantingPrivileges

Discretionaryaccessbasedonauthorizationidentifiers (username&password), ownership(specifiedbyauth.id.) &privileges (actions
usercancarryoutonthegiventable, e.g.,SELECT, etc.)

ExamplesofUsing SQLAccessControl
Allowanymemberofstaff(withanAuthID)toaccessthe Clienttable:
GRANT ALL PRIVILEGES ON Client TO PUBLIC

GRANT{PrivilegeList|ALLPRIVILEGES}
ONObjectName TO{AuthIdList|PUBLIC}[WITHGRANTOPTION]

where(typically):
ObjectNameisatable PrivilegeListmaybeacombinationof:
SELECT,INSERT,UPDATE,DELETE (canspecifycolumnnames) REFERENCES(columnnamesreferenced byintegrityconstraints,e.g., checkorforeignkeyconstraints) USAGE(useofdomaindefinitions) WITHGRANTOPTIONmeansusersinAuthIdListcanpasson privilegestoothers

Allowonlypersonnelstafftohirestaffortochangetheir salaries:
GRANT SELECT, INSERT, UPDATE (Salary) ON Staff TO personnel

Privilegesarerevokedinasimilarmanner:
REVOKE { PrivilegeList | ALL PRIVILEGES } ON ObjectName FROM { AuthIdList | PUBLIC } [ RESTRICT | CASCADE ] Recall:CASCADEwilldelete allrelatedobjectswhichreference thetable, andRESTRICTwillrejecttheDROPiftherearedependent objects

267

268

WhatareViews?
Aviewisavirtualtable,constructedfrombasetables Whywouldwewanttodothis? Onlythedefinitionofaviewisstoredpermanently(asa query) Aviewisrealiseddynamicallywhenitisfirstreferenced 3typesof fviews: i h horizontal, i l vertical, i l grouped/joined d/j i d ViewsaremanipulatedlikeotherDBMSobjects:
CREATE VIEW ViewName ... (next slide) DROP VIEW ViewName; GRANT ALL PRIVILEGES ON ViewName TO PUBLIC; REVOKE ALL PRIVILEGES ON ViewName FROM PUBLIC;

CreatingViews HorizontalViews
Ahorizontalview restrictstherows thatmaybeseen:
CREATE VIEW Manager3Staff AS (subselect) SELECT * FROM Staff WHERE BranchNo = 'B003';
(definingquery)

Then...
SELECT * FROM Manager3Staff; Sonowbranchmanagercanonlyseedetailsofherownbranch

Manager3Staff StaffNo Fname SG37 SG5 Ann Susan Lname Beech Brand Position Assistant Manager Sex F F Salary 12000 24000 BranchN o B003 B003

269

270

45

CreatingViews VerticalViews
Averticalview restrictsthecolumns thatmaybeseen:
CREATE VIEW Staff3 AS (subselect/defining query) SELECT StaffNo, Fname, Lname, Position FROM Manager3Staff; noticetheviewhere!

GeneralSyntaxforCreatingViews
Generalsyntax:
CREATE VIEW ViewName [ (NewColNames) ] AS SubSelect;

Then...
SELECT * FROM Staff3;

Sonowtheviewercantseethesalary yinfoofstaffmembers ( (only ythe managerseesthis)

StaffNo
SG37 SG5

Fname
Ann Susan

Staff3 Lname
Beech Brand
271

Position
Assistant Manager

TheSubSelectclauseiscalledthedefiningquery Tocreateaview,ausermusthaveSELECTprivilegeonthe b tables base bl Oncecreated,viewsoftenbehavelikeordinarybasetables... ViewscanbeusedinSELECTorJOINclauses Viewscanbeupdated(withsomerestrictions) DROPVIEWViewName[RESTRICT|CASCADE]

272

Grouped&JoinedViews
Viewscanbeusedtohelpsimplifycomplexqueries Example:createaviewshowingthenumberof propertiesmanagedbyeachmemberofstaffandthe branchestheyworkat:
CREATE VIEW StaffProperties (StaffNo, BranchNo, Properties) AS SELECT s.StaffNo, s.BranchNo, COUNT (*) FROM St Staff ff s, P PropertyForRent t F R t p WHERE s.StaffNo = p.StaffNo GROUP BY s.BranchNo, s.StaffNo; GROUPBYstmtinsubselect grouped view Multipletablesinsubselect joinedview JoinedViewsimplifies querying; nowwejustquerytheview

HowAreViewsImplemented?
MostDBMSsimplementviewsusingviewresolution,which translatesstoredqueryintoactualqueryonsrctables specifiedintheview SQLrewritestheviewreferencesbacktotheunderlyingbase tables viewmaterialisation:alternativeimplementation SQLpopulatesatemporarytablewhentheviewisfirst referencedandkeepsituptodate However,keepingthetemporarytableuptodatecanbe difficult... ViewmaterialisationisanactiveareaofDBresearch

CannowqueryStaffPropertiesasifitsabasetable
SELECT*FROMStaffProperties;
273

274

HowtoAccessOtherUsers'Objects
InSQL,thefullnameofatablehastheform: server.schema.owner.table e.g. achilles.mcscw3.sk223.student IftheSystemAdministrator(user'sa')ownsallofthe DreamHome tables, tables anduser'sbrand' sbrand managesBranch3 3, Thesa mightenter:
USE Dreamhome; GRANT SELECT ON Manager3Staff TO sbrand;

RestrictionsonViews
Withviews,somequeriesarenot permitted:
Queriesthatresolvetonested aggregates,e.g.,SELECTCOUNT(cnt)FROM
StaffPropCnt;(cntisbasedonanaggregatedfn)

Queries Q i that th tgive i aggregates t in i a WHEREclause,e.g.,SELECT*FROMStaffPropCnt


WHEREcnt>2;(cntderivedfromanaggregatefn)

Then,usersbrand couldreferencetheviewas:
SELECT * FROM Dreamhome.sa.Manager3Staff;

Orequally:
SELECT * FROM Dreamhome.Manager3Staff;
275

Groupedviewscantbejoinedwitha basetableorview

276

46

RestrictionsonViews
Viewscanbeupdatedprovided:
Therearenoaggregatesinthecolumnstobe updatedandDISTINCTisntspecified(canteliminate
duplicaterowsfromqueryresults)

UpdatingViews AnImportantSubtlety
SQLallowsaviewtobeupdatedprovidedthechangedrowsinthe basetablesstillsatisfyalloftheconditionsofthedefiningquery's WHEREclause. Forexample:
UPDATEManager3StaffSETBranchNo='B005' WHEREStaffNo='SG37';

TherearenoGROUPBYorHAVINGclausesbecausethis Theviewcontainsonlyonesourcetable(i.e.,nojoined views,Unions,Intsorsetdiff.(EXCEPT))withnonested SELECTs;alsoeveryeltinSELECTmustappearonly1x,&canonly


beacol

infodoesntsaywhereitcamefrom;inINSERTINTOStaffPropCnt VALUES(B003,SG5,2)wedontknowwhich2propertiesSG5manages(dont knowappropriateprimarykeyvaluesinPropertyForRent)

Thiswouldfailbecausethemodifiedrow(BranchNo='B005') wouldnolongerbeselectedbytheviewdefinition(WHERE BranchNo='B003'). )

Cantviolateintegrityconstraintsofbasetable either(e.g.:noNULLswhereNULLSnotallowed) Otherwise(i.e.,iftherow/colinviewcanbetraced backtoitssourcetable),changestoviewmeans changestobasetables(i.e.,viewcanbeupdatable)


277

WITHCHECKOPTIONofCREATEVIEWstmt:Viewupdatesmaynot allowrowstomigrateoutoftheview WITHLOCALCHECKOPTIONmeansanyupdatesonthisorrelatedobj cantcauserowstodisappearfromthisviewunlessitalsodisappears fromtheotherview WITHCASCADEDCHECKOPTION(default)meansanyupdatesonthis view&onrelatedviewscantcauserowstodisappearfromthisview Canexploitthisbehaviour tohelpenforce DBintegrity Putdomain/business constraintsintotheviewdefinition&only updateviews
278

SummaryofViews
Advantages:
Viewshelpprovidegranularityofaccesscontrol Viewscanhelpreducecomplexity(simplifytables&(e.g.)multitablequeries)and improveaccesscontrol,e.g.,customization(sametablescanbeseendifferentlyby differentusers) &convenience(usersseeonlywhattheyneed),improvedsecurity (viewsappropriate foruser,restrictsaccess todb),constancy(viewshowspartofbasetables & ifbasecolsnotinviewchg,noeffect),currency(changes tobasetableaccessed invieware
immediatelyseeninview)

SQL OverallSummary
SQLisapowerfulrelationalDBquerylanguage SQLisdeclarative,notprocedural(e.g.novariables) SQLisshowingitsage...(e.g.quirkysyntax,boltedon features) Butdespitebeingover25yearsold... SQLremainsTHEworld worldstandard standardforDBMSs MakesureyouunderstandSELECT,JOIN,UPDATEetc. andqualificationsofthese&canextracttheinfoyou want;makesureyoucandoeverythingwevedonein thepracticalsattheleast

ViewscanhelpmaintainDBintegrity(e.g.bydoingupdatesviaviews,recallthatif
WITHCHECK OPTIONisused,allupdates mustsatisfy definingquerysWHERE clause)

Disadvantages:
Therearesomerestrictionsontheiruse:someviewscantbeupdated.cantdo
aggregatesonaggregates inSELECT clauseoruseanaggregate fninWHEREclause;alsogrouped viewscant bejoinedwithabasetable/view, etc. (heredefiningqueryisrunonbasetables againeachtime;probw/frequentaccess)

Implementation:resolutionmethodcancauseaperformancepenalty Structurerestriction:downsideofconstancy (SELECT *FROMFooonlyselectscols


whichwereinFoowhenViewwascreated;viewneedstoberecreated fornewcolsinFootoappear inView) onfirstviewquery,buthardtomaintain currencyifbasetablesupdated)

Materialisationmethodcancauseconsistencyproblems(storestemptable

279

280

Next
TheInternet(done) HTML(done) RelationalDatabases(done) MySQL y Q ( (done) ) PHP (combiningHTML&MySQL)

Chapter0

IntroductiontoComputers and ProgrammingLanguages

281

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 0 - 282

47

AHistoryofComputers
CharlesBabbageiscreditedasthefatherofcomputer.Althoughnever actuallybuilt,heproposedthecomputingmachinescalledDifferenceEngine andAnalyticalEnginethatpossessedthecorecharacteristicsoftodays computers. AdaLovelace,whowrotedemonstrationprogramsforAnalyticalEngine,is creditedasthefirstprogrammer. ThefirstmoderncomputerwasbuiltbyAtanasoffofIowaStateUniversityin thelate1930s. AnelectromechanicalcomputerMARKIwasbuiltbyHowardAikenof Harvard. ThefirstcompletelyelectroniccomputerENIACIwasbuiltbyMauchlyand EckertoftheUniversityofPennsylvania.

ComputerArchitecture
Output Devices RAM

Communication i ti Devices

CPU Storage Devices

Input Devices
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 0 - 283

4th Ed Chapter 0 - 284

ProgressofCPUSpeed

ProgrammingLanguages
Threelevelsofprogramminglanguages:
MachineLanguages
Machinelanguageinstructionsarebinarycodedandverylow level.

AssemblyLanguages
Assemblylanguageallowssymbolicprogramming.Requiresan assemblertotranslateassemblyprogramsintomachine programs.
For more information on Intel CPUs, click
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

Intel Museum or Quick Reference Chart.

HighlevelLanguages
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 0 - 285

Highlevellanguageprovidesaveryhighconceptualmodelof computing.Requiresacompilertotranslatehighlevel 4 Ed Chapter 0 - 286 pogramsintoassembly programs.


th

Java
Javaisahighlevelobjectorientedlanguage developedbySunMicrosystems. Javascleandesignandwideavailabilitymake itanideallanguageforteachingthe fundamentalsofcomputerprogramming.

Chapter1

IntroductiontoObjectOriented ProgrammingandSoftware Development

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

Animated Version 4th Ed Chapter 0 - 287 . 4th Ed Chapter 1 - 288

48

Objectives
Afteryouhavereadandstudiedthischapter,you shouldbeableto
Namethebasiccomponentsofobjectorientedprogramming Differentiateclassesandobjects. Differentiateclassandinstancemethods. methods Differentiateclassandinstancedatavalues. Drawprogramdiagramsusingiconsforclassesandobjects Describesignificanceofinheritanceinobjectoriented programs Nameandexplainthestagesofthesoftwarelifecycle
. 4th Ed Chapter 1 - 289

ClassesandObjects
Objectorientedprogramsuseobjects. Anobject isathing,bothtangibleand intangible.Account,Vehicle,Employee,etc. To T create t anobject bj ti inside id th thecomputer t program,wemustprovideadefinitionfor objectshowtheybehaveandwhatkindsof informationtheymaintaincalledaclass. Anobjectiscalledaninstance ofaclass.
. 4th Ed Chapter 1 - 290

GraphicalRepresentationofaClass
<Class Name>
We use a rectangle to represent a class with its name appearing inside the rectangle.

GraphicalRepresentationofanObject

<Object Name>

We use a rectangle to represent an object and place the underlined name of the object inside the rectangle.

Example:

Account

Motorcycle

Example:
SV198 This is an object named SV198.

The notation we used here is based on the industry standard notation called UML, which stands for Unified Modeling Language.

4th Ed Chapter 1 - 291

4th Ed Chapter 1 - 292

AnObjectwiththeClassName
<Object Name> : <Class Name> This notation indicates the class which the object is an instance.

MessagesandMethods
Toinstructaclassoranobjecttoperformatask,wesenda message toit. Youcansendamessageonlytotheclassesandobjects thatunderstandthemessageyousenttothem. Aclassoranobjectmustpossessamatchingmethod tobe abletohandlethereceivedmessage. message Amethoddefinedforaclassiscalledaclassmethod,and amethoddefinedforanobjectiscalledaninstance method. Avaluewepasstoanobjectwhensendingamessageis calledanargument ofthemessage.

Example:
This tells an object SV198 is an instance of the BankAccount class.

SV198 : BankAccount

4th Ed Chapter 1 - 293

4th Ed Chapter 1 - 294

49

SendingaMessage
Message deposit with the argument 250.00 is sent to a BankAccount object SV198. Ask for the current balance of this particular account.

SendingaMessageandGettinganAnswer

getCurrentBalance() deposit 250.00


SV198 : BankAccount SV198 : BankAccount

current balance

The current balance of SV198 is returned.

4th Ed Chapter 1 - 295

4th Ed Chapter 1 - 296

CallingaClassMethod
Ask for the maximum possible speed for all MobileRobot objects is returned.

ClassandInstanceDataValues
Anobjectiscomprisedofdatavaluesandmethods. Aninstancedatavalue isusedtomaintaininformation specifictoindividualinstances.Forexample,each BankAccountobjectmaintainsitsbalance. Aclassdatavalue isusedtomaintaininformationsharedby allinstancesoraggregateinformationabouttheinstances. Forexample,minimumbalanceistheinformationsharedby allAccountobjects,whereastheaveragebalanceofall BankAccountobjectsisanaggregateinformation.

MobileRobot getMaximumSpeed()

maximum speed

4th Ed Chapter 1 - 297

4th Ed Chapter 1 - 298

SampleInstanceDataValue
SV129 : BankAccount current balance 908.55 SV098 : BankAccount current balance 1304.98 SV211 : BankAccount current balance 354.00

SampleClassDataValue
BankAccount
minimum balance 100.00 There is one copy of minimum balance for the whole class and shared by all instances.

This line is an instance-of relationship.

SV129 : BankAccount All three BankAccount objects possess the same instance data value current balance. The actual dollar amounts are, of course, different. current balance 908.55

SV098 : BankAccount current balance 1304.98

SV211 : BankAccount current balance 354.00

4th Ed Chapter 1 - 299

4th Ed Chapter 1 - 300

50

ObjectIconwithClassDataValue

Inheritance

SV129 : BankAccount minimum balance 100.00 current balance 908.55 When the class icon is not shown, we include the class data value in the object icon itself.

InheritanceisamechanisminOOPtodesign twoormoreentitiesthataredifferentbut sharemanycommonfeatures.


Featurescommontoallclassesaredefinedinthe superclass. Theclassesthatinheritcommonfeaturesfromthe superclassarecalledsubclasses.
Wealsocallthesuperclassanancestorandthesubclass adescendant.

4th Ed Chapter 1 - 301

4th Ed Chapter 1 - 302

ASampleInheritance

InheritanceHierarchy

HerearethesuperclassAccount andits subclassesSavingsandChecking.


Account

Anexampleofinheritancehierarchyamong differenttypesofstudents.
Student

Graduate

Undergrad

Checking

Savings Masters Doctoral Law Commuting Resident

4th Ed Chapter 1 - 303

4th Ed Chapter 1 - 304

SoftwareEngineering
Muchlikebuildingaskyscraper,weneeda disciplinedapproachindevelopingcomplex softwareapplications. Softwareengineering istheapplicationofa systematicanddisciplinedapproachtothe development,testing,andmaintenanceofa program. Inthisclass,wewilllearnhowtoapplysound softwareengineeringprincipleswhenwe developsampleprograms.
. 4th Ed Chapter 1 - 305

SoftwareLifeCycle
Thesequenceofstagesfromconceptionto operationofaprogramiscalledsoftwarelife cycle. Fivestagesare
Analysis Design Coding Testing OperationandMaintenance
. 4th Ed Chapter 1 - 306

51

Chapter2

Objectives
Afteryouhavereadandstudiedthischapter,you shouldbeableto
IdentifythebasiccomponentsofJavaprograms WritesimpleJavaprograms Describethedifferencebetweenobjectdeclarationand creation DescribetheprocessofcreatingandrunningJavaprograms UsetheDate,SimpleDateFormat,String,andJOptionPane standardclasses DevelopJavaprograms,usingtheincrementaldevelopment approach

GettingStartedwithJava

4th Ed Chapter 2 - 307

4th Ed Chapter 2 - 308

TheFirstJavaProgram
ThefundamentalOOPconceptillustratedby theprogram: Anobjectorientedprogramuses objects. j Thisprogramdisplaysawindowonthescreen. Thesizeofthewindowissetto300pixels wideand200pixelshigh.ItstitleissettoMy FirstJavaProgram.
. 4th Ed Chapter 2 - 309

ProgramCh2Sample1
import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFrame myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); } }
Use an object Declare a name Create an object j

4th Ed Chapter 2 - 310

ProgramDiagramforCh2Sample1

DependencyRelationship

Ch2Sample1
myWindow : JFrame

Ch2Sample1
setTitle("My First Java Program") myWindow : JFrame

Instead of drawing all messages, we summarize it by showing only the dependency relationship. The diagram shows that Ch2Sample1 "depends" on the service provided by myWindow.

4th Ed Chapter 2 - 311

4th Ed Chapter 2 - 312

52

ObjectDeclaration
Class Name This class must be defined before this declaration can be stated. Object Name One object is declared here. Object Name Name of the object we are creating here.

ObjectCreation
Class Name An instance of this class is created. Argument No arguments are used here.

JFrame

myWindow;

myWindow

= new JFrame (

);

More Examples

Account Student Vehicle

personal; jan, jim, jon; car1, car2;

More Examples

myCust = new Customer( ); jon = new Student("John Java"); car1 = new Vehicle( );

4th Ed Chapter 2 - 313

4th Ed Chapter 2 - 314

Declarationvs.Creation
1 2
Customer myCust myCust = = myCust; new new Customer( ); Customer( );

StateofMemoryvs.Program

myCust

myCust : Customer 1. The identifier myCust is declared and space is allocated in memory.

myCust

: Customer

: Customer

2. A Customer object is created and the identifier myCust is set to refer to it.

State-of-Memory Notation

Program Diagram Notation

4th Ed Chapter 2 - 315

4th Ed Chapter 2 - 316

Namevs.Objects
Customer myCust myCust myCust myCust = = = = myCust; new new new new Customer( Customer( ); ); Customer( ); ); Customer(

SendingaMessage
Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Argument The argument we are passing with the message.

myWindow y
myCust

setVisible

true

) ;

More Examples
Created with the first new . : Customer : Customer Created with the second new . Reference to the first Customer object is lost.

account.deposit( 200.0 ); student.setName("john"); car1.startEngine( );

4th Ed Chapter 2 - 317

4th Ed Chapter 2 - 318

53

ExecutionFlow
Program Code State-of-Memory Diagram
myWindow

ProgramComponents
AJavaprogramiscomposedof
: JFrame width height title visible

JFrame myWindow

myWindow; = new JFrame( );

myWindow.setSize(300, 200); myWindow.setTitle ("My First Java Program"); myWindow.setVisible(true);


300 200
My First Java

comments, import statements,and classdeclarations.

true

The diagram shows only four of the many data members of a JFrame object.

4th Ed Chapter 2 - 319

4th Ed Chapter 2 - 320

ProgramComponent:Comment
/* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFrame myWindow;

MatchingCommentMarkers
/* This is a comment on one line */ /* Comment number 1 */ /* Comment number 2 */ /

Comment
/* /* /* This is a comment */ */

These are part of the comment.

myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); } }

Error: No matching beginning marker.

4th Ed Chapter 2 - 321

4th Ed Chapter 2 - 322

ThreeTypesofComments
/*
/* This is a comment with three lines of text. */

ImportStatement
Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFrame myWindow;

Multiline Comment

Import Statement

// This is a comment // This is another comment // This is a third comment

Single line Comments myWindow = new JFrame( ); myWindow.setSize(300, 200);

/** * This class provides basic clock functions. In addition * to reading the current time and todays date, you can * use this class for stopwatch functions. */ . 4th Ed Chapter 2 - 323

myWindow.setTitle("My First Java Program"); javadoc Comments } myWindow.setVisible(true); }

4th Ed Chapter 2 - 324

54

ImportStatementSyntaxandSemantics
Package Name Name of the package that contains the classes we want to use. Class Name The name of the class we want to import. Use asterisks to import all classes. /*

ClassDeclaration
Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*;

Class Declaration

<package name> e.g. dorm

<class name> ; Resident;

class Ch2Sample1 { public static void main(String[ ] args) { JFrame myWindow;

myWindow = new JFrame( ); myWindow.setSize(300, 200);

More Examples

import import import

javax.swing.JFrame; java.util.*; com.drcaffeine.simplegui.*;


}

myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); }

4th Ed Chapter 2 - 325

4th Ed Chapter 2 - 326

MethodDeclaration
/* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ Modifier import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFrame myWindow;

MethodDeclarationElements
Modifier Return Type Method Name Parameter

Method Declaration public static void main( String[ ] args ){

JFrame myWindow; y myWindow = new JFrame( ); myWindow.setSize(300, 200);

Method Body y

myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); } }

myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); }


. 4th Ed Chapter 2 - 327 . 4th Ed Chapter 2 - 328

/*

TemplateforSimpleJavaPrograms
Chapter 2 Sample Program: Displaying a Window

WhyUseStandardClasses
Comment Import Statements

File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 {

public static void main(String[ ] args) { JFrame myWindow;

Class Name

myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); } }

Dontreinventthewheel.Whenthereare existingobjectsthatsatisfyourneeds,usethem. LearninghowtousestandardJavaclassesisthe firststeptowardmasteringOOP.Beforewecan learnhowtodefineourownclasses, classes weneedto learnhowtouseexistingclasses Wewillintroducefourstandardclasseshere:


JOptionPane String Date SimpleDateFormat.
. 4th Ed Chapter 2 - 330

Method Body

4th Ed Chapter 2 - 329

55

JOptionPane
UsingshowMessageDialog oftheJOptionPane classisasimplewaytodisplayaresultofa computationtotheuser.
JOptionPane.showMessageDialog(null, JO ti P h M Di l ( ll "I Love Java");

DisplayingMultipleLinesofText
Wecandisplaymultiplelinesoftextby separatinglineswithanewlinemarker\n.
JOptionPane.showMessageDialog(null, "one\ntwo\nthree");

This dialog will appear at the center of the screen.

4th Ed Chapter 2 - 331

4th Ed Chapter 2 - 332

String
Thetextualvaluespassedtothe showMessageDialogmethodareinstances oftheString class. Asequenceofcharactersseparatedby doublequotesisaString constant. Therearecloseto50methodsdefinedin theStringclass.Wewillintroducethreeof themhere:substring,length,andindexOf. Wewillalsointroduceastringoperation calledconcatenation.
. 4th Ed Chapter 2 - 333

StringisanObject
1 2
String String name name = = name; name; new new String("Jon Java"); Java"); String("Jon

name

1
: String

1. The identifier name is declared and space is allocated in memory.

2
Jon Java 2. A String object is created and the identifier name is set to refer to it.

4th Ed Chapter 2 - 334

StringIndexing

Definition:substring
Assumestr isaStringobjectandproperly initializedtoastring. str.substring(i,j) willreturnanewstringby extractingcharactersofstr frompositioni to j1 where0 i lengthofstr,0 j length ofstr, str andi j. j Ifstr is"programming" ,thenstr.substring(3, 7) willcreateanewstringwhosevalueis "gram" becauseg isatposition3andm isat position6. Theoriginalstringstr remainsunchanged.

The position, or index, of the first character is 0.

4th Ed Chapter 2 - 335

4th Ed Chapter 2 - 336

56

Examples:substring
String text = "Espresso";

Definition:length
AssumestrisaStringobjectandproperly initializedtoastring. str.length() willreturnthenumberof charactersinstr. Ifstris"programming" ,thenstr.length() will return11becausethereare11charactersin it. Theoriginalstringstr remainsunchanged.

text.substring(6,8) text.substring(0,8) text.substring(1,5) text.substring(3,3) text.substring(4,2)


.

"so" "Espresso" "spre" "" error


4th Ed Chapter 2 - 337

4th Ed Chapter 2 - 338

Examples:length
String str1 = str2 = str3 = str4 = str1.length( ) str2.length( ) str3.length( ) str4.length( ) str1, str2, str3, str4; "Hello" ; "Java" ; "" ; //empty string " " ; //one space

Definition:indexOf
Assumestr andsubstr areStringobjectsand properlyinitialized. str.indexOf(substr ) willreturnthefirst positionsubstr occursinstr. Ifstr is"programming" andsubstr is"gram" , then h str.indexOf(substr d f( b ) will llreturn3 becausethepositionofthefirstcharacterof substr instr is3. Ifsubstr doesnotoccurinstr,then1is returned. Thesearchiscasesensitive.
4th Ed Chapter 2 - 339 . 4th Ed Chapter 2 - 340

5 4 0 1

Examples:indexOf
String str; str = "I Love Java and Java loves me.";

Definition:concatenation
Assumestr1andstr2areStringobjectsand properlyinitialized. str1+str2 willreturnanewstringthatisa concatenationoftwostrings. Ifstr1is"pro"andstr2is"gram",thenstr1+ str2 willreturn"program". Noticethatthisisanoperatorandnota methodoftheStringclass. Thestringsstr1andstr2remainsthesame.
. 4th Ed Chapter 2 - 342

21

str.indexOf( "J" ) str2.indexOf( "love" ) str3.indexOf( "ove" ) str4.indexOf( "Me" )

7 21 3 -1
. 4th Ed Chapter 2 - 341

57

Examples:concatenation
String str1, str2; str1 = "Jon" ; str2 = "Java" ;
str1 + str2 str1 + " " + str2 str2 + ", " + str1 "Are you " + str1 + "?"

Date
TheDate classfromthejava.util packageisusedto representadate. WhenaDate objectiscreated,itissettotoday(the currentdatesetinthecomputer) TheclasshastoString g methodthatconvertsthe internalformattoastring. Date today; today = new Date( ); today.toString( );
"Fri Oct 31 10:05:18 PST 2003"
. 4th Ed Chapter 2 - 344

"J J "JonJava" " "Jon Java" "Java, Jon" "Are you Jon?"

4th Ed Chapter 2 - 343

SimpleDateFormat
TheSimpleDateFormat classallowstheDate informationtobedisplayedwithvariousformat. Table2.1page68showstheformattingoptions.
Date today = new Date( ) ); SimpleDateFormat sdf1, sdf2; sdf1 = new SimpleDateFormat("MM/dd/yy"); sdf2 = new SimpleDateFormat("MMMM dd,yyyy"); "10/31/03" sdf1.format(today);
sdf2.format(today);

JOptionPaneforInput
UsingshowInputDialog oftheJOptionPane classisasimplewaytoinputastring.
String name; name = JOptionPane.showInputDialog p p g (null, "What is your name?");
This dialog will appear at the center of the screen ready to accept an input.

"October 31, 2003"

4th Ed Chapter 2 - 345

4th Ed Chapter 2 - 346

Chapter3

Animated Version 4th Ed Chapter 3 - 347

Objectives
Afteryouhavereadandstudiedthischapter,you shouldbeableto
Selectpropertypesfornumericaldata. WritearithmeticexpressionsinJava. Evaluatearithmeticexpressionsusingtheprecedencerules. Describehowthememoryallocationworksforobjectsand primitivedatavalues. values Writemathematicalexpressions,usingmethodsintheMath class. UsetheGregorianCalendar classinmanipulatingdate informationsuchasyear,month,andday. UsetheDecimalFormat classtoformatnumericaldata Convertinputstringvaluestonumericaldata PerforminputandoutputbyusingSystem.in andSystem.out

NumericalData

4th Ed Chapter 3 - 348

58

ManipulatingNumbers
InJava,toaddtwonumbersxandy,wewrite
x + y

Variables
Whenthedeclarationismade,memoryspace isallocatedtostorethevaluesofxandy. xandyarecalledvariables.Avariablehas threeproperties:
Amemorylocationtostorethevalue, Thetypeofdatastoredinthememorylocation,and Thenameusedtorefertothememorylocation.

Butbeforetheactualadditionofthetwo numbers b takes t k place, l wemust tdeclare d l their th i datatype.Ifxandyareintegers,wewrite


int x, y;

or
int x; int y;
4th Ed Chapter 3 - 349

Samplevariabledeclarations:
int x; int v, w, y;
4th Ed Chapter 3 - 350

NumericalDataTypes
Sixnumericaldatatypes:byte,short,int,long,float & double. Samplevariabledeclarations:
int i, j, k; , numberTwo; ; float numberOne, long bigInteger; double bigNumber;

DataTypePrecisions
The six data types differ in the precision of values they can store in memory.

At the time a variable is declared, it also can be initialized. For example, we may initialize the integer variables count and height to 10 and 34 as
int count = 10, height = 34;
4th Ed Chapter 3 - 351 4th Ed Chapter 3 - 352

AssignmentStatements
double float long int short h t byte

Weassignavaluetoavariableusingan assignmentstatements. Thesyntaxis


<variable> = <expression> ;

Examples:
sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0;

4th Ed Chapter 3 - 354

59

ArithmeticOperators
Thefollowingtablesummarizesthearithmetic operatorsavailableinJava.

ArithmeticExpression
Howdoestheexpression
x + 3 * y

This is an integer division where the fractional part is truncated.


4th Ed Chapter 3 - 355

getevaluated?Answer:xisaddedto3*y. Wedeterminetheorderofevaluationby followingtheprecedencerules. Ahigherprecedenceoperatorisevaluated beforethelowerone.Iftwooperatorsarethe sameprecedence,thentheyareevaluatedleft torightformostoperators.


4th Ed Chapter 3 - 356

PrecedenceRules

TypeCasting
Ifx isafloat andy isanint,whatwillbethedatatypeofthe followingexpression?
x * y

Theanswerisfloat. The Th above b expression i is i called ll damixed i dexpression i . Thedatatypesoftheoperandsinmixedexpressionsare convertedbasedonthepromotionrules.Thepromotionrules ensurethatthedatatypeoftheexpressionwillbethesame asthedatatypeofanoperandwhosetypehasthehighest precision.

4th Ed Chapter 3 - 357

4th Ed Chapter 3 - 358

ExplicitTypeCasting
Insteadofrelyingonthepromotionrules,we canmakeanexplicittypecastbyprefixingthe operandwiththedatatypeusingthe followingsyntax:
( <data type> ) <expression>

ImplicitTypeCasting
Considerthefollowingexpression:
double x = 3 + 5;

Example
(float) y / 3 (int) (x / y * 3.0)
Type case y to float and then divide it by 3. Type cast the result of the expression x / y * 3.0 to int.
4th Ed Chapter 3 - 359

Theresultof3+5isoftypeint.However, sincethevariablex isdouble,thevalue8 (type ( yp int)isp promotedto8.0( (type yp double) beforebeingassignedtox. Noticethatitisapromotion.Demotionis notallowed.
int x = 3.5;
A higher precision value cannot be assigned to a lower precision variable.

4th Ed Chapter 3 - 360

60

Constants
Wecanchangethevalueofavariable.Ifwe wantthevaluetoremainthesame,weusea constant.
final double PI = 3 3.14159; 14159; final int MONTH_IN_YEAR = 12; final short FARADAY_CONSTANT = 23060;
The reserved word final is used to declare constants. These are constants, also called named

Primitivevs.Reference
Numericaldataarecalledprimitivedatatypes. Objectsarecalledreferencedatatypes, becausethecontentsareaddressesthatrefer tomemorylocationswheretheobjectsare actuallystored.

These are called

constant.

literal constant.

4th Ed Chapter 3 - 361

4th Ed Chapter 3 - 362

PrimitiveDataDeclarationandAssignments

AssigningNumericalData
int number; number = 237; number = 35;

int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87;

A. Variables are
allocated in memory.

number

35 237

A
int firstNumber, secondNumber; firstNumber = 234; B secondNumber = 87;

firstNumber secondNumber

234 87 int number; number = 237; number = 35;

A. The variable

A B C

is allocated in memory.

B. The value 237


is assigned to number.

B. Values are assigned


to variables.

C. The value 35
overwrites the previous value 237.

Code

State of Memory
4th Ed Chapter 3 - 363

Code

State of Memory
4th Ed Chapter 3 - 364

AssigningObjects
Customer customer; customer = new Customer( ); customer = new Customer( );

HavingTwoReferencestoaSingleObject

customer
Customer Customer

Customer clemens, twain; clemens = new Customer( ); twain = clemens;

clemens twain
Customer

A
Customer customer; customer = new Customer( ); B. The reference to the customer = new Customer( );
new object is assigned to customer.

A B
A The variable is A.
allocated in memory.

Customer clemens, twain; twain, clemens = new Customer( );

A Variables are A.
allocated in memory.

B. The reference to the twain = clemens;


new object is assigned to clemens.

C Code

C. The reference to
another object overwrites the reference in customer.

C Code

C. The reference in
clemens is assigned to customer.

State of Memory
4th Ed Chapter 3 - 365

State of Memory
4th Ed Chapter 3 - 366

61

TypeMismatch

TypeConversion

Supposewewanttoinputanage.Willthis work?
int age;

Wrapperclasses areusedtoperformnecessary typeconversions,suchasconvertingaString objecttoanumericalvalue.


int String age; g inputStr;

age = JOptionPane.showInputDialog( null, "Enter your age");

No. String value cannot be assigned directly to an int variable.


4th Ed Chapter 3 - 367

inputStr = JOptionPane.showInputDialog( null, "Enter your age"); age = Integer.parseInt(inputStr);


4th Ed Chapter 3 - 368

OtherConversionMethods

SampleCodeFragment
//code fragment to input radius and output //area and circumference double radius, area, circumference; String radiusStr = JOptionPane.showInputDialog( null, "Enter radius: " ); radius = Double.parseDouble(radiusStr); p ( ); //compute area and circumference area = PI * radius * radius; circumference = 2.0 * PI * radius; JOptionPane.showMessageDialog(null, "Given Radius: " + radius + "\n" + "Area: " + area + "\n" + "Circumference: " + circumference);

4th Ed Chapter 3 - 369

4th Ed Chapter 3 - 370

OverloadedOperator+
Theplusoperator+canmeantwodifferentoperations, dependingonthecontext. <val1>+<val2>isanadditionifbotharenumbers.Ifeitherone ofthemisaString,theitisaconcatenation. Evaluationg goesfromlefttoright. g
output = "test" + 1 + 2; output = 1 + 2 + "test";

TheDecimalFormatClass
UseaDecimalFormat objecttoformatthenumericaloutput.
double num = 123.45789345; DecimalFormat df = new DecimalFormat("0.000"); // h //three d decimal i l places l

System.out.print(num); System.out.print(df.format(num));

123.45789345

123.458

4th Ed Chapter 3 - 371

4th Ed Chapter 3 - 372

62

StandardOutput

StandardOutputWindow

TheshowMessageDialog methodisintended fordisplayingshortonelinemessages,notfor ageneralpurposeoutputmechanism. UsingSystem.out, wecanoutputmultiple linesoftexttothestandardoutputwindow.

Asamplestandardoutputwindowfordisplaying multiplelinesoftext.

The exact style of standard output window depends on the Java tool you use.
4th Ed Chapter 3 - 373 4th Ed Chapter 3 - 374

TheprintMethod

TheprintlnMethod

Weusetheprint methodtooutputavalueto thestandardoutputwindow. Theprint methodwillcontinueprintingfrom theendofthecurrentlydisplayedoutput. Example


System.out.print( "Hello, Dr. Caffeine." );

Weuseprintln insteadofprint toskipaline.


int x = 123, y = x + x; System.out.println( "Hello, Dr. Caffeine." ); System.out.print( " x = " ); System.out.println( x ); System.out.print( " x + x = " ); System.out.println( y ); System.out.println( " THE END" );

4th Ed Chapter 3 - 375

4th Ed Chapter 3 - 376

StandardInput

CommonScannerMethods:
Method
nextByte() nextDouble() nextFloat() nextInt() nextLong() nextShort() next()

ThetechniqueofusingSystem.intoinputdata iscalledstandardinput. Wecanonlyinputasinglebyteusing System.indirectly. p p primitivedatavalues, ,weusethe Toinput Scannerclass(fromJava5.0).


Scanner scanner = new Scanner(System.in); int num = scanner.nextInt();

Example
byteb=scanner.nextByte(); doubled=scanner.nextDouble(); floatf=scanner.nextFloat(); inti=scanner.nextInt(); longl=scanner.nextLong(); shorts=scanner.nextShort(); Stringstr=scanner.next();

4th Ed Chapter 3 - 377

4th Ed Chapter 3 - 378

63

TheMathclass

SomeMathClassMethods
Method exp(a) log(a) floor(a) max(a b) max(a,b) pow(a,b) sqrt(a) sin(a) Description
Natural number e raised to the power of a. Natural logarithm (base e) of a. The largest whole number less than or equal to a.
The larger of a and b.

TheMath classinthejava.langpackage containsclassmethodsforcommonlyused mathematicalfunctions.


double num, x, y; x = ; ; y = ; num = Math.sqrt (Math.max(x, y) + 12.4);

The number a raised to the power of b. The square root of a. The sine of a. (Note: all trigonometric functions are computed in radians)

Table 3.6 in the textbook contains a list of class methods defined in the Math class.

Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math class.
4th Ed Chapter 3 - 380

4th Ed Chapter 3 - 379

Chapter4

Objectives
Afteryouhavereadandstudiedthischapter,you shouldbeableto
Defineaclasswithmultiplemethodsanddata members Differentiatethelocalandinstancevariables Defineandusevaluereturningmethods Distinguishprivateandpublicmethods Distinguishprivateandpublicdatamembers Passbothprimitivedataandobjectstoamethod
Animated Version 4th Ed Chapter 4 - 381

DefiningYourOwnClasses Part1

WhyProgrammerDefinedClasses
UsingjusttheString, GregorianCalendar,JFrame andotherstandardclasseswillnotmeetallof ourneeds.Weneedtobeabletodefineourown classescustomizedforourapplications. pp Learninghowtodefineourownclassesisthe firststeptowardmasteringtheskillsnecessaryin buildinglargeprograms. Classeswedefineourselvesarecalled programmerdefinedclasses.

FirstExample:UsingtheBicycleClass
class BicycleRegistration { public static void main(String[] args) { Bicycle bike1, bike2; String owner1, owner2; //Create and assign values to bike1

bike1 = new Bicycle( );

bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); //Create and assign values to bike2

bike2.setOwnerName("Ben Jones"); owner1 = bike1.getOwnerName( ); //Output the information owner2 = bike2.getOwnerName( ); System.out.println(owner1 + " owns a bicycle."); System.out.println(owner2 + " also owns a bicycle."); } }

4th Ed Chapter 4 - 383

4th Ed Chapter 4 - 384

64

TheDefinitionoftheBicycleClass
class Bicycle { // Data Member private String ownerName; //Constructor: Initialzes the data member public Bicycle( ) { ownerName = "Unknown"; } //Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; } //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; }

MultipleInstances
OncetheBicycle classisdefined,wecancreatemultipleinstances.
bike1
Bicycle bike1, bike2; bik 1 = new Bicycle( bike1 i l ( ) ); bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); bike2.setOwnerName("Ben Jones"); : Bicycle y ownerName "Adam Smith" : Bicycle y ownerName "Ben Jones"

bike2

Sample Code

4th Ed Chapter 4 - 385

4th Ed Chapter 4 - 386

TheProgramStructureandSource Files
BicycleRegistration Bicycle

ClassDiagramforBicycle

Bicycle Bicycle( ) getOwnerName( ) setOwnerName(String)


Method Listing We list the name and the data type of an argument passed to the method.

There are two source files files. Each class definition is stored in a separate file.
BicycleRegistration.java Bicycle.java

To run the program: 1. javac Bicycle.java (compile) 2. javac BicycleRegistration.java (compile) 3. java BicycleRegistration (run)

4th Ed Chapter 4 - 387

4th Ed Chapter 4 - 388

TemplateforClassDefinition
Import Statements Class Comment

DataMemberDeclaration
<modifiers> <data type> <name> ;

class

Class Name

Modifiers
Data Members

Data Type

Name

private
Methods
(incl. Constructor)

String

ownerName ;

Note: Theres only one modifier in this example.

4th Ed Chapter 4 - 389

4th Ed Chapter 4 - 390

65

MethodDeclaration
<modifier> } <return type> <method name> ( <parameters> ){ <statements>

Aconstructor isaspecialmethodthatisexecutedwhenanewinstanceofthe classiscreated.

Constructor

public <class name> ( <parameters> ){ <statements> }


Method Name Parameter Modifier Class Name Parameter

Modifier

Return Type yp

public

void

setOwnerName

String

name

) {

public }

Bicycle

) {

ownerName = name; }

Statements

ownerName = "Unassigned";
Statements

4th Ed Chapter 4 - 391

4th Ed Chapter 4 - 392

SecondExample:UsingBicycleandAccount
class SecondMain { //This sample program uses both the Bicycle and Account classes public static void main(String[] args) { Bicycle bike; Account myAcct; String myName = "Jon Java";
class Account {

TheAccountClass
private String ownerName; private double balance; public Account( ) { ownerName = "Unassigned"; balance = 0.0; } public void add(double amt) { balance = balance + amt; } public void deduct(double amt) { balance = balance - amt; } public double getCurrentBalance( ) { return balance; } public String getOwnerName( ) { } return ownerName; public void setInitialBalance (double bal) { } balance = bal; public void setOwnerName (String name) { } ownerName = name;

bike = new Bicycle( ); bike.setOwnerName(myName); bike setOwnerName(myName); myAcct = new Account( ); myAcct.setOwnerName(myName); myAcct.setInitialBalance(250.00); myAcct.add(25.00); myAcct.deduct(50); //Output some information System.out.println(bike.getOwnerName() + " owns a bicycle and"); System.out.println("has $ " + myAcct.getCurrentBalance() + " left in the bank"); } }

Page 1

Page 2

4th Ed Chapter 4 - 393

4th Ed Chapter 4 - 394

TheProgramStructureforSecondMain
Bicycle SecondMain Account
} }

ArgumentsandParameters
class Sample { public static void main(String[] arg) { Account myAcct = new Account(); . . . myAcct.add(400); . . . } class Account { . . . public void add(double amt) { } balance = balance + amt;

parameter

. . .

. . .

argument

SecondMain.java

Bicycle.java

Account.java

Anargumentisavaluewepasstoamethod
Note: You only need to compile the class once. Recompile only when you made changes in the code.
4th Ed Chapter 4 - 395

To run the program: 1. javac Bicycle.java 2. javac Account.java 2. javac SecondMain.java 3. java SecondMain

(compile) (compile) (compile) (run)

A parameter is a placeholder in the called method to hold the value of the passed argument.

4th Ed Chapter 4 - 396

66

MatchingArgumentsandParameters

Demo myInst = new Demo( ); int i = 5; int k = 14; myInst.compute(i, k, 20);

MemoryAllocation
i k 5 14 20 i j x 5 14 20.0

Thenumber or argumentsandthe parametersmustbe thesame

3 arguments

Separatememory spaceisallocatedfor thereceiving method. Values of arguments are passed into memory allocated for parameters.

Passing Side

Arguments and parameters are p paired left to right The matched pair must be assignmentcompatible (e.g. you cannot pass a double argument to a int parameter)

Passing Side
class Demo { public void compute(int i, int j, double x) { . . . } }

Receiving Side

3 parameters

Literal constant has no name

Receiving Side

4th Ed Chapter 4 - 397

4th Ed Chapter 4 - 398

PassingObjectstoaMethod
Aswecanpassintanddoublevalues,wecan alsopassanobjecttoamethod. Whenwepassanobject,weareactually passingthereference(name)ofanobject
itmeansaduplicateofanobjectisNOTcreatedin thecalledmethod

PassingaStudentObject
LibraryCard card2; card2 = new LibraryCard(); card2.setOwner(student);

student

1
st

card2

Passing Side

1 2
: LibraryCard owner : Student name "Jon Java" borrowCnt email "jj@javauniv.edu"

class LibraryCard { private Student owner; public bli void id setOwner(Student tO (St d t st) t) { } } owner = st;

Receiving Side

1 2
4th Ed Chapter 4 - 399

Argument is passed Value is assigned to the data member

State of Memory
4th Ed Chapter 4 - 400

SharinganObject
WepassthesameStudent objecttocard1andcard2

InformationHidingandVisibilityModifiers

Since we are actually passing a reference to the same object, it results in owner of two LibraryCard objects pointing to the same Student object
4th Ed Chapter 4 - 401

Themodifierspublicandprivatedesignatethe accessibilityofdatamembersandmethods. Ifaclasscomponent(datamemberormethod)is declaredprivate,clientclassescannotaccessit. Ifaclasscomponentisdeclaredpublic,client classescanaccessit. Internaldetailsofaclassaredeclaredprivateand hiddenfromtheclients.Thisisinformation hiding.


4th Ed Chapter 4 - 402

67

AccessibilityExample
Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); class Service { public int memberOne; private int memberTwo; public void doOne() { } private void doTwo() { } }

DataMembersShouldBeprivate

Datamembersaretheimplementationdetails oftheclass,sotheyshouldbeinvisibletothe clients.Declarethemprivate . Exception:Constantscan(should)bedeclared publiciftheyaremeanttobeuseddirectlyby theoutsidemethods.

Client

Service
4th Ed Chapter 4 - 403 4th Ed Chapter 4 - 404

GuidelineforVisibilityModifiers
Guidelinesindeterminingthevisibilityofdata membersandmethods:
Declaretheclassandinstancevariablesprivate. Declaretheclassandinstancemethodsp privateif theyareusedonlybytheothermethodsinthe sameclass. Declaretheclassconstantspublicifyouwantto maketheirvaluesdirectlyreadablebytheclient programs.Iftheclassconstantsareusedfor internalpurposesonly,thendeclarethemprivate.
4th Ed Chapter 4 - 405

DiagramNotationforVisibility

public plus symbol (+) private minus symbol (-)

4th Ed Chapter 4 - 406

ClassConstants
InChapter3,weintroducedtheuseofconstants. Weillustratetheuseofconstantsinprogrammer definedserviceclasseshere. Remember,theuseofconstants
providesameaningfuldescriptionofwhatthevalues standfor.number=UNDEFINED;ismoremeaningful thannumber=1; provideseasierprogrammaintenance.Weonlyneedto changethevalueintheconstantdeclarationinsteadof locatingalloccurrencesofthesamevalueinthe programcode
4th Ed Chapter 4 - 407

ASampleUseofConstants
class Dice { private static final int MAX_NUMBER = 6; private static final int MIN_NUMBER = 1; private static final int NO_NUMBER = 0; private int number; public Dice( ) { number = NO NO_NUMBER; NUMBER; } //Rolls the dice public void roll( ) { number = (int) (Math.floor(Math.random() * (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER); } //Returns the number on this dice public int getNumber( ) { return number; } }
4th Ed Chapter 4 - 408

68

LocalVariables
Localvariablesaredeclaredwithinamethod declarationandusedfortemporaryservices,such asstoringintermediatecomputationresults.
public double convert(int num) { double result; local variable

Local,Parameter&DataMember

Anidentifierappearinginsideamethodcanbea localvariable,aparameter,oradatamember. Therulesare


Iftheresamatchinglocalvariabledeclarationora parameter,thentheidentifierreferstothelocal variableortheparameter. Otherwise,iftheresamatchingdatamember declaration,thentheidentifierreferstothedata member. Otherwise,itisanerrorbecausetheresnomatching declaration.

result = Math.sqrt(num * num); return result; }

4th Ed Chapter 4 - 409

4th Ed Chapter 4 - 410

SampleMatching
class MusicCD { private String private String private String artist; title; id;

CallingMethodsoftheSameClass
Sofar,wehavebeencallingamethodofanotherclass(object). Itispossibletocallmethodofaclassfromanothermethodof thesameclass.
inthiscase,wesimplyrefertoamethodwithoutdotnotation

public MusicCD(String name1, String name2) { String ident; artist = name1; title ident = name2; = artist.substring(0,2) + "-" + title.substring(0,9); id } ... }
4th Ed Chapter 4 - 411 4th Ed Chapter 4 - 412

= ident;

ChangingAnyClasstoaMainClass
Anyclasscanbesettobeamainclass. Allyouhavetodoistoincludethemainmethod.
class Bicycle { //definition of the class as shown before //comes here //The main method that shows a sample //use of the Bicycle class public static void main(String[] args) { Bicycle myBike; myBike = new Bicycle( ); myBike.setOwnerName("Jon Java"); System.out.println(myBike.getOwnerName() + "owns a bicycle"); } }
4th Ed Chapter 4 - 413

Chapter5

SelectionStatements

Animated Version 4th Ed Chapter 5 - 414

69

Objectives
Afteryouhavereadandstudiedthischapter,you shouldbeableto
Implementaselectioncontrolusingif statements Implementaselectioncontrolusingswitch statements Writebooleanexpressionsusingrelationalandboolean expressions Evaluategivenbooleanexpressionscorrectly Nestanif statementinsideanotherif statement Describehowobjectsarecompared Choosetheappropriateselectioncontrolstatementfora giventask

TheifStatement
int testScore; testScore = //get test score input if (testScore < 70)
This statement is executed if the testScore JOptionPane.showMessageDialog(null, is less than 70.

"You did not pass" ); else


This statement is executed if the testScore

JOptionPane.showMessageDialog(null, is 70 or higher. "You did pass" );

4th Ed Chapter 5 - 416

SyntaxfortheifStatement
if ( <boolean expression> ) <then block> else <else block>
Boolean Expression
JOptionPane. showMessageDialog s o essage a og (null, "You did pass"); if ( testScore < 70 )

ControlFlow
false
testScore < 70 ?

true

JOptionPane. showMessageDialog s o essage a og (null, "You did not pass");

Then Block
else

JOptionPane.showMessageDialog(null, "You did not pass" );

Else Block

JOptionPane.showMessageDialog(null, "You did pass " );

4th Ed Chapter 5 - 417

4th Ed Chapter 5 - 418

RelationalOperators
< <= == != > >= //less than //less than or equal to //equal to //not equal to //greater than //greater than or equal to {

CompoundStatements
Usebracesifthe<then>or<else>blockhasmultiplestatements.
if (testScore < 70) JOptionPane.showMessageDialog(null, "You did not pass ); JOptionPane.showMessageDialog(null, JOpt o a e.s o essage a og( u , Try harder next time ); }

Then Block

testScore < 80 testScore * 2 >= 350 30 < w / (h * h) x + y != 2 * (a + b) 2 * Math.PI * radius <= 359.99

else { JOptionPane.showMessageDialog(null, You did pass ); JOptionPane.showMessageDialog(null, Keep up the good work ); }

Else Block

4th Ed Chapter 5 - 419

4th Ed Chapter 5 - 420

70

StyleGuide
if ( <boolean expression> ) { } else { } if ( <boolean expression> ) { } else { }

TheifthenStatement
if ( <boolean expression> ) <then block> Style 1

Boolean Expression

if (

testScore >= 95

Style 2

Then Block

JOptionPane.showMessageDialog(null, "You are an honor student");

4th Ed Chapter 5 - 421

4th Ed Chapter 5 - 422

ControlFlowofifthen
testScore >= 95?

TheNestedifStatement
Thethenandelseblockofanifstatementcan containanyvalidstatements,includingotherif statements.Anifstatementcontaininganother ifstatementiscalledanestedifstatement.
if ( (testScore >= 70) ) { if (studentAge < 10) { System.out.println("You did a great job"); } else { System.out.println("You did pass"); //test score >= 70 } } else { //test score < 70 System.out.println("You did not pass"); } //and age >= 10

true

false

JOptionPane. showMessageDialog s o essage a og ( (null, u , "You are an honor student");

4th Ed Chapter 5 - 423

4th Ed Chapter 5 - 424

ControlFlowofNestedifStatement
false
testScore >= 70 ?

WritingaProperifControl
inner if
if (num1 < 0) if (num2 < 0) if (num3 < 0) negativeCount = 3; else negativeCount = 2;

true
false

negativeCount = 0; if (num1 < 0) negativeCount++; if (num2 < 0) negativeCount++; if (num3 < 0) negativeCount++;

messageBox.show ("You did not pass");

studentAge < 10 ?

true

else if (num3 < 0) negativeCount = 2; else negativeCount = 1;

messageBox.show ("You did pass");

messageBox.show ("You did a great job");

else if (num2 < 0) if (num3 < 0) negativeCount = 2; else negativeCount = 1; else if (num3 < 0) negativeCount = 1; else negativeCount = 0;

The statement negativeCount++; increments the variable by one

4th Ed Chapter 5 - 425

4th Ed Chapter 5 - 426

71

if elseifControl
if (score >= 90) System.out.print("Your grade is A"); if (x < y) else if (score >= 80) System.out.print("Your grade is B"); else else if (score >= 70) System.out.print("Your grade is C"); else if (score >= 60) System.out.print("Your grade is D"); else System.out.print("Your grade is F"); if (x < y) if (x < z) if (x < z)

Matchingelse
Are A and B different? A Both A and B means
if (x < y) { if (x < z) { System.out.print("Good bye"); System.out.print("Hello"); } else { System.out.print("Good bye"); }

Test Score
90 score 80 score 90 70 score 80 60 score 70 score 60

Grade
A B C D F

System.out.print("Hello");

System.out.print("Hello"); else System.out.print("Good bye");

4th Ed Chapter 5 - 427

4th Ed Chapter 5 - 428

BooleanOperators

SemanticsofBooleanOperators

Abooleanoperator takesbooleanvaluesasits operandsandreturnsabooleanvalue. Thethreebooleanoperatorsare


and: or: not && || !

Booleanoperatorsandtheirmeanings:
P false false true true Q false true false true P && Q false false false true P || Q false true true true !P true true false false

if (temperature >= 65 && distanceToDestination < 2) { System.out.println("Let's walk"); } else { System.out.println("Let's drive"); }
4th Ed Chapter 5 - 429 4th Ed Chapter 5 - 430

DeMorgan'sLaw
DeMorgan'sLawallowsustorewriteboolean expressionsindifferentways
Rule 1: !(P && Q) !P || !Q Rule 2: !(P ( || Q) !P && !Q Q

ShortCircuitEvaluation
Considerthefollowingbooleanexpression:
x > y || x > z

!(temp >= 65 && dist < 2) !(temp >=65) || !(dist < 2) by Rule 1 (temp < 65 || dist >= 2)

Theexpressionisevaluatedlefttoright.Ifx>yistrue,then theresnoneedtoevaluatex>zbecausethewhole expressionwillbetruewhetherx>zistrueornot not. Tostoptheevaluationoncetheresultofthewholeexpression isknowniscalledshortcircuitevaluation. Whatwouldhappeniftheshortcircuitevaluationisnotdone forthefollowingexpression?


z == 0 || x / z > 20

4th Ed Chapter 5 - 431

4th Ed Chapter 5 - 432

72

OperatorPrecedenceRules

BooleanVariables

Theresultofabooleanexpressioniseither true orfalse.Thesearethetwovaluesof datatypeboolean. Wecandeclareavariableofdatatype b l boolean and dassign i ab boolean l value l toi it.
boolean pass, done; pass = 70 < x; done = true; if (pass) { } else { }
4th Ed Chapter 5 - 433 4th Ed Chapter 5 - 434

BooleanMethods
Amethodthatreturnsabooleanvalue,suchas
private boolean isValid(int value) { if (value < MAX_ALLOWED) return true; } else { return false; } }

ComparingObjects

Withprimitivedatatypes,wehaveonlyone waytocomparethem,butwithobjects (referencedatatype),wehavetwowaysto comparethem them.


1. Wecantestwhethertwovariablespointtothe sameobject(use==),or 2. Wecantestwhethertwodistinctobjectshave thesamecontents.

Can be used as

if (isValid(30)) { } else { }

4th Ed Chapter 5 - 435

4th Ed Chapter 5 - 436

Using==WithObjects(Sample1)
String str1 = new String("Java"); String str2 = new String("Java"); if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They y p ( y are not equal"); q ) }

Using==WithObjects(Sample2)
String str1 = new String("Java"); String str2 = str1; if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They y p ( y are not equal"); q ) }

They are not equal

Not equal because str1 and str2 point to different String objects.

They are equal

It's equal here because str1 and str2 point to the same object.

4th Ed Chapter 5 - 437

4th Ed Chapter 5 - 438

73

UsingequalswithString
String str1 = new String("Java"); String str2 = new String("Java"); if (str1.equals(str2)) { System.out.println("They are equal"); } else { S t System.out.println("They t i tl ("Th are not t equal"); l") }

TheSemanticsof==

They are equal

It's equal here because str1 and str2 have the same sequence of characters.

4th Ed Chapter 5 - 439

4th Ed Chapter 5 - 440

InCreatingStringObjects
int gradeLevel;

TheswitchStatement
gradeLevel = Integer.parseInt( JOptionPane.showInputDialog("Grade (Frosh1,Soph-2,...):" ) ); switch (gradeLevel) { case 1: System.out.print("Go to the Gymnasium"); break; case 2: System.out.print("Go to the Science Auditorium"); break; case 3: System.out.print("Go to Harris Hall Rm A3"); break; case 4: System.out.print("Go to Bolt Hall Rm 101"); break; } This statement is executed if the gradeLevel is equal to 1.

This statement is executed if the gradeLevel is equal to 4.

4th Ed Chapter 5 - 441

4th Ed Chapter 5 - 442

Syntax fortheswitchStatement switch ( <arithmetic expression> ) {


<case label 1> : <case body 1> <case label n> : <case body n> } Arithmetic Expression
switch ( gradeLevel break; case 2: System.out.print( "Go to the Science Auditorium" ); break; case 3: System.out.print( "Go to Harris Hall Rm A3" ); break; case 4: System.out.print( "Go to Bolt Hall Rm 101" ); break; } ) { case 1: System.out.print( "Go to the Gymnasium" );

switchWithNobreakStatements
true
x = 10;

switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; }


Case Body

N == 1?

false
N == 2?

true
x = 20;

Case Label

false
N == 3?

true
x = 30;

false

4th Ed Chapter 5 - 443

4th Ed Chapter 5 - 444

74

switchWithbreakStatements
switch ( N ) { case 1: x = 10; break; case 2: x = 20; break; case 3: x = 30; break; }
N == 3? N == 1?

switchWiththedefaultBlock
switch (ranking) { case 10: case 9: 8: System.out.print("Master"); break; case case case case 7: 6 System.out.print("Journeyman"); 6: break; 5: 4: System.out.print("Apprentice"); break; default: System.out.print("Input error: Invalid Data"); break; } case

true
x = 10; break;

false
N == 2?

true
x = 20; break;

false true

x = 30; break;

false

4th Ed Chapter 5 - 445

4th Ed Chapter 5 - 446

Chapter6

Objectives
Afteryouhavereadandstudiedthischapter,youshouldbeableto
Implementrepetitioncontrolinaprogramusingwhilestatements. Implementrepetitioncontrolinaprogramusingdowhile statements. Implementagenericloopandahalfrepetitioncontrolstatement Implementrepetitioncontrolinaprogramusingforstatements. Nestalooprepetitionstatementinsideanotherrepetition statement. Choosetheappropriaterepetitioncontrolstatementforagiven task PrompttheuserforayesnoreplyusingtheshowConfirmDialog methodofJOptionPane. (Optional)Writesimplerecursivemethods
Animated Version

RepetitionStatements

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 447

Definition
Repetitionstatementscontrolablockof codetobeexecutedforafixednumberof timesoruntilacertainconditionismet. Countcontrolledrepetitions terminatethe executionoftheblockafteritisexecuted forafixednumberoftimes. times Sentinelcontrolledrepetitions terminate theexecutionoftheblockafteroneofthe designatedvaluescalleda sentinel is encountered. Repetitionstatementsarecalledloop statements also.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 449

Thewhile Statement
int sum = 0, number = 1; while ( number <= 100 ) { sum } = sum + number; number = number + 1;
These statements are executed as long as number is less than or equal to 100.

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 450

75

Syntaxforthewhile Statement
while ( <boolean expression> ) <statement>
while ( sum
Statement (loop body)

ControlFlowofwhile
int sum = 0, number = 1

Boolean Expression
number <= 100 ?

true

number <= 100 = sum + number;

) {

false

sum = sum + number; number = number + 1;

number = number + 1; }
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 451

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 452

MoreExamples
1
int sum = 0, number = 1; while ( sum <= 1000000 ) { sum } = sum + number; number = number + 1; Keeps adding the numbers 1, 2, 3, until the sum becomes larger than 1,000,000.

FindingGCD

int product = 1, number = 1, count = 20, lastNumber; lastNumber = 2 * count - 1; while (number <= lastNumber) { product = product * number; number } = number + 2;

Computes the product of the first 20 odd integers.

Direct Approach

More Efficient Approach

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 453

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 454

Example:TestingInputData
String inputStr; int age; Priming Read inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); while (age < 0 || age > 130) { JOptionPane.showMessageDialog(null, "An invalid age was entered. Please try again."); inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); }

UsefulShorthandOperators
sum = sum + number;
is equivalent to

sum += number;

Operator += -= *= /= %=

Usage a += b; a -= b; a *= b; a /= b; a %= b;
The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Meaning a = a + b; a = a b; a = a * b; a = a / b; a = a % b;
4th Ed Chapter 6 - 456

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 455

76

WatchOutforPitfalls
1. Watchoutfortheoffbyoneerror(OBOE). 2. Makesuretheloopbodycontainsastatementthatwill eventuallycausethelooptoterminate. 3. Makesurethelooprepeatsexactlythecorrectnumberof times. 4. IfyouwanttoexecutetheloopbodyNtimes,then initializethecounterto0 andusethetestcondition counter<N orinitializethecounterto1 andusethetest conditioncounter<=N. 1

LoopPitfall 1
int product = 0; while ( product < 500000 ) { product = product * 5; }
Infinite Loops
Both loops will not terminate because the boolean expressions will never become false.

int count = 1; while ( count != 10 ) { count = count + 2; }

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 457

Overflow
1

LoopPitfall 2
float count = 0.0f; while ( count != 1.0f ) { count = count + 0.3333333f; } //seven 3s
Using Real Numbers
Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory.

Aninfiniteloopoftenresultsinanoverflow error. Anoverflowerror occurswhenyouattempt toassignavaluelargerthanthemaximum valuethevariablecanhold hold. InJava,anoverflowdoesnotcauseprogram termination.Withtypesfloat anddouble,a valuethatrepresentsinfinityisassignedtothe variable.Withtypeint,thevaluewraps aroundandbecomesanegativevalue.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 459

float count = 0.0f; while ( count != 1.0f ) { count = count + 0.33333333f; } //eight 3s

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 460

LoopPitfall 2a
int result = 0; double cnt = 1.0; while (cnt <= 10.0){ cnt += 1.0; result++; } System.out.println(result);

Goal:Executetheloopbody10times.
1
count = 1; while ( count < 10 ){ . . . count++; }

LoopPitfall 3
2
count = 1; while (count <= 10 ){ . . . count++; }

10
2
int result = 0; double cnt = 0.0; while (cnt <= 1.0){ cnt += 0.1; result++; } System.out.println(result);

Using Real Numbers


Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory.

count = 0; while (count <= 10 ){ . . . count++; }

count = 0; while (count < 10 ){ . . . count++; }

11
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 461

1 and 3 exhibit off-by-one error.


The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 462

77

Thedowhile Statement
int sum = 0, number = 1; do { sum += number; number++; } while ( sum <= 1000000 );
These statements are g as sum executed as long is less than or equal to 1,000,000.

Syntaxforthedowhile Statement
do <statement> while (<boolean expression>); do { sum += number; number++; }while (sum<=1000000);
Boolean Expression Statement (loop body)

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 463

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 464

ControlFlowofdowhile
int sum = 0, number = 1

LoopandaHalfRepetitionControl

Loopandahalfrepetitioncontrol canbeused totestaloopsterminatingconditioninthe middleoftheloopbody. Itisimplementedbyusingreservedwords while,if, andbreak.

sum += number; number++;

sum <= 1000000 ?

true

false
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 465 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 466

Example:LoopandaHalfControl

PitfallsforLoopandaHalfControl

String name; while (true){ name = JOptionPane.showInputDialog(null, ); "Your name"); if (name.length() > 0) break; JOptionPane.showMessageDialog(null, "Invalid Entry." + "You must enter at least one character.");

Beawareoftwoconcernswhenusingthe loopandahalfcontrol:
Thedangerofaninfiniteloop. Thebooleanexpressionofthewhile statementistrue,whichwillalwaysevaluatetotrue.Ifweforgetto includeanif statementtobreakoutoftheloop, loop itwillresultinan infiniteloop. Multipleexitpoints. Itispossible,althoughcomplex,towritea correctcontrolloopwithmultipleexitpoints(breaks).Itisgood practicetoenforcetheoneentryoneexitcontrol flow.

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 467

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 468

78

ConfirmationDialog
Aconfirmationdialogcanbeusedtoprompttheuserto determinewhethertocontinuearepetitionornot.
JOptionPane.showConfirmDialog(null, /*prompt*/ /*dialog / g title*/ / "Play Another Game?", "Confirmation", ,

Example:ConfirmationDialog
boolean keepPlaying = true; int selection; while (keepPlaying){ //code to play one game comes here // . . . selection l ti = JO JOptionPane.showConfirmDialog( ti P h C fi Di l ( null, "Play Another Game?", "Confirmation", JOptionPane.YES_NO_OPTION); keepPlaying=(selection== JOptionPane.YES_OPTION);

/*button options*/ JOptionPane.YES_NO_OPTION);

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 469

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 470

Thefor Statement
int i, sum = 0, number; for (i = 0; i < 20; i++) { number = scanner.nextInt( ); sum += number; }
These statements are executed for 20 times ( i = 0, 1, 2, , 19).

Syntaxforthefor Statement
for ( <initialization>; <boolean expression>; <increment> <statement> Boolean Expression )

Initialization

Increment

for (

i = 0

i < 20

i++

) { Statement (loop body)

number = scanner.nextInt(); sum += number; }

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 471

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 472

ControlFlowoffor
1
i = 0;

Morefor LoopExamples
for (int i = 0; i < 100; i += 5) i = 0, 5, 10, , 95

false

i < 20 ?

for (int j = 2; j < 40; j *= 2) j = 2, 4, 8, 16, 32

true
number = . . . ; sum += number;

3
i ++;

for (int k = 100; k > 0; k--) ) k = 100, 99, 98, 97, ..., 1

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 473

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 474

79

TheNestedforStatement
Nestingafor statementinsideanotherfor statementiscommonlyusedtechniquein programming. Letsgeneratethefollowingtableusingnested forstatement.
OUTER

GeneratingtheTable
int price; for (int width = 11; width <=20, width++){ for (int length = 5, length <=25, length+=5){
INNER R

price = width * length * 19; //$19 per sq sq. ft ft. System.out.print (" } //finished one row; move on to next row System.out.println(""); " + price);

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 475

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 476

FormattingOutput
Wecallthespaceoccupiedbyanoutputvaluethe field.The numberofcharactersallocatedtoafieldisthefieldwidth.The diagramshowsthefieldwidthof6. FromJava5.0,wecanusetheFormatter class.System.out (PrintStream)alsoincludestheformatmethod.

TheFormatterClass

WeusetheFormatter classtoformattheoutput. Firstwecreateaninstanceoftheclass


Formatter formatter = new Formatter(System.out);

Thenwecallitsformatmethod
int num = 467; formatter.format("%6d", num);

Thiswilloutputthevaluewiththefieldwidthof6.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 477 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 478

TheformatMethodofFormatter
Thegeneralsyntaxis
format(<control string>, <expr1>, <expr2>, . . . )

TheformatMethodofPrintStream
InsteadofusingtheFormatterclassdirectly,wecanachievethe sameresultbyusingtheformatmethodofPrintStream (System.out)
Formatter formatter = new Formatter(System.out); formatter.format("%6d", 498);

Example:
int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format("%3d + %3d = %5d", num1, num2, num3);

isequivalentto
System.out.format("%6d", 498);

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 479

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 6 - 480

80

ControlStrings
Integers
% <field width> d

EstimatingtheExecutionTime
Inmanysituations,wewouldliketoknow howlongittooktoexecuteapieceofcode. Forexample,
Executiontimeofaloopstatementthatfindsthe greatestcommondivisoroftwoverylarge numbers,or Executiontimeofaloopstatementtodisplayall primenumbersbetween1and100million

RealNumbers
% <field width> . <decimal places> f

Strings
% s

Forotherdatatypesandmoreformattingoptions,please consulttheJavaAPIfortheFormatterclass.

Executiontimecanbemeasuredeasilyby usingtheDateclass.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 481 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 482

UsingtheDateClass
Here'sonewaytomeasuretheexecutiontime
Date startTime = new Date(); //code you want to measure the execution time Date endTime = new Date(); long elapsedTimeInMilliSec = endTime.getTime() startTime.getTime();

Chapter7

DefiningYourOwnClasses Part2

Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 483 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 7 - 484

Objectives
Afteryouhavereadandstudiedthischapter,you shouldbeableto
Describehowobjectsarereturnedfrommethods Describehowthereservedwordthis isused Defineoverloadedmethodsandconstructors Defineclassmethodsandvariables Describehowtheargumentsarepassedtothe parametersusingthepassbyvaluescheme Documentclasseswithjavadoccomments Organizeclassesintoapackage

ReturninganObjectfromaMethod
Aswecanreturnaprimitivedatavaluefroma method,wecanreturnanobjectfroma methodalso. Wereturnanobjectfromamethod, method weare actuallyreturningareference(oranaddress) ofanobject.
Thismeanswearenotreturningacopyofan object,butonlythereferenceofthisobject
The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 486

81

SampleObjectReturningMethod
Here'sasamplemethodthatreturnsanobject:
public Fraction simplify( ) { F Fraction ti simp; i int num = getNumberator(); int denom = getDenominator(); int gcd = gcd(num, denom); simp = new Fraction(num/gcd, denom/gcd); } return simp;
Return an instance of the Fraction class Return type indicates the class of an object we're returning from the method.

ASampleCalltosimplify
public Fraction simplify( ) { f1 = new Fraction(24, 36); f2 = f1.simplify(); int num = getNumerator(); int denom = getDenominator(); int gcd = gcd(num, denom); Fraction simp = new Fraction(num/gcd, denom/gcd); } return simp;

f1 simp f2

: Fraction numerator 24 denominator 36

: Fraction numerator 2 denominator 3

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 487

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 488

ASampleCalltosimplify(cont'd)
public Fraction simplify( ) { f1 = new Fraction(24, 26); f2 = f1.simplify(); int num = getNumerator(); int denom = getDenominator(); int gcd = gcd(num, denom); Fraction simp = new Fraction(num/gcd, denom/gcd); return simp; }

ReservedWordthis
Thereservedwordthis iscalledaselfreferencingpointer becauseitreferstoanobjectfromtheobject'smethod.
: Object

f1 simp f2
this

: Fraction numerator 24 denominator 36

: Fraction numerator 2 denominator 3 The value of simp, which is a reference, is returned and assigned to f2.

The reserved word this can be used in three different ways. We will see all three uses in this chapter.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 489

4th Ed Chapter 7 - 490

TheUseofthis intheaddMethod
public Fraction add(Fraction frac) { int a, b, c, d; Fraction sum; a = this.getNumerator(); //get the receiving b = this.getDenominator(); //object's num and denom c = frac.getNumerator(); //get frac's num d = frac.getDenominator(); //and denom sum = new Fraction(a*d + b*c, b*d); return sum; }

f3=f1.add(f2)
Because f1 is the receiving object (we're calling f1's method), so the reserved word this is referring to f1.

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 491

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 492

82

f3=f2.add(f1)
This time, we're calling f2's method, so the reserved word this is referring to f2.

Usingthis toRefertoDataMembers
Inthepreviousexample,weshowedtheuseofthis tocallamethodofareceivingobject. Itcanbeusedtorefertoadatamemberaswell.
class Person { int age;

public void setAge(int val) { this.age = val; } . . . }

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 493

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 494

OverloadedMethods
Methodscansharethesamenameaslongas
theyhaveadifferentnumberofparameters(Rule1)or theirparametersareofdifferentdatatypeswhenthe numberofparametersisthesame(Rule2)
public void myMethod(int x, int y) { ... } public void myMethod(int x) { ... }

OverloadedConstructor
Thesamerulesapplyforoverloadedconstructors
thisishowwecandefinemorethanoneconstructorto aclass

public Person( ) { ... }

Rule 1

public Person(int age) { ... }

Rule 1

public void myMethod(double x) { ... } public void myMethod(int x) { ... }

public Pet(int age) { ... }

Rule 2

public Pet(String name) { ... }

Rule 2

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 495

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 496

Constructorsandthis
Tocalla constructor fromanother constructor ofthesame class,weuse thereserved wordthis.
public Fraction( ) { //creates 0/1 this(0, 1); } public Fraction(int number) { //creates number/1 this(number, 1); } public Fraction(Fraction frac) { //copy constructor this(frac.getNumerator(), frac.getDenominator()); } public Fraction(int num, int denom) { setNumerator(num); setDenominator(denom); }
The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

ClassMethods
Weusethereservedwordstatic todefinea classmethod.
public static int gcd(int m, int n) { //th code //the d i implementing l ti th the E Euclidean lid algorithm l ith } public static Fraction min(Fraction f1, Fraction f2) { //convert to decimals and then compare }

4th Ed Chapter 7 - 497

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 498

83

CallbyValueParameterPassing
Whenamethodiscalled,
thevalueoftheargumentispassedtothematchingparameter,and separatememoryspaceisallocatedtostorethisvalue.

CallbyValueExample
class Tester { public void myMethod(int one, double two ) { one = 25; two = 35.4; } }

Thiswayofpassingthevalueofargumentsiscalledapassby value orcallbyvalue scheme. Sinceseparatememoryspaceisallocatedforeachparameter duringtheexecutionofthemethod,


theparameterislocaltothemethod,andtherefore changesmadetotheparameterwillnotaffectthevalueofthe correspondingargument.

Tester tester; int x, y; tester = new Tester(); x = 10; y = 20; tester.myMethod(x, y); System.out.println(x + " " + y);

10 20
produces

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 499

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 500

MemoryAllocationforParameters

MemoryAllocationforParameters(cont'd)

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 501

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 502

ParameterPassing:KeyPoints
1. Argumentsarepassedtoamethodbyusingthepassby value scheme. 2. Argumentsarematchedtotheparametersfromlefttoright.Thedata typeofanargumentmustbeassignmentcompatible withthedata typeofthematchingparameter. 3. Thenumberofargumentsinthemethodcallmustmatchthenumber of fparametersinthe h method h ddefinition. d f 4. Parametersandargumentsdonothavetohavethesamename. 5. Localcopies,whicharedistinctfromarguments,arecreatedevenif theparametersandargumentssharethesamename. 6. Parametersareinputtoamethod,andtheyarelocaltothe method.Changesmadetotheparameterswillnotaffectthevalueof correspondingarguments.

OrganizingClassesintoaPackage
ForaclassAtouseclassB,theirbytecodefiles mustbelocatedinthesamedirectory.
Thisisnotpracticalifwewanttoreuse programmerdefinedclassesinmanydifferent programs

Thecorrectwaytoreuseprogrammerdefined classesfrommanydifferentprogramsisto placereusableclassesinapackage. Apackage isaJavaclasslibrary.


The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 7 - 504

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 503

84

CreatingaPackage
Thefollowingstepsillustratetheprocessof creatingapackagenamemyutil thatincludes theFraction class.
1.Includethestatement

UsingJavadocComments
Manyoftheprogrammerdefined classeswedesignare intendedtobeusedbyotherprogrammers.
Itis,therefore,veryimportanttoprovidemeaningfuldocumentation totheclientprogrammerssotheycanunderstandhowtouseour classescorrectly.

package myutil;
asthefirststatementofthesourcefilefortheFractionclass. 2 Theclassdeclarationmustinclude thevisibilitymodifierpublicas 2.

public class Fraction { ... }


3.Createafoldernamedmyutil,thesamenameasthepackagename.InJava,the packagemusthaveaonetoone correspondence withthefolder. 4.PlacethemodifiedFractionclassintothemyutil folderandcompileit. 5.ModifytheCLASSPATHenvironment variabletoincludethefolderthatcontains themyutil folder.

Byaddingjavadoccommentstotheclasseswedesign,wecan provideaconsistentstyleofdocumentingtheclasses. Oncethejavadoccommentsareaddedtoaclass,wecan generateHTMLfilesfordocumentationbyusingthejavadoc command.


The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 505

4th Ed Chapter 7 - 506

javadocforFraction
Thisisaportionof theHTML documentationfor theFractionclass showninabrowser. ThisHTMLfileis producedby processingthe javadoccommentsin thesourcefileofthe Fractionclass.

javadocTags
Thejavadoccommentsbeginswith/**and endswith*/ Specialinformationsuchastheauthors, parameters, p ,returnvalues, ,andothersare indicatedbythe@marker
@param @author @return etc

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 507

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 508

Example:javadocSource
. . . /** * Returns the sum of this Fraction * and the parameter frac. The sum * returned is NOT simplified. * * @ @param f frac th the F Fraction ti t to add dd t to thi this * Fraction * * @return the sum of this and frac */ public Fraction add(Fraction frac) { ... } . . .

Example:javadocOutput

this javadoc will produce

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 509

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 7 - 510

85

javadocResources
Generalinformationonjavadocislocatedat
http://java.sun.com/j2se/javadoc

Chapter8

ExceptionsandAssertions

Detailedreferenceonhowtousejavadocon Windowsislocatedat
http://java.sun.com/j2se/1.5/docs/tooldocs/windows/javadoc.html
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 7 - 511

4th Ed Chapter 8 - 512

Objectives
Afteryouhavereadandstudiedthischapter, youshouldbeableto
Improvethereliabilityofcodebyincorporating exceptionhandlingandassertionmechanisms. Writemethodsthatpropagateexceptions. Implementthetrycatch blocksforcatchingand handlingexceptions. Writeprogrammerdefinedexceptionclasses. Distinguishthecheckedandunchecked,or runtime,exceptions.

Definition

Anexception representsanerrorcondition thatcanoccurduringthenormalcourseof programexecution. Whenanexceptionoccurs,oristhrown,the normalsequenceofflowisterminated.The exceptionhandlingroutineisthenexecuted; wesaythethrownexceptioniscaught.


The McGraw-Hill Companies, Inc. Permission required for reproduction or di l 4th Ed Chapter 8 - 514

NotCatchingExceptions
String inputStr; int age;

CatchinganException
inputStr = JOptionPane.showInputDialog(null, "Age:"); try {

inputStr = JOptionPane.showInputDialog(null, "Age:"); age = Integer.parseInt(inputStr);

try

age = Integer.parseInt(inputStr); } catch (NumberFormatException e){

Error message for invalid input


java.lang.NumberFormatException: ten at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at Ch8Sample1.main(Ch8Sample1.java:20)

catch
}

JOptionPane.showMessageDialog(null, "" + inputStr + + " is invalid\n" "Please enter digits only");

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 515

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 516

86

trycatch ControlFlow

GettingInformation

Therearetwomethodswecancalltoget informationaboutthethrownexception:
getMessage printStackTrace
try { . . . } catch (NumberFormatException e){ System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); }
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 517

4th Ed Chapter 8 - 518

Multiplecatch Blocks
Asingletrycatchstatementcanincludemultiplecatchblocks, oneforeachtypeofexception.
try { . . . age = Integer.parseInt(inputStr); . . . val = cal.get(id); //cal is a GregorianCalendar . . . } catch (NumberFormatException e){ . . . } catch (ArrayIndexOutOfBoundsException e){ . . . }
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

Multiplecatch ControlFlow

4th Ed Chapter 8 - 519

4th Ed Chapter 8 - 520

Thefinally Block

trycatchfinally ControlFlow

Therearesituationswhereweneedtotake certainactionsregardlessofwhetheran exceptionisthrownornot. Weplacestatementsthatmustbeexecuted regardlessofexceptionsinthefinallyblock.

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 521

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 522

87

PropagatingExceptions
Insteadofcatchingathrownexceptionbyusingthetry catchstatement,wecanpropagatethethrownexception backtothecallerofourmethod. Themethodheaderincludesthereservedwordthrows.

ThrowingExceptions
Wecanwriteamethodthatthrowsanexceptiondirectly, i.e.,thismethodistheoriginoftheexception. Usethethrow reservedtocreateanewinstanceofthe Exceptionoritssubclasses. Themethodheaderincludesthereservedwordthrows.
public void doWork(int num) throws Exception { . . . if (num != val) throw new Exception("Invalid val"); . . . }

public int getAge( ) throws NumberFormatException { . . . int age = Integer.parseInt(inputStr); . . . return age; }

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 523

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 524

ExceptionThrower

TypesofExceptionThrowers

Whenamethodmaythrowanexception, eitherdirectlyorindirectly,wecallthe methodanexceptionthrower. Everyexceptionthrowermustbeoneoftwo types:


catcher. propagator.

Anexceptioncatcher isanexceptionthrower thatincludesamatchingcatch blockforthe thrownexception. Anexceptionpropagator doesnotcontaina matchingcatch block. Amethodmaybeacatcherofoneexception andapropagatorofanother.

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 525

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 526

SampleCallSequence

ExceptionTypes

Alltypesofthrownerrorsareinstancesofthe Throwable classoritssubclasses.


SeriouserrorsarerepresentedbyinstancesoftheError class oritssubclasses. Exceptionalcasesthatcommonapplicationsshouldhandle arerepresentedbyinstancesoftheException classorits subclasses.

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 527

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 528

88

ThrowableHierarchy

Checkedvs.Runtime

Thereareover60classesinthehierarchy. Therearetwotypesofexceptions:
Checked. Unchecked.

Acheckedexception isanexceptionthatis checkedatcompiletime. Allotherexceptionsareunchecked,or runtime,exceptions.Asthenamesuggests, theyaredetectedonlyatruntime.


The McGraw-Hill Companies, Inc. Permission required for reproduction or di l The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 529

4th Ed Chapter 8 - 530

DifferentHandlingRules

HandlingCheckedExceptions

Whencallingamethodthatcanthrow checkedexceptions
usethetrycatch statementandplacethecallin thetry block,or modifythemethodheadertoincludethe appropriatethrows clause.

Whencallingamethodthatcanthrow runtimeexceptions,itisoptionaltousethe trycatchstatementormodifythemethod headertoincludeathrowsclause.


The McGraw-Hill Companies, Inc. Permission required for reproduction or di l 4th Ed Chapter 8 - 531

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 532

HandlingRuntimeExceptions

ProgrammerDefinedExceptions
Usingthestandardexceptionclasses,wecanusethe getMessagemethodtoretrievetheerrormessage. Bydefiningourownexceptionclass,wecanpackmoreuseful information
forexample example,wemaydefineaOutOfStockexceptionclassandinclude informationsuchashowmanyitemstoorder

AgeInputExceptionisdefinedasasubclassofExceptionand includespublicmethodstoaccessthreepiecesofinformation itcarries:lowerandupperboundsofvalidageinputandthe (invalid)valueenteredbytheuser.

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 533

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 534

89

Assertions
Thesyntaxfortheassertstatementis assert <boolean expression>; where<boolean expression> representstheconditionthatmustbetrueif thecodeisworkingcorrectly. Iftheexpressionresultsinfalse,an AssertionError (asubclassofError)isthrown.
4th Ed Chapter 8 - 535

SampleUse#1
public double deposit(double amount) { double oldBalance = balance; balance += amount; assert balance > oldBalance; } public double withdraw(double amount) { double oldBalance = balance; balance -= amount; assert balance < oldBalance; }

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 536

SecondForm
Theassertstatementmayalsotaketheform:
assert <boolean expression>: <expression>;

SampleUse#2

public double deposit(double amount) { double oldBalance = balance; balance += + amount;

where<expression> representsthevaluepassed asanargumenttotheconstructorofthe AssertionError class.Thevalueservesasthe detailedmessageofathrownexception.


The McGraw-Hill Companies, Inc. Permission required for reproduction or di l 4th Ed Chapter 8 - 537

assert balance > oldBalance : "Serious Error balance did not " + " increase after deposit"; }

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 538

CompilingProgramswithAssertions

RunningProgramswithAssertions

BeforeJava2SDK1.4,thewordassertisa validnonreservedidentifier.Inversion1.4and after,thewordassert istreatedasaregular identifiertoensurecompatibility compatibility. Toenabletheassertionmechanism,compile thesourcefileusing


javac source 1.4 <source file>
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l 4th Ed Chapter 8 - 539

Toruntheprogramwithassertionsenabled, use
java ea <main class> j

Iftheea optionisnotprovided,theprogram isexecutedwithoutcheckingassertions.

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 540

90

DifferentUsesofAssertions

Chapter9

Preconditionassertions checkforacondition thatmustbetruebeforeexecutingamethod. Postconditionassertions checkconditionsthat mustbetrueafteramethodisexecuted executed. Acontrolflowinvariant isathirdtypeof assertionthatisusedtoassertthecontrol mustflowtoparticularcases.

CharactersandStrings

The McGraw-Hill Companies, Inc. Permission required for reproduction or di l

4th Ed Chapter 8 - 541

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 542

Objectives
Afteryouhavereadandstudiedthischapter, youshouldbeableto
Declareandmanipulatedataofthechardatatype. WritestringprocessingprogramusingString, StringBuilder andStringBufferobjects. StringBuilder, objects Differentiatethethreestringclassesandusethe correctclassforagiventask. Specifyregularexpressionsforsearchingapattern inastring. UsethePatternandMatcherclasses. ComparetheStringobjectscorrectly.

Characters

InJava,singlecharactersarerepresented usingthedatatypechar. Characterconstantsarewrittenassymbols enclosedinsinglequotes. Charactersarestoredinacomputer memoryusingsomeform f of fencoding. d ASCII,whichstandsforAmericanStandard CodeforInformationInterchange,isoneof thedocumentcodingschemeswidelyused today. JavausesUnicode,whichincludesASCII,for representingchar constants.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 544

ASCIIEncoding
9

UnicodeEncoding

70

For example, character 'O' is 79 (row value 70 + col value 9 = 79).

TheUnicodeWorldwideCharacterStandard (Unicode)supportstheinterchange,processing, anddisplayofthewrittentextsofdiverse languages. JavausestheUnicodestandardforrepresenting char constants.


char ch1 = 'X'; System.out.println(ch1); System.out.println( (int) ch1);

X 88

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 545

91

CharacterProcessing
char ch1, ch2 = X; Declaration and initialization

Strings

System.out.print("ASCII code of character X is " + (int) 'X' ); System.out.print("Character with ASCII code 88 is " + (char)88 ); Type conversion between int and char.

A < c

This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99.

Astring isasequenceofcharactersthatis treatedasasinglevalue. InstancesoftheString classareusedto representstringsinJava Java. Wecanaccessindividualcharactersofastring bycallingthecharAtmethodoftheString object.

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 547

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 548

AccessingIndividualElements
IndividualcharactersinaStringaccessedwiththecharAt method.
String name = "Sumatra";
char String int int

Example:CountingVowels
letter; name vowelCount = JOptionPane.showInputDialog(null,"Your name:"); = 0; Heres the code to count the number of vowels in the input g string. numberOfCharacters = name.length();

for (int i = 0; i < numberOfCharacters; i++) { letter = name.charAt(i);

0
S

1
u

2
m

3
a

4
t

5
r

6
a

if (

l tt letter == 'a' ' ' || letter l tt == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) {

name
This variable refers to the whole string.

name.charAt( 3 )
The method returns the character at position # 3. }

vowelCount++; } System.out.print(name + ", your name has " + vowelCount + " vowels");
The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 549

4th Ed Chapter 9 - 550

Example:CountingJava
int boolean String javaCount repeat word; = 0; = true; Continue reading words and count how many times the word Java occurs in the input, ignoring the case.

OtherUsefulStringOperators
Method compareTo substring trim valueOf startsWith endsWith Meaning
Compares the two strings. str1.compareTo( str2 ) Extracts the a substring from a string. str1.substring( 1, 4 ) Removes the leading and trailing spaces. str1 trim( ) str1.trim( Converts a given primitive data value to a string. String.valueOf( 123.4565 ) Returns true if a string starts with a specified prefix string. str1.startsWith( str2 ) Returns true if a string ends with a specified suffix string. str1.endsWith( str2 )

while ( repeat ) {

word = JOptionPane.showInputDialog(null,"Next word:"); if ( word.equals("STOP") ) repeat = false; { Notice how the comparison is done. We are not using the == operator.

} else if ( word.equalsIgnoreCase("Java") ) { javaCount++; } }

See the String class documentation for details.


The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 551 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 552

92

PatternExample
Supposestudentsareassignedathreedigitcode:
Thefirstdigitrepresentsthemajor(5indicatescomputerscience); Theseconddigitrepresentseitherinstate(1),outofstate(2),orforeign (3); Thethirddigitindicatescampushousing:
Oncampusdormsarenumbered 17. Students d l livingoff ffcampusarerepresented d by b the h digit d 8. The 3-digit pattern to represent computer science majors living on-campus is

RegularExpressions

Thepatterniscalledaregularexpression. Rules
Thebrackets[] representchoices Theasterisksymbol* meanszeroormore occurrences. Theplussymbol+ meansoneormoreoccurrences. Thehatsymbol^ meansnegation. Thehyphen meansranges. Theparentheses() andtheverticalbar| meana rangeofchoicesformultiplecharacters.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 554

5[123][1-7]
first character is 5 second character is 1, 2, or 3 third character is any digit between 1 and 7
4th Ed Chapter 9 - 553

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

RegularExpressionExamples
Expression
[013] [0-9][0-9] [0-9&&[^4567]] [a-z0-9] [a-zA-Z][a-zA-Z09_$]*

ThereplaceAllMethod
ThereplaceAll methodreplacesalloccurrences ofasubstringthatmatchesagivenregular expressionwithagivenreplacementstring.
Replace all vowels with the symbol @ String originalText, modifiedText; originalText = ...; //assign string

Description
A single digit 0, 1, or 3. Any two-digit number from 00 to 99. A single digit that is 0, 1, 2, 3, 8, or 9. A single character that is either a g lowercase letter or a digit. A valid Java identifier consisting of alphanumeric characters, underscores, and dollar signs, with the first character being an alphabet.

[wb](ad|eed)

Matches wad, weed, bad, and beed. x is a single digit.

(AZ|CA|CO)[0-9][0-9] Matches AZxx,CAxx, and COxx, where

modifiedText = originalText.replaceAll("[aeiou]","@");

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 555

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 556

ThePattern andMatcher Classes

Thecompile Method
Thecompile methodofthePatternclass convertsthestatedregularexpressiontoan internalformattocarryoutthepatternmatching operation. Thisconversioniscarriedouteverytimethe matches methodoftheStringclassisexecuted, soitismoreefficienttousethecompilemethod whenwesearchforthesamepatternmultiple times. Seethesampleprograms Ch9MatchJavaIdentifier2andCh9PMCountJava
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 558

Thematches andreplaceAll methodsoftheStringclassare shorthandforusingthePattern andMatcher classesfromthe java.util.regex package. IfstrandregexareStringobjects,then


str.matches(regex); g

isequivalentto
Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); matcher.matches();

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 557

93

Thefind Method
Thefind methodisanotherpowerfulmethodof theMatcher class.
Itsearchesforthenextsequenceinastringthat matchesthepattern,andreturnstrueifthepatternis found. found

TheStringClassisImmutable

InJavaaStringobjectisimmutable
ThismeansonceaStringobjectiscreated,it cannotbechanged,suchasreplacingacharacter withanothercharacterorremovingacharacter TheStringmethodswehaveusedsofardonot changetheoriginalstring.Theycreatedanew stringfromtheoriginal.Forexample,substring createsanewstringfromagivenstring.

Whenamatcherfindsamatchingsequenceof characters,wecanquerythelocationofthe sequencebyusingthestart andend methods. SeeCh9PMCountJava2


The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 559

TheStringclassisdefinedinthismannerfor efficiencyreason.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 560

EffectofImmutability

TheStringBuffer Class

We can do this because String objects are immutable.

Inmanystringprocessingapplications,we wouldliketochangethecontentsofastring. Inotherwords,wewantittobemutable. Manipulatingthecontentofastring string,suchas replacingacharacter,appendingastringwith anotherstring,deletingaportionofastring, andsoon,maybeaccomplishedbyusingthe StringBuffer class.
4th Ed Chapter 9 - 561 The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 562

The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

StringBufferExample
word word
char

SampleProcessing
ReplaceallvowelsinthesentencewithX.
letter; inSentence = JOptionPane.showInputDialog(null, "Sentence:"); = new StringBuffer(inSentence); String : StringBuffer StringBuffer tempStringBuffer int

Changing a string Java to Diva

: StringBuffer

numberOfCharacters = tempStringBuffer.length();

Java

Diva

for (int index = 0; index < numberOfCharacters; index++) { letter = tempStringBuffer.charAt(index); if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' ||

Before

After
} }

letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { tempStringBuffer.setCharAt(index,'X');

StringBuffer word = new StringBuffer("Java"); word.setCharAt(0, 'D'); word.setCharAt(1, 'i');


The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

JOptionPane.showMessageDialog(null, tempStringBuffer );
The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

4th Ed Chapter 9 - 563

4th Ed Chapter 9 - 564

94

Theappend andinsert Methods


Weusetheappend methodtoappenda StringorStringBufferobjecttotheendofa StringBufferobject.
Themethodcanalsotakeanargumentofthe primitivedatatype. Anyprimitivedatatypeargumentisconvertedto astringbeforeitisappendedtoaStringBuffer object.

TheStringBuilderClass
ThisclassisnewtoJava5.0(SDK1.5) TheclassisaddedtothenewestversionofJavatoimprove theperformanceoftheStringBufferclass. StringBufferandStringBuildersupportexactlythesamesetof methods sotheyareinterchangeable methods, interchangeable. ThereareadvancedcaseswherewemustuseStringBuffer, butallsampleapplicationsinthebook,StringBuildercanbe used. Sincetheperformanceisnotourmainconcernandthatthe StringBufferclassisusableforallversionsofJava,wewilluse StringBufferonlyinthisbook.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 566

Wecaninsertastringataspecifiedposition byusingtheinsert method.


The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 565

Chapter10

Objectives
Afteryouhavereadandstudiedthischapter,you shouldbeableto
Manipulateacollectionofdatavalues,usinganarray. Declareanduseanarrayofprimitivedatatypesin writingaprogram. Declareanduseanarrayofobjectsinwritinga program Defineamethodthatacceptsanarrayasits parameterandamethodthatreturnsanarray Describehowatwodimensionalarrayisimplemented asanarrayofarrays Manipulateacollectionofobjects,usinglistsand maps
Animated Version 4th Ed Chapter 10 - 567

Arrays

ArrayBasics
Anarray isacollectionofdatavalues. Ifyourprogramneedstodealwith100 i integers, 500 00Accountobjects, bj 365 36 real l numbers,etc.,youwilluseanarray. InJava,anarrayisanindexedcollectionof datavaluesofthesametype.

ArraysofPrimitiveDataTypes
ArrayDeclaration
<data type> [ ] <variable> <data type> <variable>[ ] //variation 1 //variation 2

ArrayCreation
<variable> = new <data type> [ <size> ]

Example
Variation 1
double[ ] rainfall; rainfall = new double[12]; rainfall = new double[12];

Variation 2
double rainfall [ ];

An array is like an object!


4th Ed Chapter 10 - 569 4th Ed Chapter 10 - 570

95

AccessingIndividualElements
Individualelementsinanarrayaccessedwiththeindexed expression.
double[] rainfall = new double[12];

ArrayProcessing Sample1
double[] rainfall = new double[12]; double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showInputDialog(null,
The public constant length returns the capacity of an array.

rainfall

10

11

The index of the first position in an array is 0.

rainfall[2]

This indexed expression refers to the element at position #2

) ); }

"Rainfall for month " + (i+1)

sum += rainfall[i]; annualAverage = sum / rainfall.length;

4th Ed Chapter 10 - 571

4th Ed Chapter 10 - 572

ArrayProcessing Sample2
double[] rainfall = new double[12]; String[] monthName = new String[12]; monthName[0] = "January"; monthName[1] = "February"; double annualAverage, sum = 0.0;
The same pattern for the remaining ten months.

ArrayProcessing Sample3
Computetheaveragerainfallforeachquarter.
//assume rainfall is declared and initialized properly double[] quarterAverage = new double[4]; for (int i = 0; i < 4; i++) { sum = 0; for (int j = 0; j < 3; j++) { sum += rainfall[3*i + j]; } quarterAverage[i] = sum / 3.0; } //Quarter (i+1) average //compute the sum of //one quarter

for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for " + monthName[i] )); sum += rainfall[i]; } annualAverage = sum / rainfall.length;
The actual month name instead of a number.

4th Ed Chapter 10 - 573

4th Ed Chapter 10 - 574

ArrayInitialization
Likeotherdatatypes,itispossibletodeclare andinitializeanarrayatthesametime.
int[] number = { 2, 4, 6, 8 }; double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2, 9.00, 3.123, 22.084, 18.08 }; String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

VariablesizeDeclaration
InJava,wearenotlimitedtofixedsizearray declaration. Thefollowingcodepromptstheuserforthesizeof anarrayanddeclaresanarrayofdesignatedsize:
i t size; int i int[] number; size= Integer.parseInt(JOptionPane.showInputDialog (null, "Size of an array:")); number = new int[size];

number.length samplingData.length monthName.length

4 9 12
4th Ed Chapter 10 - 575

4th Ed Chapter 10 - 576

96

ArraysofObjects
InJava,inadditiontoarraysofprimitivedata types,wecandeclarearraysofobjects Anarrayofprimitivedataisapowerfultool,but anarrayofobjectsisevenmorepowerful. Theuseofanarrayofobjectsallowsusto modeltheapplicationmorecleanlyand logically.

ThePersonClass
WewillusePersonobjectstoillustratetheuseofanarrayof objects.
Person latte; latte = new Person( ); latte.setName("Ms. Latte"); latte.setAge(20); latte.setGender('F'); System.out.println( "Name: " + latte.getName() System.out.println( "Age : " + latte.getAge() ); );

The Person class supports the set methods and get methods.

System.out.println( "Sex : " + latte.getGender() );

4th Ed Chapter 10 - 577

4th Ed Chapter 10 - 578

CreatinganObjectArray 1
Code

CreatinganObjectArray 2
Code
Only the name myPerson is declared, no array is allocated yet. Person[ ] myPerson; Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created.

Person[ ]

myPerson;

myPerson = new Person[20]; myPerson[0] = new Person( );

myPerson = new Person[20]; myPerson[0] = new Person( );

myPerson

myPerson myPers on 0 1 2 3 4 16 17 18 19

State of Memory

State of Memory

After A is executed
4th Ed Chapter 10 - 579

After B is executed
4th Ed Chapter 10 - 580

CreatinganObjectArray 3
Code
Person[ ] myPerson; One Person object is created and the reference to this object is placed in position 0.

PersonArrayProcessing Sample1
CreatePerson objectsandsetupthemyPerson array.
String int char name, inpStr; age; gender;

myPerson = new Person[20];

myPerson[0] = new Person( );

myPerson myPers on 0 State of Memory 1 2 3 4 16 17 18 19

for (int i = 0; i < myPerson.length; i++) { name age = inputBox.getString("Enter name:"); = inputBox.getInteger("Enter i ( age:"); ) //read in data values

inpStr = inputBox.getString("Enter gender:"); gender = inpStr.charAt(0); myPerson[i] = new Person( ); //create a new Person and assign values ); );

Person

myPerson[i].setName myPerson[i].setAge

( name ( age

After C is executed
4th Ed Chapter 10 - 581

myPerson[i].setGender( gender ); }

4th Ed Chapter 10 - 582

97

Findtheyoungestandoldestpersons.
int int minIdx = 0; maxIdx = 0; //index to the youngest myPerson //index to the oldest myPerson

PersonArrayProcessing Sample2

ObjectDeletion Approach1
int delIdx = 1;

myPerson[delIdx] = null;

Delete Person B by setting the reference in position 1 to null.

for (int i = 1; i < myPerson.length; i++) { if ( myPerson[i].getAge() < myPerson[minIdx].getAge() ) { minIdx = i; // //found a younger myPerson

myPerson 0 1 2 3

myPerson 0 1 2 3

} else if (myPerson[i].getAge() > myPerson[maxIdx].getAge() ) { maxIdx } } //myPerson[minIdx] is the youngest and myPerson[maxIdx] is the oldest = i; //found an older myPerson

Before A is executed
4th Ed Chapter 10 - 583

After A is executed
4th Ed Chapter 10 - 584

ObjectDeletion Approach2
int delIdx = 1, last = 3;

myPerson[delIdx] = myPerson[last]; myPerson[last] = null;

Delete Person B by setting the reference in position 1 to the last person.

Searchingforaparticularperson.Approach2Deletionisused.
int i = 0; while ( myPerson[i] != null && !myPerson[i].getName().equals("Latte") ) {

PersonArrayProcessing Sample3

myPerson 0 1 2 3

myPerson 0 1 2 3

i++; } if ( myPerson[i] == null ) { //not found - unsuccessful search System.out.println("Ms. Latte was not in the array"); } else { //found - successful search System.out.println("Found Ms. Latte at position " + i); }

Before A is executed

After A is executed
4th Ed Chapter 10 - 585

4th Ed Chapter 10 - 586

Code

PassingArraystoMethods 1
A
public int searchMinimum(float[] number)) {

Code

PassingArraystoMethods 2
public int searchMinimum(float[] number)) {

minOne = searchMinimum(arrayOne);

minOne = searchMinimum(arrayOne);

At

A before searchMinimum
A. Local variable
number does not exist before the method execution

The address is copied at B


arrayOne number
B. The value of the
argument, which is an address, is copied to the parameter.

arrayOne

State of Memory
4th Ed Chapter 10 - 587

State of Memory
4th Ed Chapter 10 - 588

98

Code

PassingArraystoMethods 3
public int searchMinimum(float[] number)) {

Code C

PassingArraystoMethods 4
public int searchMinimum(float[] number)) { }

minOne = searchMinimum(arrayOne);

minOne = searchMinimum(arrayOne);

Whil at While t C
arrayOne

inside i id the th method th d


number
C. The array is
accessed via number inside the method.

hMi i At D after searchMinimum


arrayOne number
D. The parameter is
erased. The argument still points to the same object.

State of Memory
4th Ed Chapter 10 - 589

State of Memory
4th Ed Chapter 10 - 590

TwoDimensionalArrays
Twodimensionalarraysareusefulinrepresentingtabularinformation.

DeclaringandCreatinga2DArray

Declaration
<data type> [][] <variable> <data type> <variable>[][] //variation 1 //variation 2

Creation
<variable> = new <data type> [ <size1> ][ <size2> ]
payScaleTable

Example
double[][] payScaleTable; payScaleTable = new double[4][5];

0 0 1 2 3
4th Ed Chapter 10 - 591

4th Ed Chapter 10 - 592

AccessinganElement
Anelementinatwodimensionalarrayis accessedbyitsrowandcolumnindex.

Sample2DArrayProcessing
Findtheaverageofeachrow.
double[ ] average = { 0.0, 0.0, 0.0, 0.0 }; for (int i = 0; i < payScaleTable.length; i++) { for (int j = 0; j < payScaleTable[i].length; j++) { average[i] += payScaleTable[i][j]; } average[i] = average[i] / payScaleTable[i].length; }

4th Ed Chapter 10 - 593

4th Ed Chapter 10 - 594

99

JavaImplementationof2DArrays

TwoDimensionalArrays

Thesamplearraycreation
payScaleTable = new double[4][5];

Subarrays maybedifferentlengths. Executing


triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1];

isreallyashorthandfor
payScaleTable = new double [4][ ]; payScaleTable[0] payScaleTable[1] payScaleTable[2] payScaleTable[3] = = = = new new new new double double double double [5]; [5]; [5]; [5];

resultsinanarray ythatlookslike:

4th Ed Chapter 10 - 596

ListsandMaps

JavaInterface

Thejava.util standardpackagecontains differenttypesofclassesformaintaininga collectionofobjects. Theseclassesarecollectivelyreferredtoas theJavaCollectionFramework(JCF). JCFincludesclassesthatmaintaincollections ofobjectsassets,lists,ormaps.

AJavainterfacedefinesonlythebehaviorof objects
Itincludesonlypublicmethodswithnomethodbodies. Itdoesnotincludeanydatamembersexceptpublic constants NoinstancesofaJavainterfacecanbecreated

4th Ed Chapter 10 - 597

4th Ed Chapter 10 - 598

JCFLists

ListMethods
Herearefiveofthe25listmethods:
boolean add void Object clear get ( Object o ) ( ( int idx ) ) ) )
Adds an object o to the list Clears this list, list i.e., i e make the list empty Returns the element at position idx

JCFincludestheList interfacethatsupports methodstomaintainacollectionofobjects asalinearlist L = (l0, l1, l2, . . . , lN) Wecanaddto,removefrom,andretrieve objectsinagivenlist. Alistdoesnothaveasetlimittothe numberofobjectswecanaddtoit.
4th Ed Chapter 10 - 599

boolean remove ( int idx int size (

Removes the element at position idx Returns the number of elements in the list

4th Ed Chapter 10 - 600

100

UsingLists

SampleListUsage
Here'sanexampleofmanipulatingalist:
import java.util.*; List Person friends; myPerson;

Tousealistinaprogram,wemustcreatean instanceofaclassthatimplementstheList interface. TwoclassesthatimplementtheList interface:


ArrayList LinkedList Li k dLi

friends = new ArrayList( ); myPerson = new Person("jane", 10, 'F'); friends.add( myPerson ); myPerson = new Person("jack", friends.add( myPerson ); Person p = (Person) friends.get( 1 ); 6, 'M');

TheArrayList classusesanarraytomanage data. TheLinkedList classusesatechniquecalled linkednoderepresentation.


4th Ed Chapter 10 - 601

4th Ed Chapter 10 - 602

JCFMaps

MapMethods
Herearefiveofthe14listmethods:
void clear ( )
Clears this list, i.e., make the map empty

JCFincludestheMap interfacethatsupports methodstomaintainacollectionofobjects(key, value)pairscalledmapentries.


key value

boolean containsKey ( Object key )

k0 k1
. . .

v0 v1
. . .

one entry

Returns true if the map contains an entry with a given key

Object

put (Object key, Object value) )

Adds the given (key, value) entry to the map

boolean remove ( Object key int size ( )

Removes the entry with the given key from the map Returns the number of elements in the map
4th Ed Chapter 10 - 603 4th Ed Chapter 10 - 604

kn

vn

UsingMaps

Touseamapinaprogram,wemustcreate aninstanceofaclassthatimplementsthe Mapinterface. TwoclassesthatimplementtheMap interface: f


HashMap TreeMap

Here'sanexampleofmanipulatingamap:
import java.util.*; Map catalog;

SampleMapUsage

catalog = new TreeMap( ); catalog.put("CS101", catalog.put( CS101 , "Intro Intro Java Programming"); Programming ); catalog.put("CS301", "Database Design"); catalog.put("CS413", "Software Design for Mobile Devices"); if (catalog.containsKey("CS101")) { System.out.println("We teach Java this semester"); } else { System.out.println("No Java courses this semester");

}
4th Ed Chapter 10 - 605

101

Inthislectureyouwilllearn
DatabaseProgramming WithJava
DrStuartKerrigan
ThecomponentsoftheJDBCinterfacetoDBMSs HowtoconnecttoadatabasefromJava HowtosendSQLstatementsfromJavatoaDBMS TheconceptsofResultSetobjectandaCursor HowtonavigateandupdateaResultSetfromJava

608

JDBC
JDBCistheJavaDatabaseConnectivityAPI
AllowsJavaprogramtoaccessdatastoredintabular format,suchasinRDBMSandspreadsheets. DBdriverwrittenbytheDBvendorandimplemented asaclasswhichisloadedpriortousingtheJDBC methodsitprovides. Driverandsupportingclassesandinformation typicallypackagedinjarfile. MySQL Connector/J

TheJDBCProgrammingModel
TheJDBCusesaclientserver programmingmodel:
Clientmakesaconnectiontothe DB(theserver) ClientsendsSQLstatement(s)to theDB Manipulatedatabasemetadata DBsendsbackaResultSet ClientprocessesResultSet ClientdisconnectsfromtheDB

Pointstonote:
ResultSetincludesqueryresults andmetadata JDBCthrowsanexception wheneverthere'sanerror
610

JDBCisthedriverforMySQL
609

UsingJDBC
ImportJDBClibrary
import java.sql.*;

WhatDoesTryMean?
Errorsalwaysoccurinsoftwareprograms. Databaseprogramsmaybecriticalapplications. Errorsshouldbecaughtandhandledgracefully. P Programs should h ldrecoverand dl leavethe h d database b inaconsistentstate. UseJavaexceptionhandlerstodetecterrors. ReadWuChapter8

DriverManager providesDBinterfacemethods MostJavaprogramsuseimporttoloadaclass WithJDBC,usuallyloaddriverclassatruntime:

import p java.lang.*; j g import java.sql.*; public static void main (String args[]) { try { // this loads & initialises the driver Class.forName("com.mysql.jdbc.Driver"); // now connect to DB ... } catch (ClassNotFoundException e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } }

611

612

102

MakingaJDBCODBC DatabaseConnection
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost/mydatabase", "yourusername", "yourpassword"); // make more calls to JDBC methods here... con.close();

StatementandResultSetObjects
Statement stmt = con.createStatement(); String sql = "SELECT * FROM Staff;"; ResultSet rs = stmt.executeQuery(sql); print_rs(rs); // shown later rs.close(); // free memory stmt close(); stmt.close();

Needtoputyourownusername(typicallyroot)and password(yourMySQLpassword)intothegetConnection method

CanpassanylegalSQLquerytoexecuteQuery() Here,rsholdstheentireresultstable(Staff)...

613

614

ResultSetsandCursors

ResultSetMetadata
The ResultSet object is a container for the results of a query (table): EachResultSetcontains:
NumberedFields(columns) Fieldnames&types (metadata) ACursor(currentrow)

Wecanfindthenumberofcolumns,thecolumnnames anddatatypes(REAL,CHAR,etc.)fromtheResultSet metadata:


ResultSetMetaData md = rs.getMetaData(); int num num_columns columns = md.getColumnCount(); for (int i=1; i<=num_columns; i++) {
System.out.println("Column Number = " + i); System.out.println("Column Name = " + md.getColumnLabel(i)); System.out.println("Column Type = " + md.getColumnTypeName(i));

First cursor position is BEFORE FIRST ROW Rows and columns COUNT FROM ONE
615

616

Example:PrintingaResultSet
Wecanmovethroughtherowsusingthenext()method:
privatevoidprint_rs(ResultSetrs)throws SQLException{
ResultSetMetaDatamd=rs.getMetaData(); intnum_columns =md.getColumnCount(); while(rs.next()){
Stringrow_buffer ff =""; for(inti=1;i<=num_columns;i++){ row_buffer+=row_buffer+""+rs.getString(i);

HandlingResultSetFieldTypes
ThereisagetfunctionforeachofthemainSQLdatatypes (eachneedsacolumnno.oracolumnname):
getString() getInt() getDouble() getDate() D () ingeneralgetxxxx()

} System.out.println(row_buffer);

} }

Todoarithmeticonfieldvalues,needtoextractinto appropriatetype:
doubleave=rs.getDouble("Rent")/rs.getInt("Rooms");

NoteuseofmetadataandgetString()method

617

618

103

Updatable&ScrollableCursors
Thereareseveraltypesofcursor.Thetypewegetis controlledbythecalltocreateStatement():
stmt=con.createStatement(intscrolling,intconcurrency);

ScrollableCursorMethodFunctions
Scrollablecursorshavearichsetofmethod functions:

Booleannext(),previous() voidabsolute(introw_num), voidrelative(introw_increment), Booleanfirst(),last() voidbeforeFirst(),afterLast()

scrolling:
ResultSet.TYPE_FORWARD_ONLY thedefault! ResultSet.TYPE_SCROLL_INSENSITIVE usethis ResultSet.TYPE_SCROLL_SENSITIVE advanced

concurrency:
ResultSet.CONCUR_READ_ONLY thedefault! ResultSet.CONCUR_UPDATABLE

Youcanalsoaskwherethecursoriscurrently positioned:
BooleanisFirst(),isLast() BooleanisBeforeFirst(),isAfterLast()

619

620

InsertingorDeletingRows
ForqueriesthatdonotreturnaResultSet,usethe executeUpdate()method:
Statement stmt = con.createStatement(); String sql = "DELETE FROM Client " + "WHERE ClientNo = " + "'CR56' " "'CR56';"; int num_rows = stmt.executeUpdate(sql);

UpdatinganExistingRow
Toupdatearow,firstgetitintotheResultSet:
Statement stmt = con.createStatement(); String code = "CR56"; String sql = "SELECT * FROM Client" +" WHERE ClientNo ="+ " '" + code + "'" + ";"; ResultSet rs = stmt.executeQuery(sql); rs.absolute(1); // move to first \& only row rs.updateDouble("MaxRent", 500.0); rs.updateString("PrefType", "House"); rs.updateRow(); rs.close();

If successful, get num_rows = 1 (no. rows changed) Coulduse"INSERTINTOClient..."inthesameway... Healthwarning:

TAKESPECIALCAREWITHSPACESANDQUOTES
621

Here,ResultSetmustcontaintheprimarykey why?
622

HandlingNULLs
TheJDBCAPIhandlesNULLsusingaspecial methodfunction:wasNull()
Haveto"get"afieldvalue,andthentestforNULL ...
String x = rs.getString( rs getString("City"); City ); if (rs.wasNull()) x = "NULL"; int i = rs.getInt("Rooms"); if (rs.wasNull()) i = -1; // or whatever

Summary

Programmingmodel: Client(Java)sendsSQLstringstoserver(DBMS) Server(DBMS)sendsaResultSet backtoclient... Programmingfeatures: JDBCisstronglytyped:getString(), getString() getInt()... getInt() JDBCthrowsexceptionswheneverthere'saerror Considertypeofcursor:scrollable/updateable? ResultSet rows&columnscountfromONE ResultSet cursorstartsBEFOREthefirstrow

Yourcodecanthentestforspecialvalue later...
623

624

104