Java Databases Stuff
Java Databases Stuff
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
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
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
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.
DatabaseAdvantages
consistentandstructuredmodelofdata efficientelectronicfilingcabinet:noneedto controldata ad dhoc h queries i easytoupdate,changestructure concurrency:sharingdata improvedsecurity
Themainidea
Modellingtheworld
My model model
applications
database
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
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)
loan-date
17
18
Objectives
CO7101:Java&DatabasesFor Bioinformatics
RelationalDatabases2: TheStoryofLarryTheLion Dr.StuartKerrigan
Theterminologyoftherelationalmodel
Candidate,primaryandforeignkeys
Howtouserelationstomodel
entities ii relationshipsbetweenentities
Integrityrulesforrelationalmodel Queries
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
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
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
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.
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
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
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)
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)
ABetterDefinitionofRelation
Givenarelationschema,arelation ortable definedforthatschemaisafinitesetoftuples suchthat:
Eachtuplecontainsasmanyvaluesasthereare attributenamesintherelationschema. Eachvalueisdrawnfromthedomainwithwhich itsattribute(column)typeisassociated. Recall:
ForeignKeys
Theremaybemorethanonecandidatekey Wemaychooseaparticularoneandcalledittheprimary key
45
46
Examples
Animal name Larry Ernie Sydney ... Keeper family weight age 4 3 6 lion 500 elephant 4000 snake 1000
RelationalIntegrity
Relationalintegrity isasetofruleswhich ensurethatthedataisaccurate Therulescontain:
Domainconstraints(wehavealreadymetthese constraints) Entityintegrityrule Referentialintegrityrule
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
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
CO7101Java&Databases
EntityRelationshipDiagrams Dr.StuartKerrigan
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)
63
64
Attributes
Anattribute isanabstractionofasingle characteristicorpropertyofanentityora relationshiptype Entitiesareidentifiedbytheirproperties,i.e. bysetsofvaluesheldbyattributes Attributedomainisasetofvaluesthatmaybe assignedtoanattribute
65
AttributeValuesforaCar
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
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
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..*
MembershipClass 3
Optionalbothsides:
Astudentneednotattendanylectures Alectureneednotbeattendedbyanystudents
Student 0..*
Attends
Strongvs.WeakEntityTypes
Strongentitytype:anentitytypethatisnot dependentontheexistenceofanotherentitytype foritsprimarykey
Forexample,Staff,Library_User, ... Hasitsownprimarykey
Lecture 0..*
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..*
91
92
Revision:ThecomponentsofaDB
CO7101Java&Databases
Normalization:WhenThereIs Something FishyInYourDatabases Dr.StuartKerrigan
CO7101 Java & Databases 93
Data
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
STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1
LECTURER Dr. Kerrigan Dr. Solanki Dr. Kerrigan Dr. Solanki Dr. Bell
TITLE Information Technology Information Technology Databases for Dummies Spreadsheets for Idiots
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
SUPPLIER ADDRESS 23 Main St. 59 High St. 5 High St. 23 Main St. 5 High St.
GOODS SUPPLIED 2 586 PCs 6 486 PCs 1 printer 4 586 PCs 2 486 PCs
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
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
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
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
ExampleofFD
A B
RealLifeExampleofFD
A B
StudentID
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
19
WhyisthisexampleNOTin1NF?
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
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
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
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
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
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
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."
STUDENT. No. COURSE 765432 CO1019 765432 CO1005 776829 CO1019 776829 CO1005 776829 Chem1
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)
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
RealLifeExampleofFD
A B
RealLifeExampleofFD
A B
StudentID
Student Name
StudentID
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]
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
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
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
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
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
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
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
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
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;
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
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
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
Dogollan Trinity
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);
RS
R-S
191
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
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
202
PreviouslyonCO1019:
CO7101:Java&DatabasesFor Bioinformatics
SQL3: Subqueries and Multiple Tables Dr.StuartKerrigan
CREATEtables,INSERTdataintotableandSELECTdataoutof table UseAggregatefunctions UPDATEdataandDELETEdatafromtable
ALLONONETABLEONLY!
CreateaUnionbetweentwoidenticalqueriesofdifferent tables
203
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!
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)
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
209
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)
(matching
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!!.
213
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
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
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;
219
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
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
223
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
225
PreviouslyonCO1019
CO7101:Java&DatabasesFor Bioinformatics
SQL4: ImplementingRelationshipsUsingKeys&UsingNatural Joins Dr.StuartKerrigan
Queriesinvolvingmultipletables Differenttypesofjoin
NaturalJoinuseskeysspecifiedintable
Relationships
1*relationships 11relationships **relationships
227
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;
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
1 2 3 4
SQLwillrejectoperationsthatwouldviolate referentialintegrity
237
PopulateTables
Room NameRoom
(Primary Key)
Guest Number
(ForeignKey)
UsingaNaturalJoin
SELECT RoomName, FirstName, LastName FROM Guest NATURAL JOIN Room;
1 1 2 3 4
1 2 3 4
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
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
1 1 2 3 4
1 2 3 4
RepopulateTables
Room
Room Name
(Primary Key)
Relationships
Last Name Hope Gall Example Running
Guest
Guest Number
(ForeignKey)
Guest Number
(Primary Key)
FirstName
1 2 3 4
1 2 3 4
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
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
1 2 3 4 NULL
1 2 3 4
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
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
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
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)
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
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)
1 2 3 3
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)
1 2 3 3
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
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;
StaffNo
SG37 SG5
Fname
Ann Susan
Staff3 Lname
Beech Brand
271
Position
Assistant Manager
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)
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';
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)
Materialisationmethodcancauseconsistencyproblems(storestemptable
279
280
Next
TheInternet(done) HTML(done) RelationalDatabases(done) MySQL y Q ( (done) ) PHP (combiningHTML&MySQL)
Chapter0
281
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
Input Devices
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
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
HighlevelLanguages
The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
Java
Javaisahighlevelobjectorientedlanguage developedbySunMicrosystems. Javascleandesignandwideavailabilitymake itanideallanguageforteachingthe fundamentalsofcomputerprogramming.
Chapter1
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.
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
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
current balance
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
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.
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
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.
ASampleInheritance
InheritanceHierarchy
Anexampleofinheritancehierarchyamong differenttypesofstudents.
Student
Graduate
Undergrad
Checking
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
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
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.
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
More Examples
myCust = new Customer( ); jon = new Student("John Java"); car1 = new Vehicle( );
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
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.
53
ExecutionFlow
Program Code State-of-Memory Diagram
myWindow
ProgramComponents
AJavaprogramiscomposedof
: JFrame width height title visible
JFrame myWindow
true
The diagram shows only four of the many data members of a JFrame object.
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 */ */
myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); } }
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 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
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
More Examples
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 Body y
myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); } }
/*
TemplateforSimpleJavaPrograms
Chapter 2 Sample Program: Displaying a Window
WhyUseStandardClasses
Comment Import Statements
Class Name
myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle("My First Java Program"); myWindow.setVisible(true); } }
Method Body
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");
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
2
Jon Java 2. A String object is created and the identifier name is set to refer to it.
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.
56
Examples:substring
String text = "Espresso";
Definition:length
AssumestrisaStringobjectandproperly initializedtoastring. str.length() willreturnthenumberof charactersinstr. Ifstris"programming" ,thenstr.length() will return11becausethereare11charactersin it. Theoriginalstringstr remainsunchanged.
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
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?"
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.
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
58
ManipulatingNumbers
InJava,toaddtwonumbersxandy,wewrite
x + y
Variables
Whenthedeclarationismade,memoryspace isallocatedtostorethevaluesofxandy. xandyarecalledvariables.Avariablehas threeproperties:
Amemorylocationtostorethevalue, Thetypeofdatastoredinthememorylocation,and Thenameusedtorefertothememorylocation.
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
Examples:
sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0;
59
ArithmeticOperators
Thefollowingtablesummarizesthearithmetic operatorsavailableinJava.
ArithmeticExpression
Howdoestheexpression
x + 3 * y
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.
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.
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.
constant.
literal constant.
PrimitiveDataDeclarationandAssignments
AssigningNumericalData
int number; number = 237; number = 35;
A. Variables are
allocated in memory.
number
35 237
A
int firstNumber, secondNumber; firstNumber = 234; B secondNumber = 87;
firstNumber secondNumber
A. The variable
A B C
is allocated in memory.
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
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.
A Variables are A.
allocated in memory.
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;
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);
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
62
StandardOutput
StandardOutputWindow
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
StandardInput
CommonScannerMethods:
Method
nextByte() nextDouble() nextFloat() nextInt() nextLong() nextShort() next()
Example
byteb=scanner.nextByte(); doubled=scanner.nextDouble(); floatf=scanner.nextFloat(); inti=scanner.nextInt(); longl=scanner.nextLong(); shorts=scanner.nextShort(); Stringstr=scanner.next();
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.
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
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.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."); } }
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
TheProgramStructureandSource Files
BicycleRegistration Bicycle
ClassDiagramforBicycle
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)
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 ;
65
MethodDeclaration
<modifier> } <return type> <method name> ( <parameters> ){ <statements>
Constructor
Modifier
Return Type yp
public
void
setOwnerName
String
name
) {
public }
Bicycle
) {
ownerName = name; }
Statements
ownerName = "Unassigned";
Statements
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
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
A parameter is a placeholder in the called method to hold the value of the passed argument.
66
MatchingArgumentsandParameters
MemoryAllocation
i k 5 14 20 i j x 5 14 20.0
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
Receiving Side
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
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
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
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
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
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
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.
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
Then Block
else
Else Block
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
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
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
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++;
studentAge < 10 ?
true
else if (num2 < 0) if (num3 < 0) negativeCount = 2; else negativeCount = 1; else if (num3 < 0) negativeCount = 1; else negativeCount = 0;
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");
BooleanOperators
SemanticsofBooleanOperators
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)
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
Can be used as
if (isValid(30)) { } else { }
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 ) }
Not equal because str1 and str2 point to different String objects.
It's equal here because str1 and str2 point to the same object.
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==
It's equal here because str1 and str2 have the same sequence of characters.
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.
switchWithNobreakStatements
true
x = 10;
N == 1?
false
N == 2?
true
x = 20;
Case Label
false
N == 3?
true
x = 30;
false
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
Chapter6
Objectives
Afteryouhavereadandstudiedthischapter,youshouldbeableto
Implementrepetitioncontrolinaprogramusingwhilestatements. Implementrepetitioncontrolinaprogramusingdowhile statements. Implementagenericloopandahalfrepetitioncontrolstatement Implementrepetitioncontrolinaprogramusingforstatements. Nestalooprepetitionstatementinsideanotherrepetition statement. Choosetheappropriaterepetitioncontrolstatementforagiven task PrompttheuserforayesnoreplyusingtheshowConfirmDialog methodofJOptionPane. (Optional)Writesimplerecursivemethods
Animated Version
RepetitionStatements
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.
75
Syntaxforthewhile Statement
while ( <boolean expression> ) <statement>
while ( sum
Statement (loop body)
ControlFlowofwhile
int sum = 0, number = 1
Boolean Expression
number <= 100 ?
true
) {
false
number = number + 1; }
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 451
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;
Direct Approach
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
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.
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
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);
11
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 6 - 461
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)
ControlFlowofdowhile
int sum = 0, number = 1
LoopandaHalfRepetitionControl
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.
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);
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++
ControlFlowoffor
1
i = 0;
Morefor LoopExamples
for (int i = 0; i < 100; i += 5) i = 0, 5, 10, , 95
false
i < 20 ?
true
number = . . . ; sum += number;
3
i ++;
for (int k = 100; k > 0; k--) ) k = 100, 99, 98, 97, ..., 1
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);
FormattingOutput
Wecallthespaceoccupiedbyanoutputvaluethe field.The numberofcharactersallocatedtoafieldisthefieldwidth.The diagramshowsthefieldwidthof6. FromJava5.0,wecanusetheFormatter class.System.out (PrintStream)alsoincludestheformatmethod.
TheFormatterClass
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);
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.
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
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 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.
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.
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;
OverloadedMethods
Methodscansharethesamenameaslongas
theyhaveadifferentnumberofparameters(Rule1)or theirparametersareofdifferentdatatypeswhenthe numberofparametersisthesame(Rule2)
public void myMethod(int x, int y) { ... } public void myMethod(int x) { ... }
OverloadedConstructor
Thesamerulesapplyforoverloadedconstructors
thisishowwecandefinemorethanoneconstructorto aclass
Rule 1
Rule 1
Rule 2
Rule 2
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 }
83
CallbyValueParameterPassing
Whenamethodiscalled,
thevalueoftheargumentispassedtothematchingparameter,and separatememoryspaceisallocatedtostorethisvalue.
CallbyValueExample
class Tester { public void myMethod(int one, double two ) { one = 25; two = 35.4; } }
Tester tester; int x, y; tester = new Tester(); x = 10; y = 20; tester.myMethod(x, y); System.out.println(x + " " + y);
10 20
produces
MemoryAllocationforParameters
MemoryAllocationforParameters(cont'd)
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
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.
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
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
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
Objectives
Afteryouhavereadandstudiedthischapter, youshouldbeableto
Improvethereliabilityofcodebyincorporating exceptionhandlingandassertionmechanisms. Writemethodsthatpropagateexceptions. Implementthetrycatch blocksforcatchingand handlingexceptions. Writeprogrammerdefinedexceptionclasses. Distinguishthecheckedandunchecked,or runtime,exceptions.
Definition
NotCatchingExceptions
String inputStr; int age;
CatchinganException
inputStr = JOptionPane.showInputDialog(null, "Age:"); try {
try
catch
}
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
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
Thefinally Block
trycatchfinally ControlFlow
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; }
ExceptionThrower
TypesofExceptionThrowers
Anexceptioncatcher isanexceptionthrower thatincludesamatchingcatch blockforthe thrownexception. Anexceptionpropagator doesnotcontaina matchingcatch block. Amethodmaybeacatcherofoneexception andapropagatorofanother.
SampleCallSequence
ExceptionTypes
88
ThrowableHierarchy
Checkedvs.Runtime
Thereareover60classesinthehierarchy. Therearetwotypesofexceptions:
Checked. Unchecked.
DifferentHandlingRules
HandlingCheckedExceptions
Whencallingamethodthatcanthrow checkedexceptions
usethetrycatch statementandplacethecallin thetry block,or modifythemethodheadertoincludethe appropriatethrows clause.
HandlingRuntimeExceptions
ProgrammerDefinedExceptions
Usingthestandardexceptionclasses,wecanusethe getMessagemethodtoretrievetheerrormessage. Bydefiningourownexceptionclass,wecanpackmoreuseful information
forexample example,wemaydefineaOutOfStockexceptionclassandinclude informationsuchashowmanyitemstoorder
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; }
SecondForm
Theassertstatementmayalsotaketheform:
assert <boolean expression>: <expression>;
SampleUse#2
assert balance > oldBalance : "Serious Error balance did not " + " increase after deposit"; }
CompilingProgramswithAssertions
RunningProgramswithAssertions
Toruntheprogramwithassertionsenabled, use
java ea <main class> j
90
DifferentUsesofAssertions
Chapter9
Preconditionassertions checkforacondition thatmustbetruebeforeexecutingamethod. Postconditionassertions checkconditionsthat mustbetrueafteramethodisexecuted executed. Acontrolflowinvariant isathirdtypeof assertionthatisusedtoassertthecontrol mustflowtoparticularcases.
CharactersandStrings
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
X 88
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.
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();
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.
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.
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
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)
modifiedText = originalText.replaceAll("[aeiou]","@");
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
isequivalentto
Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); matcher.matches();
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.
TheStringclassisdefinedinthismannerfor efficiencyreason.
The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4th Ed Chapter 9 - 560
EffectofImmutability
TheStringBuffer Class
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
StringBufferExample
word word
char
SampleProcessing
ReplaceallvowelsinthesentencewithX.
letter; inSentence = JOptionPane.showInputDialog(null, "Sentence:"); = new StringBuffer(inSentence); String : StringBuffer StringBuffer tempStringBuffer int
: 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');
JOptionPane.showMessageDialog(null, tempStringBuffer );
The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
94
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
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 [ ];
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
rainfall[2]
) ); }
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.
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];
4 9 12
4th Ed Chapter 10 - 575
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.
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
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;
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 ); }
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;
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;
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
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
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
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
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; }
99
JavaImplementationof2DArrays
TwoDimensionalArrays
Thesamplearraycreation
payScaleTable = new double[4][5];
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:
ListsandMaps
JavaInterface
AJavainterfacedefinesonlythebehaviorof objects
Itincludesonlypublicmethodswithnomethodbodies. Itdoesnotincludeanydatamembersexceptpublic constants NoinstancesofaJavainterfacecanbecreated
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
Removes the element at position idx Returns the number of elements in the list
100
UsingLists
SampleListUsage
Here'sanexampleofmanipulatingalist:
import java.util.*; List Person friends; myPerson;
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');
JCFMaps
MapMethods
Herearefiveofthe14listmethods:
void clear ( )
Clears this list, i.e., make the map empty
k0 k1
. . .
v0 v1
. . .
one entry
Object
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
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
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();
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)
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();
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