Date post: | 21-Oct-2015 |
Category: |
Documents |
Upload: | stuart-kerrigan |
View: | 61 times |
Download: | 0 times |
DEPARTMENT OF COMPUTER SCIENCE
CO7101 Java & Databases For Bioinformatics
Course Notes 2014
Dr. S. Kerrigan
Foreword These notes are to accompany the module CO7101. They contain material that goes beyond the core knowledge of this course. For more motivation and background please attend the lectures. These notes are detailed. Thus, while they should be useful and have been checked carefully, there may be some errors. Please do let me know about any typos or other mistakes which you find. If you have any other (constructive) comments, please tell me about them. If you are to do well in this course, YOU MUST ATTEND THE LECTURES. They will give you additional examples, highlight key issues which may not appear quite as important from the notes as in fact the issues are, and give guidance towards what you need to know for the examinations. You should note especially that with a course of this nature, notation, definitions and ideas can differ even among the experts. The lectures will clarify many of the more woolly areas. It is recommended you purchase the following books to accompany these notes:-
1. An Introduction to Object-Oriented Programming with Java, 5th Edition by C. Thomas Wu (Otani), Naval Postgraduate School
2. Database Systems: A Practical Approach to Design, Implementation and
Management, 5th Edition, Thomas M. Connolly, Carolyn E. Begg
1
CO7101: Java & Databases For Bioinformatics
Relational Databases 1:
CO7101: Java & Databases For Bionformatics
1
Relational Databases 1:
Dr. Stuart Kerrigan
Material in this Unit by Dr. Nick Measor, Dr. Stephan Reiff-Marganiec and Dr. Naila Rhaman
Before Databases: File‐Based Approach to Information Systems (up to 1980s)
A collection of application programs that perform
services for the end‐users such as answering queries and production of reports.
2
and production of reports.
Each program defines and manages its own data,
so we may have data redundancy, inconsistency
and duplication.
Library Example
3
Library needs to manage:
the book cataloguebook loansbook reservationsrecall of overdue loanscatalogue inquiriesmembership. . .
Traditional file approach
• Library‐user file:– information about each library user.
• Catalogue file:– information about books in the library.
4
• Loans file:– information about each book on loan and the person
who is borrowing the book.
• Reservations file:– information about each book reserved and the person
who is reserving the book.
The filesLibraryusers
Catalogue
5
Loans
Reservations
Example of file: The library users
D. Andrews 14 High Street Oadby Leicester LE2 5HE tel: 274 4893 loan-status: Adult
57-AD-97
d
6
Library- users
D. Andrews 14 High Street Oadby Leicester LE2 5HE tel: 274 4893 loan-status: Adult
57-AD-97
2
Traditional file‐based approach
ReservationInformation
LoanInformation
OverdueLetters
CatalogueInquiry
LoanProcess
ReservationProcess
OverdueLoans Process
CatalogueInquiryProcess
7
ProcessProcess Loans Processq yProcess
Reservationsfile
Cataloguefile
Library-usersfile
Loansfile
NOTE: The processes must relate data between the files when necessary
Another approach – a single file
Why not put all the information in a single table –such as an Excel spreadsheet?
8
Name Address Telephone Status Book title
Book author
ISBN Date borrowed
And so on with further cells supplying all the inform
Duplication of information in the single file approach
Name Address Telephone Status Book title Book author
ISBN Date borrowed
D. 14 High 274 4893 Adult Donatello Green 123- 12/04/
9
Andrews Street halgh 4567 2006
D. Andrews
14 High Street
274 4893 Adult War and Peace
Tolstoy 456-1234
18/05/2006
Summary of file‐based system disadvantages
• Separation of data
• Duplication of data: wasteful, loss of data integrity.
• Data dependence ‐ difficult to change the structure of data, unresponsive to updates, extensions, d l hi h d l
10
redevelopment: high development cost
• Incompatible file formats
• Fixed queries, difficult to do ad hoc queries
• Low reliability, security, integrity
The solution – use a database
Important points to remember:
A shared collection of logically related data
(and a description of this data) designed to
meet the information needs of an organisation.
11
• shared• collection• self‐describing• logically related:
– entities– attributes– relationships
Definition of DBMS
a DBMS provides the following facilities:
A software system that enables users to define, create and maintain the database and provides
a controlled access to this database.
12
• Data Definition Language: data types and structures
• Data Manipulation Language: query language (e.g. SQL)
• Controlled access to the database– a security system
– a concurrency control system
– an integrity system
– a recovery control system
3
Database Advantages
• consistent and structured model of data
• efficient electronic filing cabinet: no need to control data
d h i
13
• ad hoc queries
• easy to update, change structure
• concurrency: sharing data
• improved security
The main idea
14
Model the world
User’s model of a library
15
System rules
1. A copy of a book can only be lent to one person at a time.
2. A person may borrow several books at a time.
3. Each person has a status in the library which determines such things as loan period, max. books on loan, overdue fees.
Modelling the world
applications information available
h
modelMy model
16
database
databasedesign
datamodel
information desired
the same?
Start
Entity‐Relationship Model of the Library
CopyOf
Author
nameauthor-details
Writtenby
Catalogue
isbn
date 0..*0..*title
publisher
1
res-date
0..*
17
Book
copy#accession-date
CopyOf
0..*
Reserves0..*
Library-user
user#nameaddresstel
loan-date
IsonLoan
0..10..*
Status
idstatus-details
HasStatus
0..* 1
Implementer’s model of the
library
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#)
The relation schemas:
18
Catalogue(isbn, title, publisher, date)primary key: isbn
Reservation(user#, isbn, date )primary key: user#, isbnforeign key: user# references Library-user(user#)foreign key: isbn references Catalogue(isbn)
Written-by(isbn, name)primary key: isbn, nameforeign key: isbn references Catalogue(isbn)foreign key: name references Author(name)
Status(id, details )primary key: id
Author(name, details)primary key: name
4
CO7101: Java & Databases For Bioinformatics
Relational Databases 2:
CO7101: Java & Databases For Bionformatics
19
Relational Databases 2:
The Story of Larry The Lion
Dr. Stuart Kerrigan
Objectives
• The terminology of the relational model
– Candidate, primary and foreign keys
• How to use relations to model
i i– entities
– relationships between entities
• Integrity rules for relational model
• Queries
20
Definition of Data Model
There are three components of each data model:• a structural part — rules for constructing databases terminology
An integrated collection of concepts for describing data, relationships between data, and constraints on the data.
a structural part rules for constructing databases, terminology• a set of integrity rules to ensure data accuracy• a manipulative part — defines the type of operations that
are allowed on the database
There are object‐based, relational, and other data models. Here we consider the relational model.
21
Past and Present of RM
• The relational model was originally described by E.F. Codd in his 1970 paper
– “A relational model of data for large shared data banks’’
22
History
• Three projects that started it all in late 1970s– System R, by IBM in late 1970s
• Structured Query Language (SQL) developed
• commercial products: SQL/DS and ORACLE
– INGRES, Uni. of California at BerkeleyG S, U o a o a at e e ey• relational DBMS Ingres
– Peterlee Relational Test Vehicle, IBM UK• query processing, optimization, functional extensions
• Commercially available PC versions of RDBMSs– Access and FoxPro from Microsoft
– Paradox and Visual dBase from Borland
23
Entities
An entity is a
– thing
– object
concept– concept
in the real world
24
Can be distinguished from other objects.
5
Attributes
• An attribute is a property of an entity
• An object can be described by a set of properties:
O i l id tif bj t (k )– One may uniquely identify an object (key)
– Others may add (useful) information
25
Modelling Entities in the Real World
“entity”
26
representedby a name and
a set ofattributes
Terminology
• A set of entities of the same type is represented as a table (also called relation)
• Each row in the table represents an entity
h l ib• Each column represents an attribute
• An atomic place in a table is called a cell
27
Different Terminology
User Relational Model
Programmer
Table Relation Fileor
Array
Row Tuple Record
Column Attribute Field
28
A Relation About Film Stars
Starname yob sex country
29
Marlon Brando 1924 Male USAHarrison Ford 1942 Male USADustin Hoffman 1937 Male USARobert Redford 1937 Male USAMeryl Streep 1949 Female USA
Properties of Relations
• Relations have names
• Each cell of the relation contains one atomic value
• Each attribute (column) has a distinct name
• Values of attributes come from the same domain
• The order of attributes is irrelevant• The order of attributes is irrelevant
• The number of columns (attributes) is called degree
• Each tuple (row) is distinct
• The order of tuples is not significant, theoretically
• The number of rows (tuples) is called cardinality
30
6
Keys
31
uniquely identifies entity
a1 a3 a4a2
Identify?
What is meant by identify?
Real World a set of values will take you to a unique object (entity)
32
unique object (entity).
Model a set of values will take you to a unique row (tuple).
Really the same: an object in the real world is modelled by a row in a table.
Keys
identifies a unique row in a table Larry
33
key
identifies anobject in the world row is modelling
the object
Larry Lion
Superkeys
• A superkey is a set of one or more attributes that uniquely identifies an entity within a relation
• Superkeys always exist — just take all p y y jattributes
• For example, – name, weight and age in Animal
– family and food in Diet
– type in Food
34
Candidate Keys
Let R be a relation schema (relation name followed by a list of attribute names). A subset I of the attribute names of R is called a candidate key if:candidate key if:
– No two distinct tuples of the relation can take the same values on I (Uniqueness) (in other words, I is a superkey)
– No proper subset of I satisfies the above rule (Irreducibility)
35
Primary Keys
• The primary key is the candidate key that is selected to identify tuples uniquely within the relation
• Relationships between different keys:Relationships between different keys:
– There can be many superkeys. Some of the superkeys are candidate keys. One of the candidate keys is the primary key.
– A candidate key is a superkey such that no proper subset of it is a superkey within the relation
36
7
Example
37
registration make model colour
Car(registration, make, model, colour)
Underline: primary key
The zoo has another problem
38
The zoo obtained a new animal — Larry the Leopard
Primary Key
• Name used as primary key
• But we cannot have two animals with the same primary key!
ibl l iwhich Larry?
• Possible solutions:
– change Larry's name
– key becomes name + family
– introduce a new artificial key
39
similar problems, what happens if another leopard
called Larry arrives?
y
surrogate key
Relationships
• An association between two or more entities
• Identified/described by two or more key attributes
40
Star Filmrole
cast_asEntity Type Entity Type
Relationship
Relationships Represented by Tables
Given the Film Star table and the Film table, an example of a relationship between these tables is the Role relation (table):
RoleRole
Name Film Cast_As
Harrison Ford Star Wars Han Solo
Harrison Ford Raiders of the Lost Ark
Indiana Jones
Marlon Brando
Last Tango In Paris Paul
Tables
• A table models:
– objects in the real world
– relationships between objects (entities)
I ll t bl i ll d “ l ti ”• In all cases a table is called a “relation”
42
8
Relation Schema Definition
Relation schema is a set of attribute names and theirdomains.
DomainsAttribute names
43
CHARACTER(25)CHARACTER(10)
SMALLINT
namenationalityyob
Player(name, nationality, yob)
Example of Relation
(Tom Watson , USA, 1949)(Jack Nicklaus, USA, 1940)
A set of tuples for relation Player
44
( , , )(Severiano Ballesteros, Spain, 1957)(Raymond Floyd, USA, 1942)
Values ofattribute
name
Taken fromdomain
CHARACTER(25)
A Better Definition of Relation
• Given a relation schema, a relation or tabledefined for that schema is a finite set of tuples such that:
– Each tuple contains as many values as there are– Each tuple contains as many values as there are attribute names in the relation schema.
– Each value is drawn from the domain with which its attribute (column) type is associated.
45
Foreign Keys
• Recall:
– There may be more than one candidate key
– We may choose a particular one and called it the primary key
• A foreign key is an attribute (or a set of attributes) that matches the candidate key of some relation
• Examples: keeper attribute in the Animal table, or supervisor in the Managed‐by table
46
Examples
name family weight age keeper
Larry lion 500 4 112Ernie elephant 4000 3 724Sydney snake 1000 6 134. . .
Animalforeign key
47
Keeperpersonnel_no name age
112 Jones 34724 Thomas 42134 Brown 25. . .
Relational Integrity
• Relational integrity is a set of rules which ensure that the data is accurate
• The rules contain:– Domain constraints (we have already met theseDomain constraints (we have already met these constraints)
– Entity integrity rule
– Referential integrity rule
• Before we define the last two rules, we study the concept of nulls
48
9
Nulls
• Null represents a value for an attribute that is currently unknown or it is not applicable.
• Null is not the same as
– numeric value zero
– string of spaces
• Not all RDBMS use nulls. If we don’t use nulls, then we need to use “false’’ data to represent missing or non‐applicable data. For example, use number ‐1 in the field of type text.
49
Entity Integrity
• Recall: Entities are modelled by tables. Each table has a primary key.
• Entity Integrity:
In a table no cell under a primary
• For example, in the Animal table no record can have a null in the name column; and in the Food table there may be no nulls in the type (of Food) column
50
In a table, no cell under a primarykey column can be null.
Referential Integrity
If a foreign key exist in a table, either the foreignkey value must match a candidate key value ofsome row in its home table, or the foreign key valuemust be null.
51
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.
Queries
• How to search for specific data in the database?– Example: list all animals eating buns with weight between 20 and 200 kg, in ascending order of their age
• DBMS supports flexible queries of the data• QBE (Query‐by‐example): a visual way of specifying a Q (Q y y p ) y p y gquery
• SQL (Structured Query Language): a language for specifying queries to a relational database– de facto standard– Use English words, e.g. SELECT, INSERT, WHERE…
52
QBE and SQL
• QBE can be regarded as a graphical “front‐end” to SQL
• They are non‐procedural languages: you specify whatyou want, not how to get it
• Some operations:Some operations:– Update data– Search data according to some criteria– Display results in certain order– Aggregate functions (max, sum, …)
• In the practicals, you will learn how to use QBE in Access
53
Summary
• A relational database consists of nothing but relations represented as tables
• A table can represent either an entity set or a relationship between entities
• Each table has a predefined and time‐invariant format — this is specified by the relation schema
• Each table is homogeneous — each column contains only values from a specified domain
54
10
Summary: Terminology
• Entity a real‐world object / concept• Entity set a collection of entities• Attribute a property of an entity• Relation a “table” with columns and rowsT l i t bl• Tuple a row in a table
• Relationship an association between two or more entities
• Database a set of tables for entity sets and relationships
• Rel. Database a collection of normalized tables
55
CO7101 Java & Databases
Entity Relationship Diagrams
CO7101 Java & Databases 56
Entity Relationship Diagrams
Dr. Stuart Kerrigan
Objectives
• The use of conceptual models to support database design
• Basic concepts of Entity‐Relationship (ER) model: entities attributes relationshipsmodel: entities, attributes, relationships
• Types of relationships
• Diagrammatic technique for displaying ER models
57
The Database Design Process
• Step 1: Construct a conceptual model (typically ER model) to capture precisely the real‐world problem
• Step 2: Design database tables to represent• Step 2: Design database tables to represent the ER model
• Step 3: Implement the tables in a DBMS
• We will now start Step 1…
58
Conceptual Modelling
• The process of constructing a model for certain information that is independent of implementation issues such as
– The type of DBMS
– Application programs
– Programming language
– Other physical considerations
• The conceptual model should be a complete and accurate representation of the required information
59
The Entity‐Relationship (ER) Model
• The ER model is a high‐level conceptual model proposed by P.P. Chen in 1976 in the paper
– “The Entity‐Relationship model ‐ towards a unified view of data’’
• Purpose of ER model:
– Support user’s understanding of information
– Abstract from technical details of database design
– Be independent of DBMS and hardware issues
60
11
Entity‐Relationship Modelling
• Entity‐Relationship modelling: identify what information we want to describe, and structure that information in a sensible way
• How do we do this?• How do we do this?
– identify entities
– identify attributes
– identify relationships
between entities
61
The basic concepts of ER modelling
Entities
• An entity is something that makes sense in an application context:
– a tangible and/or visible thing
something that may be apprehended intellectually– something that may be apprehended intellectually
– something toward which thought or action is directed
– something about which information needs to be recorded
62
Entities and Their Representation
63
Car(reg#,make,model) XTX456A Nissan Bluebird
instance of a carconcept of a car
Entities vs. Entity Types
• Entity type: an object or a concept that is identified by users as having an independent existence– Examples: car, employee, sale
• Entity: an instance of an entity type that is uniquely identifiable– Examples:
• John Smith, L1328, 1 High Street, ...
• XTX456A Nissan Bluebird, 1023, £1234,...
64
Attributes
• An attribute is an abstraction of a single characteristic or property of an entity or a relationship type
• Entities are identified by their properties, i.e. by sets of values held by attributes
• Attribute domain is a set of values that may be assigned to an attribute
65
Attribute Values for a Car
66
Attributesregistration#makemodel
MVI 321BMW316
12
Finding and Classifying Attributes
• Naming attributes: used to uniquely identify an entity– Usually don’t change
– “What uniquely identify this object from other q y y jsimilar objects (same entity set)?”
• Descriptive attributes: provide intrinsic information about the entity– “what properties distinguish this entity (from other entity types)?”
67
Simple vs. Composite Attributes
• Simple attribute: composed of a single component, with an independent existence
• Composite attribute: composed of multiple components each with an independentcomponents, each with an independent existence
– For example, Address: contains number, street, town, ... components.
68
Single‐ vs. Multi‐valued Attributes
• Attributes are either single‐ or multi‐valued depending on the number of values they hold
– Examples:
• Tel_No: one may have more than one telephone number
• Gender: one can only have one gender
• Type_of_food: a dish may consist of several types of food: protein, carbohydrates,...
• What is the difference between composite and multi‐valued attributes?
69
Derived Attributes
• Derived Attribute: an attribute whose value is derivable from the values of other attributes, not necessarily in the same entity
– Examples:– Examples:
• Age is derivable from DoB
• Total_Staff (of, say, the Department entity) can be calculated by counting Staff entities
70
ER Diagrams: Entities and Attributes
Employee
NI#[PK]name
fi t
Entity name
Primary key
Composite
71
firstnamelastname
dob/ageskills[1..3]
Attributes
Derivedattribute
Multi-valuedattribute
Compositeattribute
Relationships
XBS 456 NFordZodiac P#351
John Smith1 Hi h St t
There are relationships between entities: My car
72
1 High StreetLeicester
P#351 owns XBS 456 N
Relationship: an association of entities, where the association includes one entity from each participating entity type
13
Representing Relationships
73
Owner
personnel-no[PK]namestreettown
ownsCar
reg#[PK]makemodel
Relationship: Notation
Entity_type_name_2
attribute_3attribute_4
Entity_type_name_1
attribute-1attribute-2
relationship
74
Staff Next_of_KinRelatedTo
Example:
Relationship: Some Terms
• Degree of a relationship: the number of participating entities in a relationship– binary
– ternary
quaternary– quaternary
– unary (recursive)• Example: “Supervises” between the entities Keeper and Keeper
• Relationships may be given role names to indicate the purpose that each participant plays in a relationship
75
Structural Constraints on Relationships
• There are cardinality and participation constraints
• Cardinality ratio (or multiplicity): describes the number of possible relationships for each participating entityparticipating entity
• For binary relationships, cardinality ratios are– one‐to‐one– one‐to‐many– many‐to‐one– many‐to‐many
76
Kinds of Relationship – 1
• One‐to‐One
– Every warehouse has no more than one manager
– Every member of Staff can manage at most one warehousewarehouse
77
0..1
Warehouse
0..1
Staff
0..10..1
Manages
One‐to‐One Relationships
a1
a b
78
a2
a3 b2
b3
b1
14
Kinds of Relationship – 2
• Many‐to‐One
– Every employee works at no more than one warehouse
– Every warehouse has several (>=0) employeesEvery warehouse has several (>=0) employees working in it
79
0..1
Warehouse
0..*
Employee
0..10..*
Works_in
Many‐to‐One Relationships
a1
a2b1
80
a5
a3
a4
b2
b3
Kinds of Relationship – 3
• One‐to‐Many
– Each manager supervises several employees
– Every employee is supervised by only one managermanager
81
0..*
Employee
0..1
Manager
0..*0..1
Manages
One‐to‐Many Relationships
a1
b1
b2
82
a2
a3
b5
b3
b4
Kinds of Relationship – 4
• Many‐to‐Many
– Each student takes several (>=0) modules
– Each module is taken by a number (>=0) of studentsstudents
83
0..*
Course
0..*
Student
0..*0..*
Takes
Many‐to‐Many Relationships
a1 b1
84
a2
a3
a4
b2
b3
b4
15
Some Examples
• What is the cardinality ratio of these relationships?
– Entity sets: Males, Females
– Relationship: is‐married‐to
– Entity: Animals, Families
– Relationship: belongs‐to
– Entity: Books, Users
– Relationship: is‐reserved‐by
85
Participation Constraints
• Determine whether the existence of an entity depends upon it being related to another entity through the relationship.
• If an entity’s existence requires the existence of an associated entity in a particular relationship, then participation is total. Otherwise, it is partial.
• Total and partial participation are often referred to as mandatory and optional, respectively.
86
Membership Class – 1
• Mandatory (total) both sides:
– A student must attend at least one lecture
– A lecture must be attended by at least one studentstudent
87
Student membership is mandatory.Lecture membership is mandatory.
1..*
Lecture
1..*
Student
1..*1..*
Attends
Membership Class – 2
• Mandatory one side and optional the other side:
– A student must attend at least one lecture
A lecture need not be attended by any students– A lecture need not be attended by any students
88
Student membership is mandatory.Lecture membership is optional.
1..*
Lecture
0..*
Student
1..*0..*
Attends
Membership Class – 3
• Optional both sides:
– A student need not attend any lectures
– A lecture need not be attended by any students
89
Student membership is optional.Lecture membership is optional.
0..*
Lecture
0..*
Student
0..*0..*
Attends
Strong vs. Weak Entity Types
• Strong entity type: an entity type that is not dependent on the existence of another entity type for its primary key– For example, Staff, Library_User, ...
Has its own primary key– Has its own primary key
• Weak entity type: an entity type that is dependent on the existence of some other entity type for its primary key– For example, Next_of_Kin, Appointment, ... (see next slide)
– Has no primary key of its own
90
16
Weak Entities: in Diagrams
• Note the total participation (why?)
Employee Dependent
0..*
has1..1 Weak entities
NameEmployee_id[PK]
91
Client Appointmentmade
1..1 0..*
Weak entities
DateTime
Client_id[PK]
Summary
• ER model and diagrams
– Entities, attributes and relationships
• Types of relationships
C di li– Cardinality: one‐to‐one, one‐to‐many, many‐to‐one, many‐to‐many
– Participation: total / partial
92
CO7101 Java & Databases
Normalization: When There Is
CO7101 Java & Databases 93
Normalization: When There Is Something Fishy In Your Databases
Dr. Stuart Kerrigan
Revision : The components of a DB
Database
Data
a abaseManagement
System
Limitations of FFDBs
Flat file databases are suitable for storage tasks if data is simple or if there is not tootasks if data is simple, or if there is not too much of it.
If data stored is too complex, then the flat file database breaks down ‐ it exhibits a number of anomalies.
Example DatabasesSUPPLIER SUPPLIER
ADDRESSSUPPLIERPHONE
GOODSSUPPLIED
DATESUPPLIED
INVOICENUMBER
Viglen 23 Main St. 234345 2 586 PCs 23/3/97 3456483Opus 5 High St. 343434 6 486 PCs 12/12/96 4566578Opus 5 High St. 343434 1 printer 3/4/97 4566683Viglen 23 Main St. 234345 4 586 PCs 12/1/97 3456210Opus 5 High St. 343434 2 486 PCs 12/3/97 4566602
STUDENT STUDENT. No. COURSE LECTURER DEPT. ROOM TIMESmith, A. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Smith, A. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Bloggs, F. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 Chem1 Dr. Bell Chem CLT 12.00
TITLE AUTHOR PUBLISHER YEAR ISBN PRICEInformation Technology Smith & Jones Collins 1990 1-23445-345 £20.00Information Technology Smith & Jones Collins 1996 1-23445-319 £25.00Databases for Dummies Bloggs Longmans 1993 2-34542-422 £15.00Spreadsheets for Idiots Macpherson Collins 1994 4-34589-445 £18.00
17
Update Anomaly
If data appears more than once in the database, then if one item of the data is altered, we must alter all the instances of that data.
Example ‐ Update Anomaly
SUPPLIER SUPPLIERADDRESS
SUPPLIERPHONE
GOODSSUPPLIED
DATESUPPLIED
INVOICENUMBER
Viglen 23 Main St. 234345 2 586 PCs 23/3/97 3456483Opus 5 High St. 343434 6 486 PCs 12/12/96 4566578Opus 5 High St. 343434 1 printer 3/4/97 4566683Viglen 23 Main St. 234345 4 586 PCs 12/1/97 3456210Opus 5 High St. 343434 2 486 PCs 12/3/97 4566602
SUPPLIER SUPPLIERADDRESS
SUPPLIERPHONE
GOODSSUPPLIED
DATESUPPLIED
INVOICENUMBER
Viglen 23 Main St. 234345 2 586 PCs 23/3/97 3456483Opus 59 High St. 343434 6 486 PCs 12/12/96 4566578Opus 5 High St. 343434 1 printer 3/4/97 4566683Viglen 23 Main St. 234345 4 586 PCs 12/1/97 3456210Opus 5 High St. 343434 2 486 PCs 12/3/97 4566602
Insertion Anomaly
If new information is available, we may not be able to enter the data until we have data for all fields.
Example ‐ Insertion Anomaly
STUDENT STUDENT. No. COURSE LECTURER DEPT. ROOM TIMESmith, A. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Smith, A. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Bloggs, F. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 Chem1 Dr. Bell Chem CLT 12.00
STUDENT STUDENT. No. COURSE LECTURER DEPT. ROOM TIMESmith, A. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Smith, A. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Bloggs, F. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 Chem1 Dr. Bell Chem CLT 12.00. Chem2 Dr. Clapper Chem
Deletion Anomaly
If we delete some information from the database, we may accidentally remove additional data which we wish to keep.
Example ‐ Deletion Anomaly
STUDENT STUDENT. No. COURSE LECTURER DEPT. ROOM TIMESmith, A. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Smith, A. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Bloggs, F. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00gg pBloggs, F. 776829 Chem1 Dr. Bell Chem CLT 12.00
If we delete Bloggs from the Chem1 course we lose our only record that Dr. Bell teaches this class in the Chem Department Room CLT at 12.00.
Not very intelligent.
18
Functional Dependency
All these anomalies occur because some fields are functionally dependenton one another.
ll d h i D K i ille.g. all records showing Dr. Kerrigan will show his Department as Computer Science, and so on.
Functional Dependency
• A property that exists between fields
– that the value in one field determines the value that can be contained in the other field
• E g if you know the value of the first attribute• E.g. if you know the value of the first attribute you can find the value of a second attribute
Example of FD
A B
If I know the value of A I can find the value of B
Real Life Example of FD
A B
StudentID StudentName
If I know the StudentID I can find the corresponding StudentName
Real Life Example of FD
A B
StudentID StudentName
Date of Birth
If I know the StudentID I can find the corresponding StudentName and the corresponding Date Of Birth
Real Life Example of FD
A B
StudentID[PK]
StudentName
Date of Birth
In good database design all non-key fields should be dependant solely on all parts of the primary key.
19
Composite Primary KeysClientID[PK] Date of
BirthPropertyID
[PK]
ClientID[PK]
Comments
In good database design all non-key fields should be dependant solely on all parts of the primary k
PropertyID[PK]
Transitive Dependency
A B
TransactionID CustomerName
If I know the TransactionID I can find the Customer’s Name. Once I know the Customer’s Name I can find the SalesRep’s Name
SalesRep
Transitive Dependency
A B
TransactionID CustomerName
If I know the TransactionID I can find the Customer’s Name. Once I know the Customer’s Name I can find the SalesRep’s Name
SalesRep
The Solution ‐Multiple Tables
We must extract some of the data fields from the list (or table) and create a second table (or more).
Our application must now be able toOur application must now be able to handle multiple tables, and perform queries etc. across multiple tables.
Converting a Database
If we have an existing flat file database, we can convert it into a well‐behaved relational database via a step‐by‐step process known as normalisation.
Normalisation
First normal form according to Codd ‐
All fields must contain atomic data.
Codd defines an atomic value as one that "cannot be decomposed into smaller pieces by the DBMS (excluding certain special functions).”
20
Example ‐ 1NF According to CoddAre fields atomic?
Name[PK]
Office PhoneNumber1
PhoneNumber2
PhoneNumber3
Dr. Stuart Kerrigan F25 3333 4452 34421
Prof. Klaus Himmelheim
D22 211 NULL NULL
M P t V k ECTO1 3332 3432 NULL
Why is this example NOT in 1NF?
Mr. Peter Venkman ECTO1 3332 3432 NULL
Example ‐ 1NF According to CoddAre fields atomic?
Title[CPK]
FirstName[CPK]
Surname[CPK]
Office PhoneNumber1
PhoneNumber2
PhoneNumber3
Dr. Stuart Kerrigan F25 3333 4452 34421
Prof. Klaus Himmelheim D22 211 NULL NULL
Name was not atomic – could be further decomposed.
Note composite primary key.
Mr. Peter Venkman ECTO1 3332 3432 NULL
Example ‐ 1NF
STUDENT STUDENT. No. COURSE LECTURER DEPT. ROOM TIMESmith, A. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Smith, G. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Bloggs, T. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00gg pBloggs, F. 776829 Chem1 Dr. Bell Chem BEN LT5 1.00
INITIAL STUDENT. No. COURSE LECTURER DEPT. ROOM TIMEA. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00G. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00T. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00F. 776829 Chem1 Dr. Bell Chem BEN LT5 1.00
SURNAMESmithSmithBloggsBloggsBloggs
These 3 columns repeat as they are storing the same information
Repeating Columns
PhoneNumber1
PhoneNumber2
PhoneNumber3
3333 4452 34421
211 NULL NULL
3332 3432 NULL
Remove Repeating Columns
Example ‐ 1NF According to Date
Title[CPK]
FirstName[CPK]
Surname[CPK]
Office PhoneNumber1
PhoneNumber2
PhoneNumber3
Dr. Stuart Kerrigan F25 3333 4452 34421
Prof. Klaus Himmelheim D22 211 NULL NULL
Mr. Peter Venkman ECTO1 3332 3432 NULL
StaffID[PK]
Title FirstName
Surname Office
1 Dr. Stuart Kerrigan F25
2 Prof. Klaus Himmelheim D22
3 Mr. Peter Venkman ECTO1
PhoneNumber [PK]
StaffID[FK]
3333 1
4452 1
34421 1
211 2
3332 3
3432 3
Phone Staff
Normalisation
Second normal form ‐
• Must be 1NF.
• Automatically 2NF if no composite• Automatically 2NF if no composite primary key.
• Each nonkey attribute in table must be functionally dependent upon the whole primary key.
21
Example ‐ 2NFViewing
ClientNo[Comp PK]
PropertyNo[Comp PK]
ViewDate Comment FirstName LastName City
CR56 PA14 24‐May‐01 too small Annie Bradock Detroit
CR56 PG36 28‐Apr‐01 NULL Annie Bradock Edinburgh
CR56 PG4 26‐May‐01 NULL Annie Bradock Londony
CR62 PA14 14‐May‐01 no dining room
John Wayne Detroit
CR76 PG4 20‐Apr‐01 too remote Ivor Taper London
• Note the composite primary key (i.e. key consists of 2 fields)
• Each nonkey attribute in table must be functionally dependent upon the entire primary key.
• Is this so?
Example ‐ 2NFClientNo[Comp PK Foreign Key]
PropertyNo[Comp PKForeign Key]
ViewDate Comment
CR56 PA14 24‐May‐01 too small
CR56 PG36 28‐Apr‐01 NULL
CR56 PG4 26‐May‐01 NULL
CR62 PA14 14‐May‐01 no dining room
ClientNo[PK]
FirstName LastName
CR56 Annie Bradock
CR62 John Wayne
CR76 Ivor Taper
CR76 PG4 20‐Apr‐01 too remote
PropertyNo[PK]
City
PA14 Detroit
PG36 Edinburgh
PG4 London
Now in 2nd Normal Form
Normalisation
Third normal form ‐
• Must be 2NF.
• All the non‐key fields must be dependent on the primary key.
Example ‐ 3NFOrderNo[PK]
Customer ContactPerson
Total
1 Acme Dave £20
2 StuCorp Fred £20000
3 Acme Dave £15
4 Acme Dave £123
•OrderNo serves as the primary key.•Customer and total amount are dependent on the order number ‐‐ this data is specific to each order.•However, the contact person is dependent upon the customer.•There is really a 1‐1 relationship between Customer and Contact Person.
5 StuCorp Fred £0.50
Example ‐ 3NFOrderNo[PK]
Customer Total
1 Acme £20
2 StuCorp £20000
3 Acme £15
4 Acme £123
Customer[PK & Foreign Key]
ContactPerson
Acme Dave
StuCorp Fred
•Create tables to represent relations ‐ a 1‐1 relationship between Customer and Contact Person.
4 Acme £123
Example ‐ 3NF
INITIAL Student. No. pk COURSE LECTURER DEPT. ROOM TIMEA. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00A. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00F 776829 CO1005 D S l ki C S i PH LTA 1 00
SURNAMESmithSmithBloggs
l F. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00F. 776829 Chem1 Dr. Bell Chem BEN LT5 1.00
BloggsBloggs
22
Example ‐ Converting to 3NFSTUDENT STUDENT. No. COURSE LECTURER DEPT. ROOM TIMESmith, A. 765432 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Smith, A. 765432 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 CO1019 Dr. Kerrigan CompSci BEN LT5 2.00Bloggs, F. 776829 CO1005 Dr. Solanki CompSci PH LTA 1.00Bloggs, F. 776829 Chem1 Dr. Bell Chem BEN LT5 1.00
COURSELECTURERINITIAL STUDENT NoSURNAME
STUDENT. No. COURSE765432 CO1019765432 CO1005776829 CO1019776829 CO1005776829 Chem1
COURSE ROOM TIMECO1019 BEN LT5 2.00CO1005 PH LTA 1.00Chem1 BEN LT5 1.00
CO1019Dr. KerriganCO1005Dr. SolankiChem1Dr. Bell
INITIAL STUDENT. No.A 765432F 776829
SURNAMESmithBloggs
2NF and 3NF
• Difference between the second and third normal forms of a normalizednormalized database?– "The key,
– the whole key,
– and nothing but the key,
– so help me Codd."
2NF
3NF
Beyond 3NF
Boyce‐Codd normal form (BCNF)
Raymond F. Boyce and Codd(1974)
Every non‐trivial functional dependency in the table is a dependency on a superkey
Fourth normal form (4NF)
Fagin (1977)
Every non‐trivial multivalued dependency in the table is a dependency on a superkey
Every non‐trivial join
Fifth normal form (5NF) Fagin (1979)dependency in the table is implied by the superkeys of the table
Domain/key normal form (DKNF)
Fagin (1981)
Every constraint on the table is a logical consequence of the table's domain constraints and key constraints
Sixth normal form (6NF)Chris Date, Hugh Darwen, and Nikos Lorentzos (2002)
Table features no non‐trivial join dependencies at all (with reference to generalized join operator)
Beyond 3NF• First normal form (1NF) ‐ Codd (1970), Date (2003) ‐ Table faithfully
represents a relation, data is atomic and has no “repeating groups”• Second normal form (2NF) ‐ Codd (1971) ‐ No non‐prime attribute in the
table is functionally dependent on a part (proper subset) of a candidate key
• Third normal form (3NF) ‐ Codd (1971) ‐ Every non‐prime attribute is non‐transitively dependent on every key of the table
• Boyce‐Codd normal form (BCNF) ‐ Boyce and Codd (1974)‐ Every non‐trivial functional dependency in the table is a dependency on a superkeytrivial functional dependency in the table is a dependency on a superkey
• Fourth normal form (4NF) ‐ Fagin (1977) ‐ Every non‐trivial multivalueddependency in the table is a dependency on a superkey
• Fifth normal form (5NF) ‐ Fagin (1979) ‐ Every non‐trivial join dependency in the table is implied by the superkeys of the table
• Domain/key normal form (DKNF) ‐ Fagin (1981) ‐ Every constraint on the table is a logical consequence of the table's domain constraints and key constraints
• Sixth normal form (6NF) ‐ Date, Darwen, and Lorentzos (2002) ‐ Table features no non‐trivial join dependencies at all (with reference to generalized join operator)
SUMMARY
–Flat file databases can handle only simple and small scale data, otherwise anomalies occur
–Relational databases can handle complex–Relational databases can handle complexand large amounts of data
–Normalisation is used to ensure efficient relationships
Relationships & Functional Dependencyp y
Dr. Stuart Kerrigan
23
A Simple Binary Relationship
• People own many houses.
• Some people own no houses.
• Some houses are unowned.
• Some houses have many people in them.
A Simple Binary Relationship
• People own many houses.
• Some people own no houses.
• Some houses are unowned.
• Some houses have many people in them.
A Simple Binary Relationship
• People can live in many houses.
• Some people live in no houses.
S h• Some houses are empty.
• Some houses have many people in them.
A Simple Binary Relationship
• People can live in many houses.
• Some people live in no houses.
S h• Some houses are empty.
• Some houses have many people in them.
A Simple? Relationship
• Some staff manage 1 or more staff members.
• Some staff do not manage other staff membersother staff members.
• A staff member has at most one manager
A Simple? Relationship
• Management staff manage 1 or more staff members.
• Some staff do not manage other staff members
manages
other staff members.
• A staff member has at most one manager
24
Functional Dependency
• A property that exists between fields
– that the value in one field determines the value that can be contained in the other field
• E g if you know the value of the first attribute• E.g. if you know the value of the first attribute you can find the value of a second attribute
Example of FD
A B
If I know the value of A I can find the value of B
Real Life Example of FD
A B
StudentIDStudent Name
If I know the StudentID I can find the corresponding StudentName
Real Life Example of FD
A B
StudentIDStudent Name
Date of Birth
If I know the StudentID I can find the corresponding StudentName and the corresponding Date Of Birth
Real Life Example of FD
A B
StudentID[PK]
StudentName
Date of Birth
In good database design all non-key fields should be dependant solely on all parts of the primary key.
Composite Primary KeysClientID[PK] Date of
BirthPropertyID
[PK]
ClientID[PK]
Comments
In good database design all non-key fields should be dependant solely on all parts of the primary k
PropertyID[PK]
25
Transitive Dependency
A B
TransactionID
Customer Name
If I know the TransactionID I can find the Customer’s Name. Once I know the Customer’s Name I can find the SalesRep’s Name.
SalesRep
Transitive Dependency
A B
TransactionID
CustomerName
If I know the TransactionID I can find the Customer’s Name. Once I know the Customer’s Name I can find the SalesRep’s Name.
SalesRep
CO7101: Java & Databases For Bioinformatics
SQL 1:
CO7101: Java & Databases For Bionformatics
147
Simple Data Definition and Select Statements
Dr. Stuart Kerrigan
SQL Components: DDL, DML, & DCL
• SQL is a transform‐oriented language
• SQL is a non‐procedural language: specify what info you require rather than how you access the data
• SQL is a very large and powerful language, but every type of SQL statement falls within one of three main categories (or sub‐languages):
• Data Definition Language (DDL) for creating a DB, defining & controlling g g ( ) g , g gaccess to data
e.g. CREATE, DROP, ALTER
• Data Manipulation Language (DML) to access a DB by retrieving and updating data
e.g. SELECT, INSERT, UPDATE, DELETE
• Data Control Language (DCL) for administering a DB
e.g. GRANT, DENY, USE
148
SQL ‐ Structured Query Language
• SQL was developed at IBM around 1975...• Structured programming?No! ‐ Structured English Query Language (from 'SEQUEL') which implements relational algebra
• SQL is a declarative language ‐ says what not howSQL is a declarative language says what not how• SQL is an abstract & portable interface to RDBMS• Different versions of SQL slightly different syntax• We use mySQL• Only standard db language to gain wide acceptance
149
SQL Syntax• SQL uses reserved keywords & user‐defined names
CREATE TABLE Staff ( StaffNo INTEGER, Salary FLOAT,
Lname VARCHAR(20) );
• This means create a table called staff with the following fields:– StaffNo as an Integer– Salary as a FlatSalary as a Flat– Lname as a text field with 20 charactersINSERT INTO Staff VALUES (32, 25000.0, 'Smith');
• This means insert into our staff table a row with the following fields:– StaffNo of 32– Salary of 25000.0– Last name of 'Smith'
150
26
SQL Syntax• SQL uses reserved keywords & user‐defined names
CREATE TABLE Staff ( StaffNo INTEGER, Salary FLOAT,Lname VARCHAR(20) );INSERT INTO Staff VALUES (32, 25000.0, 'Smith');
• By convention, keywords are upper‐case, though most SQL dialects are case‐insensitive;
• User‐defined names must be entered exactly as in tablesd i l d i i l (' ')• Text data is enclosed using single quotes (' ')
• Round brackets () are used to group related items• Commas , separate items in a list• Statements are terminated with a semicolon (';')• | indicates choice; literals: non‐numeric require single quotes,
e.g., VALUES('Bob',4); [] indicates optionality
151
Relational Tables Can AnswerMany Queries
Student Enrolment Course
152
How many courses are there & what are their names?Which students are enrolled for Java? How many students take 3 or more courses?
Data Definition Language (1)• The SQL syntax for CREATE TABLE isCREATE TABLE table_name (
Column1name data_type_for_column_1,
Column2name data_type_for_column_2,... )
Column Type Description Syntax
153
yp p y
int Accepts integer values only tinyint, int
float Accepts float values only float
boolean Accepts a TRUE or FALSE value boolean
varchar Accepts any symbol, character, or number
varchar(char limit
value), for example
varchar(20) is
string of length 20
date Date (YYYY‐MM‐DD), e.g. 2009‐02‐23 date
Data Definition Language
• How would you create the following table?• First decide what type of field to use for each field• StaffNo – this is obviously an integer• Fname, Lname, Position are text fields• Salary – this could be debatable. Let's make it a float.
StaffNo Fname Lname Position Salary
Salary this could be debatable. Let s make it a float.CREATE TABLE Staff (StaffNo INTEGER, Fname VARCHAR(20), Lname VARCHAR(20), Position VARCHAR(20), Salary FLOAT);
• mySQL description of this table is as follows:‐
154
Data Definition Language
• Forgot the domains of your table?• Use the command
DESCRIBE table_name• e.g. DESCRIBE Staff;
155
Built‐in Data Types (Domains) inMySQL
• SQL supports many data types (vendors often also have own dialects):– CHARACTER (CHAR), CHARACTER VARYING (VARCHAR)– NUMERIC, DECIMAL (DEC), INTEGER (INT), SMALLINT– FLOAT, REAL, DOUBLE PRECISION– DATE, TIME, TIMESTAMP– BOOLEAN, BIT– BINARY LARGE OBJECT (BLOB), etc.
• Some types have an associated size . e.g. CHAR(5)
156
27
SQL Syntax• SQL uses reserved keywords & user‐defined names
CREATE TABLE Staff ( StaffNo INTEGER,Salary FLOAT, Lname VARCHAR(20));
• This means create a table called staff with the following fields:– StaffNo as an Integer– Salary as a Flat– Lname as a text field with 20 charactersa e as a e e d 0 c a ac e s
• Now we want to add data to our table.INSERT INTO Staff VALUES (32, 25000.0, 'Smith');
• This means insert into our staff table a row with the following fields:– StaffNo of 32– Salary of 25000.0– Last name of 'Smith'
157
SQL Syntax
StaffNo Fname Lname Position Salary
222 Head Honcho CEO 35000
322 Mark Jones Manager 20000
261 Julie Walters Director 40000
260 Julie Walters Tax Shelter 20000
Staff
• How would you insert the values into the table?– 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
555 Dogollan Body Cleaner 500
444 Trinity Wells Porter 200
SQL Syntax• Suppose we don’t know all the information?
– e.g. we know a person’s lastname, position and salary but not their staff number or first name?
INSERT INTO Staff (Lname, Position, Salary) VALUES ('Peters','Cleaner',30);
• Leaves the unknown fields as NULL. Can put these in later…
CO7101: Java & Databases For Bionformatics
159
StaffNo Fname Lname Position Salary
222 Head Honcho CEO 35000
322 Mark Jones Manager 20000
261 Julie Walters Director 40000
260 Julie Walters Tax Shelter 20000
555 Dogollan Body Cleaner 500
444 Trinity Wells Porter 200
NULL NULL Peters Cleaner 30
Simple Queries Using SELECTSELECT * FROM Staff;
StaffNo Fname Lname Position Salary
222 Head Honcho CEO 35000
322 Mark Jones Manager 20000
Staff
160
•Here, asterisk * acts as a 'wild card'•that means SELECT all the fields FROM the staff table
•Outputs a table (so SELECT is a closed operation)
261 Julie Walters Director 40000
260 Julie Walters Tax Shelter 20000
555 Dogollan Body Cleaner 500
444 Trinity Wells Porter 200
Simple Queries Using SELECT•The SELECT statement retrieves data and formats output•SELECT is the most frequently used SQL statement•Performs relational algebra's selection, projection and join operations in a single statement
SELECT * FROM Staff;•In English this means select all the rows from the staff table.
161
SELECT
SELECT fields‐list FROM table‐listWHERE condition;
• tables‐list ‐ A list of table names you wish to select from.• fields‐list‐A list of fields from the tables in tables‐list; can also
if di i ( d li ) ll (*)specify distinct (no duplicates) or all (*)• condition– filters rows subject to some condition
SELECT Fname FROM Staff;
SELECT Fname, Lname FROM Staff WHERE Salary > 15000;
162
28
Selecting Specific Columns•Specific columns can be output by giving their names:
SELECT Fname FROM Staff;Fname
Head
Mark
163
•In English this means:‐•Select the first names (Fname) field for all the rows FROM the staff table
Mark
Julie
Julie
Dogollan
Trinity
Selecting Specific Columns•Specific columns can be output by giving their names:
SELECT Lname, Position, Salary FROM Staff;Lname Position Salary
Honcho CEO 35000
Jones Manager 20000
164
NB. must have a comma (',') between column names•In English this means:‐
•Select the last names (Lname), positions (Position) and Salaries (Salary) fields of all the rows from the staff table
Jones Manager 20000
Walters Director 40000
Walters Tax Shelter 20000
Body Cleaner 500
Wells Porter 200
Selecting Specific Columns•Use WHERE to specify a condition:
SELECT Fname, Lname, Salary FROM StaffWHERE Salary > 15000;
165
•In English means:‐•Select the first names (Fname), positions (Position) and Salaries (Salary) for all the rows FROM the staff table WHERE the salary is more than 15000
Selecting Distinct Rows•Use DISTINCT to get only one occurrence of values
SELECT DISTINCT Fname, Lname FROM Staff;Fname Lname
Head Honcho
Mark Jones
Julie Walters
166
•In English this means:‐•Select unique occurrences of the first names (Fname) and last names (Lname) FROM the staff table (i.e. no 2 Julie Walters)
•What about this query? How many rows would we get?SELECT DISTINCT Fname, Salary FROM Staff;
Dogollan Body
Trinity Wells
Selecting Specific Rows & Columns•comparison operators: < less than> greater than= equal to <= less than or equal to
167
>= greater than or equal to != not equal to lesser than or greater than
also use AND, OR and NOT
Selecting Specific Rows & Columns
•can also test for range (BETWEEN, NOT BETWEEN), SELECT Fname, Lname, Salary FROMStaff WHERE Salary BETWEEN 0 AND 10000;
•set membership (IN ('Manager'), NOT IN), •pattern match
SELECT * from Staff WHERE Lname LIKE 'W%';
168
SELECT from Staff WHERE Lname LIKE W% ;SELECT * from Staff WHERE Lname NOT LIKE 'W%';
•whether null (IS NULL, IS NOT NULL)•Condition 'Salary > 20000' is called a predicate•For each row, if predicate is true, row is output
29
Computed/Derived Fields
•Can also compute our own fields•MonthlySalary is a computed field – it is Salary divided by 12
SELECT Fname,Lname,Salary/12 as MonthlySalaryFROM Staff;
•FullName is a computed field concatenating two fields.SELECT concat(Fname ' ' Lname) as FullName
169
SELECT concat(Fname, ,Lname) as FullName FROM Staff;
•When new fields are calculated we can name them using AS
Computed/Derived Fields
170
Computed/Derived Fields
171
Building Up Complex Predicates
• Predicates evaluate to either true or false• Predicates can be combined using AND, OR, and NOT• Use brackets to avoid ambiguity• The next two statements are different:
1.SELECT * FROM Staff WHERE (Position = 'Manager') ORWHERE (Position = Manager ) OR(Position = 'Assistant' AND Salary > 10000);
2.SELECT * FROM Staff WHERE(Position = 'Manager' OR Position = 'Assistant‘)AND NOT (Salary <= 10000);
• In each case, whole WHERE clause is true or false• NULL is not equivalent to '' or <>, can't test equality; use IS
172
Other Types of Predicate
• Other predicates include BETWEEN, IN, and LIKE
• But they still evaluate to either true or falseSELECT * FROM Staff WHERE (Salary BETWEEN 10000 AND 40000) AND (Position IN ('CEO','Director','Cleaner')) AND (Fname LIKE 'H_ _ _' OR Lname LIKE 'W%');
• '_' matches exactly one character
• '%' matches zero or more characters
• So what does this query match?
173
Answer– SELECT * FROM Staff WHERE (Salary BETWEEN 10000 AND 40000) AND (Position IN ('CEO','Director','Cleaner')) AND (Fname LIKE 'H_ _ _' OR Lname LIKE 'W%');
– SELECT all the fields FROM the staff table WHERE the salary is between 10000 and 40000 and the position is either CEO, Director or Cleaner and the firstname begins with H and has 3 characters following it or the lastname begins with W. 174
30
Conclusion
• SQL is the standard query language for RDBMS• Three main categories of SQL
– DDL, Data Definition Language– DML, Data Manipulation Language DCL Data Control Language– DCL, Data Control Language
• CREATE, ALTER and DROP tables using DDL.• SELECT belongs to DML• SELECT retrieves & displays data from the database
• We continue to explore DML
CO7101: Java & Databases For Bionformatics
175
CO7101: Java & Databases For Bioinformatics
SQL 2:
CO7101: Java & Databases For Bionformatics
176
More on SELECT then UPDATE, DELETE
Dr. Stuart Kerrigan
Previously on CO1019:
• Can CREATE tables in a mySQL database
• Can INSERT INTO tables in a mySQL database
• Can use SELECT to– Retrieve data from all the rows and columns (whole table)
SELECT * FROM Staff;
CO7101: Java & Databases For Bioinformatics
177
– Retrieve data from all the rows and select columns
SELECT Fname, Lname FROM Staff;– Retrieve data from select rows and columns
SELECT Fname, Lname FROM Staff WHERE Salary > 10000;
– Compute derived field valuesSELECT Salary/12 as monthySal FROM Staff;
In this lecture you will learn
• Calculate aggregate derived data
• GROUP BY and ORDER BY in SELECT statements
• Modify row data
CO7101: Java & Databases For Bioinformatics
178
• Delete row data
• Delete entire tables
• NULL values in databases
• How to combine query results using set unions
SQL Aggregate Functions
• We do not want to just retrieve data
• We also want to summarise data
• Use in SELECT list and HAVING clause only
• Aggregate functions compute summarization (or aggregation) of data & return a value
CO7101: Java & Databases For Bioinformatics
179
aggregation) of data & return a value
• DISTINCT eliminates duplicates first
• Aggregate functions over a column – SUM – sums column values (numeric fields only)
– AVG – averages column values (numeric fields only)
– MIN – gives min column value
– MAX – gives max column value
– COUNT – gives number of values in column
SUM, MIN, MAX, AVG• Find the minimum, maximum, average and sum of staff salarySELECT MIN(salary) AS minSalary,MAX(salary) AS maxSalary,AVG(salary) AS avgSalary, SUM(salary) AS sumSalary,CO ( l ) S S l
CO7101: Java & Databases For Bioinformatics
180
COUNT(salary) AS countSalaryFROM Staff;
31
GROUP BY
• Aggregate functions help us to summarise the whole column(s) of data into one row.
• Sometimes we want to group data before applying aggregate functions
– This gives us 'subtotals' rather than 'overall total'
CO7101: Java & Databases For Bioinformatics
181
• GROUP BY is used to achieve that
• Closely tied to SELECT; can only have column names, aggregate functions, constants, a combination of these
• All columns in SELECT list must appear in GROUP BY clause unless they're in an aggregate function
• WHERE condition applied before GROUP BY
GROUP BY ‐ Example
• Find the total salaries of each person on payroll by adding salaries from different jobs. Group by their first name.
SELECT Fname, Lname, SUM(Salary) AS TotalSalary FROM Staff GROUP BY Fname, Lname;
CO7101: Java & Databases For Bioinformatics
182
MoreStaff
HAVING• Use with GROUP BY to restrict output; filters groups rather
than rows (WHERE); condition has aggregate fnSELECT branchNo, Count(staffNo) AS myCount, SUM(salary) AS mySum FROM MoreStaff GROUP BY branchNo HAVING COUNT(staffNo)>1;
StaffNo Fname Lname Position Sex DOB Salary BranchNo
SA9 Mary Howe Assistant F 19 Feb 70 9000 B007
QuerybranchNo myCount mySum
B003 3 54000
B005 2 120000
SA9 Mary Howe Assistant F 19‐Feb‐70 9000 B007
SG14 David Ford Supervisor M 24‐Mar‐58 18000 B003
SG37 Ann Beech Assistant F 11‐Oct‐60 12000 B003
SG5 Susan Brand Manager F 03‐Jun‐40 24000 B003
SL21 John White Manager M 01‐Oct‐45 30000 B005
SL41 Julie Lee Assistant F 13‐Jun‐65 90000 B005
SELECT – Group By
SELECT fields‐listFROM table‐listWHERE condition;GROUP BY columnList [HAVING condition]ORDER BY columnList
• GROUP BY filters groups of rows…• Work out aggregate functions for each group in grouped
columns
CO7101: Java & Databases For Bionformatics
184
SELECT – Order By
SELECT fields‐listFROM table‐listWHERE condition;GROUP BY columnList [HAVING condition]ORDER BY columnList
• ORDER BY sorts results ‐ can be ASCending or DESCendingORDER BY sorts results can be ASCending or DESCending• SELECT * FROM StaffORDER BY salary DESC;SELECT * FROM StaffORDER BY Fname ASC;SELECT * FROM Staff ORDER BY Lname ASC, Fname ASC, Position DESC;
CO7101: Java & Databases For Bionformatics
185
A
Z
Z
A
UPDATE Queries
UPDATE table‐listSET field1 = value1
field2 = value2 …WHERE condition; (WHERE is optional)
UPDATE Staff SET Fname ='Dilbert';S ll Fi N 'Dilb ' i h S ff blSets all First Names to 'Dilbert' in the Staff table.
UPDATE Staff SET Position='Chief Executive Officer' WHERE Position = 'CEO';
Sets Positions of 'CEO' to 'Chief Executive Officer' in the Staff table.
UPDATE Staff SET Salary = 10000 WHERE Salary < 10000;
Sets Salary to 10000 where Salary is less than 10000 in the Staff table.
CO7101: Java & Databases For Bionformatics
186
32
UPDATE Queries• Changing specific values in a table:
UPDATE Staff SET Salary = 1.05*Salary
WHERE Position = 'Director';
UPDATE the STAFF table by multiplying the salary by 1.05 where the Position is Director
CO7101: Java & Databases For Bioinformatics
187
DELETE Queries
DELETE FROM table‐listWHERE condition;
• Deleting all rows of a table:DELETE FROM Staff;
• Deleting specific rows of a table:
CO7101: Java & Databases For Bioinformatics
188
• Deleting specific rows of a table:DELETE FROM Staff WHERE Fname = 'Julie' AND Lname = 'Walters';
• Completely removing a table is a DDL (data definition language) operation:
DROP TABLE Staff;
Why Do DB Systems Allow NULLs ?
• A NULL value can be used to represent several situations:
• Don't care; Don't know; Don't know yet; Used to know!
• SQL has special rules and logic to handle NULLs:SELECT * FROM Staff WHERE Fname IS NULL;
• NB. WHERE Colname = 'NULL' does not work ! Can't test
CO7101: Java & Databases For Bioinformatics
189
NB. WHERE Colname NULL does not work ! Can t test equality on something that doesn't exist! IS is not the same as =
• Can also say: WHERE Colname IS NOT NULL
• NULLs can be useful, difficult, or dangerous
• Use NULLs wisely!
A Null Example
StaffNo Fname Lname Position Salary Room
222 Head Honcho CEO 35000 F5
322 Mark Jones Manager 20000 F30
Staff_With_Rooms
322 Mark Jones Manager 20000 F30
261 Julie Walters Director 40000 F1
260 Julie Walters Tax Shelter 20000 NULL
555 Dogollan Body Cleaner 500 NULL
444 Trinity Wells Porter 200 Cellar
Combining Results Tables
• Requirements: tables need to have same structure so they're union‐compatible
• Sometimes its useful to be able to combine query results using set operations:
R ∩ S R - SR U S
CO7101: Java & Databases For Bioinformatics
191
(a) Union (b) Intersection (c) Difference (Excep
R
S S S
R R
Set Operations in SQL
• Syntax:
(SELECT ...) UNION (SELECT ...);• For set operations, the tables must be union‐compatible
– i.e. have the same number and types of columns
• (SELECT city FROM Branch WHERE city IS NOT NULL) UNION (SELECT city FROM PropertyForRent WHERE city
CO7101: Java & Databases For Bioinformatics
192
UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL);
33
Remember this data?
StaffNo Fname Lname Position Salary
222 Head Honcho CEO 35000
322 Mark Jones Manager 20000
Staff
322 Mark Jones Manager 20000
261 Julie Walters Director 40000
260 Julie Walters Tax Shelter 20000
555 Dogollan Body Cleaner 500
444 Trinity Wells Porter 200
Union‐Compatible?
StaffNo Fname Lname Position Salary
523 Redwood Mark CEO 20000
211 Bilbo Baggins Hobbit 12000
260 Julie Walters Tax Shelter 20000
Staff2
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);
260 Julie Walters Tax Shelter 20000
Results of our UnionStaffNo Fname Lname Position Salary
222 Head Honcho CEO 35000
322 Mark Jones Manager 20000
261 Julie Walters Director 40000
260 Julie Walters Tax Shelter 20000
555 Dogollan Body Cleaner 500
444 Trinity Wells Porter 200
523 Redwood Mark CEO 20000
211 Bilbo Baggins Hobbit 12000
Results of our Union
Union‐Compatible?
StaffNo Fname Lname Position Salary Branch
123 Gilbert Laycock Engineer 35000 ENG1
212 Lenny Henry Morale Officer 20000 SCO1
260 Julie Walters Tax Shelter 20000 FRA1
Staff3
CREATE TABLE Staff3 (StaffNo INTEGER, FnameVARCHAR(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);
Union‐Compatible?
StaffNo Fname Lname Position Salary Branch
123 Gilbert Laycock Engineer 35000 ENG1
212 Lenny Henry Morale Officer 20000 SCO1
260 Julie Walters Tax Shelter 20000 FRA1
Staff3
(SELECT * FROM Staff) UNION (SELECT * FROM Staff3);
Won't work – why?
(SELECT * FROM Staff) UNION (SELECT StaffNo, Fname, Lname, Position, Salary FROM Staff3);
34
Union ExampleR U S
(a) Union (b) Intersection (c) Difference (Exce
R
S S S
R R
• Covered unions, but what about Intersections and Differences?
( ) ( ) ( ) (
Intersect and ExceptR U S
(a) Union (b) Intersection (c) Difference (Exce
R
SS S
R R
• Covered unions, but what about Intersections and Differences.
• SQL keywords are INTERSECT and EXCEPT e.g.
(SELECT * FROM Staff) INTERSECT (SELECT * FROM Staff2);(SELECT * FROM Staff) EXCEPT(SELECT * FROM Staff2);
• Sadly not supported in MySQL. There are workarounds on the internet (use Google) – but these use subqueries!
( ) ( ) ( ) (
Intersect Example
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 Salary);Staff.Salary = Staff2.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);
More on (simpler?) subqueries next time!
Conclusion
• Now understand complete SELECT syntax
• Can use aggregate functions
• UPDATE and DELETE queries
• Understand when to use NULLs in database• Understand when to use NULLs in database design.
• Can now perform simple UNIONS between tables
CO7101: Java & Databases For Bionformatics
202
CO7101: Java & Databases For Bioinformatics
SQL 3:
CO7101: Java & Databases For Bionformatics
203
Subqueries and Multiple Tables
Dr. Stuart Kerrigan
Previously on CO1019:
• CREATE tables, INSERT data into table and SELECT data out of table
• Use Aggregate functions
• UPDATE data and DELETE data from table– ALL ON ONE TABLE ONLY!
CO7101: Java & Databases For Bioinformatics
204
• Create a Union between two identical queries of different tables
35
StaffNo Fname Lname Position Salary
222 Head Honcho CEO 35000
322 Mark Jones Manager 20000
261 Julie Walters Director 40000
260 Julie Walters Tax Shelter 20000
555 Dogollan Body Cleaner 500
444 Trinity Wells Porter 200
401 Taffy Truman Manager 30000
322 Gareth Whirlwind Manager 32500
Using Subqueries ‐ Nested SELECTs
• If we know that a SELECT statement will produce a single value or row we can use this value directly in a simple predicate.
• This subquery must appear in brackets (); ORDER BY can't appear in a subquery; most subqueries can't have more than 1 table in SELECT list
• Can appear after a relational operator, function or set operator in WHERE SELECT & HAVING clauses
CO7101: Java & Databases For Bioinformatics 206
WHERE, SELECT & HAVING clauses
• Example: find all members of staff who earn more than the managers:
SELECT * FROM Staff WHERE Salary > (SELECT Salary FROM Staff WHERE Position ='Manager');
Doesn't work when we introduce multiple managers!
Subqueries That Give a List of Values
• If the SELECT statement is expected to produce a list of values, we can use the IN, ANY, ALL or EXISTS keywords to operate on the list.
• Example: find those members of staff who are not managers but earn more than anymanagers:SELECT * FROM Staff WHERE Position <> 'Manager'
CO7101: Java & Databases For Bioinformatics 207
gAND Salary > ANY (SELECT Salary FROM Staff WHERE Position = 'Manager');
ANY: Predicate is true if it matches ANY value in the liste.g. statement is true if staff is not a manager and has a higher salary than any manager.
SELECT * FROM Staff WHERE Position <> 'Manager' AND Salary > SOME (SELECT Salary FROM Staff WHERE Position ='Manager');
SOME: Synonym for any (i.e. you can use SOME or ANY interchangably)
Subqueries That Give a List of Values
SELECT * FROM Staff WHERE Position <> 'Manager' AND Salary > ALL (SELECT Salary FROM Staff WHERE Position ='Manager');ANY: Predicate is true if it matches ALL value in the liste.g. statement is true if staff is not a manager and has a higher salary than ALL the managers.
CO7101: Java & Databases For Bioinformatics 208
• SELECT * FROM Staff WHERE position IN ('Manager', 'Supervisor');IN: Predicate is true if the test element is in the list; (i.e. if position is IN the set of values we supply ‐Manager or Supervisor)
Subqueries That Give a List of Values
• SELECT staffNo, fName, lName, position FROM Staff s WHERE EXISTS (SELECT * FROM Branch b WHERE s.branchNo=b.branchNo AND city='London';
• EXISTS: Predicate is true if list is non‐empty (i.e. it exists); so in the above example it is true if only for use with
CO7101: Java & Databases For Bioinformatics 209
p ysubqueries.
Querying Multiple Tables
PropertyForRent
PropertyNo Street City Postcode Type Rooms Rent OwnerNo StaffNo BranchNo
PA14 16 Holhead Aberdeen AB7 5SU House 6 650 CO46 SA9 B007
PG16 5 Novar Dr Glasgow G12 9AX Flat 4 450 CO93 SG14 B003
PG21 18 Dale Rd Glasgow G12 House 5 600 CO87 SG37 B003
PG36 2 Manor Rd Glasgow G32 4QX Flat 3 375 CO93 SG37 B003
PG4 6 Lawrence St Glasgow G11 9QX Flat 3 350 CO40 B003
•How do we list all the properties that a given client has viewed?•Could start with an example - e.g. client CR56 ...
CO7101: Java & Databases For Bioinformatics 210
PL94 6 Argyll St London NW2 Flat 4 400 CO87 SL41 B005
ViewingClientNo PropertyNo ViewDate Comment
CR56 PA14 24-May-01 too small
CR56 PG36 28-Apr-01
CR56 PG4 26-May-01
CR62 PA14 14-May-01 no dining room
CR76 PG4 20-Apr-01 too remote
ClientClientNo Fname Lname TelNo PrefType MaxRent
CR56 Aline Stewart 0141-848-1825 Flat 350
CR62 Mary Tregear 01224-196720 Flat 600
CR74 Mike Ritchie 01475-392178 House 750
CR76 John Kay 0207-774-5632 Flat 425
36
Property Query ‐ First Attempt
• First attempt: List the property numbers viewed by client number 'CR56':
SELECT PropertyNoFROM ViewingWHERE ClientNo = 'CR56';
• But we'd like to see the client name & property details• So we'll need to access Client and PropertyForRent for
names etc
CO7101: Java & Databases For Bioinformatics 211
names etc...• To obtain info from >1 table: subqueries or joins; for result
table to contain columns from >1 table: join.• Recall subqueries: SELECT * FROM Staff WHERE branchNo =
(SELECT branchNo FROM Branch WHERE street = '163 Main St');
Property Query ‐ Second Version
SELECT DISTINCT Viewing.PropertyNo, Street, City, ViewDate
FROM Viewing, PropertyForRentWHERE ClientNo = 'CR56'AND Viewing.PropertyNo = PropertyForRent.PropertyNo; (matching
cols)
CO7101: Java & Databases For Bioinformatics 212
• We now have two table names in the FROM clause• Note use of “Table.ColumnName" to avoid ambiguity in
column names (i.e. both Viewing and PropertyForRenthave a PropertyNo column)
Property Query ‐ Third VersionSELECT DISTINCT Fname, Lname, Street, City, ViewDateFROM Viewing, PropertyForRent, ClientWHERE Viewing.ClientNo = 'CR56'AND Viewing.PropertyNo = PropertyForRent.PropertyNoAND Viewing.ClientNo = Client.ClientNo;
CO7101: Java & Databases For Bioinformatics 213
• The two “AND" clauses are called join criteria• Note for later: primary key= parent & foreign key=child: this is
parent/child relationship, or one‐to‐many (1:*), e.g. PropertyForRent/Viewing; more info on relational algebra can be found in !!.
Property Query ‐ Fourth Version
• Users shouldn't have to know about internal keys...SELECT DISTINCT Fname, Lname, Street, City, ViewDate
FROM Viewing, PropertyForRent, Client
WHERE Fname = 'Aline' AND Lname = 'Stewart'
AND Viewing.PropertyNo = PropertyForRent.PropertyNo;
CO7101: Java & Databases For Bioinformatics 214
AND Viewing.ClientNo = Client.ClientNo;
Using Table Aliases
• Table aliases can help reduce amount of typing• The following is identical to the previous query:
SELECT C.Fname, C.Lname, P.Street, P.City, V.ViewDate
FROM Viewing V, PropertyForRent P, Client CWHERE C.Fname = 'Aline' AND C.Lname = 'Stewart'
CO7101: Java & Databases For Bioinformatics
215
AND V.PropertyNo = P.PropertyNoAND V.ClientNo = C.ClientNo;
• Table aliases help reduce the risk of typing mistakes• But shouldn't the DBMS know how to match keys for us? Only if they appear in 1 table
Simple JoinsSELECT c.clientNo, fName, lName, propertyNo
FROM Client c, Viewing v
WHERE c.clientNo = v.clientNo; implicit join
SELECT c.clientNo, fName, lName, propertyNo
FROM Client c
JOIN Viewing v ON c.clientNo = v.clientNo; ‐> 2 clientNo cols
SELECT c.clientNo, fName, lName, propertyNo
FROM Client JOIN Viewing USING clientNo; explicit join
CO7101: Java & Databases For Bioinformatics
216
g ; p j
SELECT c.clientNo, fName, lName, propertyNo
FROM Client NATURAL JOIN Viewing; (only joins matched rows)
3 table query:
SELECT c.clientNo, c.fName, c.lName, p.propertyNo
FROM Client c, Viewing v, PropertyForRent p
WHERE c.clientNo = v.clientNo AND v.propertyNo = p.propertyNo;
• ORDER BY still works, just specify table.colName
• Specify table.colNo when colNo appears in >1 table; can also do this to be clearer
37
Cross Joins (Cartesian Products)
• Cartesian Product: a join with no WHERE clause, selects everything from both tables (most general join)
SELECT * FROMLeft, Right;
• mySQL allows:SELECT * FROM
CO7101: Java & Databases For Bioinformatics
217
Left CROSS JOIN Right;• Useful for:
– query optimisation– data mining
• Inner joins are type of cross join• Inner join (a type of cross join) only returns rows which
meet specified criteria, can be equijoins (a type of theta join which uses only =), or natural joins (a type of equijoin which selects rows w/ common values); Outer join returns matching & unmatching rows
Natural Joins
• Natural joins implement relationships in the Relational model• They are a type of equijoin which selects rows with common values
between tables • The DBMS will know which columns are key columns• The following queries are equivalent:
SELECT C.Fname, C.Lname, P.Street, P.City, V.ViewDateFROM Client C NATURAL JOIN
CO7101: Java & Databases For Bioinformatics
218
FROM Client C NATURAL JOIN(Viewing V NATURAL JOIN PropertyForRent P)WHERE C.Fname = 'Aline' AND C.Lname = 'Stewart';andSELECT C.Fname, C.Lname, P.Street, P.City, V.ViewDateFROM Viewing V, PropertyForRent P, Client CWHERE C.Fname = 'Aline' AND C.Lname = 'Stewart'AND V.PropertyNo = P.PropertyNoAND V.ClientNo = C.ClientNo;
• Most DBMSs support 4‐table joins, or more...
mySQL Syntax for Joins
• mySQL allows joins to be written in different ways:
• Natural joins:SELECT * FROM Left NATURAL JOIN Right;SELECT * FROM Left JOIN Right USING ColNam;
• If not joining on keys, give join condition explicitly:
CO7101: Java & Databases For Bioinformatics
219
SELECT * FROM Left JOIN Right
ON Left.ColNam = Right.ColNam;
• You can do implicit joins
• Which is best ? ‐Make up your own mind, but be aware with how they relate to each other
Theta Joins
• “Theta join" is a type of inner join (only returns rows which meet specified criteria) which have a more general WHERE predicate than equijoins (which only match on equality):
SELECT L.*, R.*, ...FROM Left L, Right RWHERE L.LeftCol Θ R.Rightcol;
CO7101: Java & Databases For Bioinformatics
220
• Θmay be one of =; ! =; <>; <; >; <=; >=• If Θ is =, its an equi join• If Θ is = and matches on key columns its a natural join• If all output columns are from one table, its a semi join
(equivalent to a subquery)
Example of a Theta Join
• For all clients, list the properties that each client can afford to rent:
SELECT C.ClientNo, P.PropertyNo
FROM Client C, PropertyForRent P
WHERE C MaxRent >= Prent;
CO7101: Java & Databases For Bioinformatics
221
WHERE C.MaxRent >= P.rent;
• The DBMS could implement theta joins by:
– First forming a cross join to give...
– An intermediate (Cartesian product) table..
– Then applying WHERE clause to find matching rows
– Notice that the relation is >= not =
Self‐Joins
• Sometimes it is useful to join a table to itself (must use aliases)
ALTER TABLE Staff ADD COLUMN BossNo CHAR(5);
SELECT S.Lname AS Person, B.Lname as Boss
FROM Staff S, Staff B
CO7101: Java & Databases For Bioinformatics 222
,
WHERE S.BossNo = B.StaffNo;
38
Outer Joins(Selecting unmatched rows)
• Inner join (a type of cross join) only returns rows which meet specified criteria, can be equijoins (a type of theta join which uses only =), or natural joins (a type of equijoin which selects rows w/ common values); Outer join returns matching & unmatching rows
• Example: List the branch offices and properties in the same city, along with any unmatched branches:
SELECT B.BrNo, P.PropNoFROM PropForRent P RIGHT JOIN Branch B ON B.City = P.City;
CO7101: Java & Databases For Bioinformatics 223
• NB. Not all DBMSs (e.g. Microsoft Access) support outer joins
Right Outer Joins & Full Outer Joins
• In a similar manner, can use RIGHT JOIN and FULL JOIN (meaning full outer join):
SELECT B.BrNo, P.PropNo
FROM Branch B FULL JOIN PropertyForRent P
ON B Cit PCit
CO7101: Java & Databases For Bioinformatics 224
ON B.City = P.City;
Types of Join
• Theta join ‐ inner join using a simple WHERE predicate
• Equi join ‐ a special case of theta join (= predicate)
• Natural join ‐ special case of equi join (match keys)
• Semi join ‐ theta join that outputs from just one table
CO7101: Java & Databases For Bioinformatics
225
• Self join ‐ joining a table to itself
• Outer join ‐may include unmatched rows; left/right/full
• Inner join – a join that only includes matched rows
• Cross join ‐ Cartesian products (no predicates); most general
Types of Join
• Explicit join uses the keyword JOIN,
• Implicit join does not use the keyword JOIN– specifies a cross‐join– WHERE clause may apply additional filter‐predicates– filter‐predicates function comparably to join‐predicates in the
explicit notation
CO7101: Java & Databases For Bioinformatics
226
explicit notation.
• Why do we need to distinguish so many different types of join ?
• Queries with different joins are often optimiseddifferently...
• Lots of online resources, e.g., http://www.w3schools.com/sql/, www.wikipedia.org, etc. The Web is your friend.
CO7101: Java & Databases For Bioinformatics
SQL 4:
CO7101: Java & Databases For Bionformatics
227
Implementing Relationships Using Keys & Using Natural Joins
Dr. Stuart Kerrigan
Previously on CO1019
• Queries involving multiple tables
• Different types of join
– Natural Join uses keys specified in table
• Relationships
– 1‐* relationships
– 1‐1 relationships
– *‐* relationships
CO7101: Java & Databases For Bionformatics
228
39
In this lecture you will learn
• SQL data types & related scalar functions• How to declare
– primary keys– foreign keys
i i d d l
229
– unique indexed columns• And how to ensure MySQL maintains the integrity constraints
• How integrity constraints can affect row operations
SQL's Integrity EnhancementFeatures (IEF)
• Real databases are often very ‘active’ with 100s of users simultaneously querying and updating the DB.
• So database integrity is important• IEFs allow the DB designer to specify & enforce:
– domain constraints
230
domain constraints– required data– entity integrity– referential integrity– enterprise constraints (business rules)
Creating Tables ‐ Data Definition
• CREATE TABLE is used to define relational tables
• Defines the data type for each column
• Also defines rules for how data is inserted and deletedCREATE TABLE Staff (StaffNo VARCHAR(5),Lname VARCHAR(20),
231
Salary FLOAT,HireDate DATE);
• VARCHAR, FLOAT, and DATE are examples of domains
• Also some rules are implied here– StaffNo is up to 5 characters long,
– Lname is 20 characters long
• Domains specify type & range of allowed data values
Built‐in Data Types (Domains) in MySQL
• SQL supports many data types (vendors often also have own dialects):– CHARACTER (CHAR), CHARACTER VARYING (VARCHAR)– NUMERIC, DECIMAL (DEC), INTEGER (INT), SMALLINT– FLOAT, REAL, DOUBLE PRECISION
232
– DATE, TIME, TIMESTAMP– BOOLEAN, BIT– BINARY LARGE OBJECT (BLOB), etc.
• Some types have an associated size . e.g. CHAR(5)
Required Data& More Domain Constraints
• NOT NULL means row can not contain nulls• Example:
CREATE TABLE Staff (StaffNo VARCHAR(5) NOT NULL,Lname VARCHAR(20) NOT NULL,Salary FLOAT CHECK (Salary BETWEEN 5050
and 20000),HireDate DATE);
• StaffNo & Lname are required ‐may not be NULL• Domain Constraints: specifies what’s ok in col/table• CHECK gives a domain constraint for Salary• Updates & insertions will fail if constraints not satisfied
Scalar Functions
• Scalar functions may be used to convert/manipulate data values (remember aggregates: MIN, MAX, etc.)
• Example:SELECT SUBSTRING(Lname, 1, 3),CONVERT(INTEGER Salary),EXTRACT(YEAR FROM HireDate)
234
FROM Staff;
• MySQL supports many scalar functions
ResultSMI 12075 1990
40
Entity Integrity ‐ Primary Keys• Reminder: the primary key of each row in a table must
be unique and non‐null.
• Example: The primary key of the Viewing table is composed of two attributes (composite key):
CREATE TABLE Viewing (ClientNo VARCHAR(5) NOT NULL,
235
PropertyNo VARCHAR(5) NOT NULL,PRIMARY KEY (ClientNo, PropertyNo))ENGINE=INNODB;
• The primary key of this table is a composite key
• SQL will reject operations that would violate primary key uniqueness
Entity Integrity ‐ Primary Keys• Primary key of the Guest table in a hotel database is
one attribute:‐CREATE TABLE Guest (GuestNumber INT NOT NULL,FirstName VARCHAR(15),LastName VARCHAR(15),PRIMARY KEY (GuestNumber)) ENGINE=INNODB;
• ENGINE=INNODB required to handle all keys.
• What about foreign keys?
• What about unique foreign keys for 1‐1 relationships
236
Referential Integrity ‐ Foreign Keys
• Foreign key links a child table to parent table. If non‐null, should match a row of parent table.
• SQL has keywords for this:CREATE TABLE Room(RoomName VARCHAR(20) NOT NULL,GuestNumber INT NOT NULL,
237
,FOREIGN KEY (GuestNumber) REFERENCES Guest(GuestNumber),PRIMARY KEY (RoomName)) ENGINE=INNODB;
• SQL will reject operations that would violate referential integrity
Populate TablesGuestGuestNumber (Primary Key)
First Name LastName
1 Bob Hope
2 Tim Gall
CO7101: Java & Databases For Bionformatics
238
3 Anne Example
4 Gilmore Running
INSERT INTO Guest VALUES (1,'Bob','Hope'), (2,'Tom', 'Gall'), (3,'Anne','Example'), (4,'Gilmore','Running');
Populate Tables
Room GuestGuestNumber (Primary Key)
First Name LastName
1 Bob Hope
2 Tim Gall
3 Anne Example
4 Gilmore Running
RoomName(Primary Key)
GuestNumber(Foreign Key)
Oakley Room 1
SamhayneRoom
1
Wood Room 2
Stoat Room 3
CO7101: Java & Databases For Bionformatics
239
Stoat Room 3
Eagle Room 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 Room',3), ('Eagle Room',4);
Using a Natural Join
SELECT RoomName, FirstName, LastName
FROM Guest NATURAL JOIN Room;
CO7101: Java & Databases For Bionformatics
240
Room Guest0..* 1..1
41
UNIQUE Values• UNIQUE ( cols )
• Example:CREATE TABLE Room(RoomName VARCHAR(20) NOT NULL,GuestNumber INT NOT NULL,UNIQUE (GuestNumber),FOREIGN KEY (G tN b ) REFERENCES G tFOREIGN KEY (GuestNumber) REFERENCES Guest(GuestNumber),PRIMARY KEY (RoomName)) ENGINE=INNODB;
• 1 guest must occupy 1 room – so no
• What happens if we remove NOT NULL on GuestNumber?
241
Repopulate TablesRoom Guest
GuestNumber (Primary Key)
First Name LastName
1 Bob Hope
2 Tim Gall
RoomName(Primary Key)
GuestNumber(Foreign Key)
Oakley Room 1
SamhayneRoom
1
CO7101: Java & Databases For Bionformatics
242
3 Anne Example
4 Gilmore Running
GuestNumber must be unique – this line would violate
integrity
Room
Wood Room 2
Stoat Room 3
Eagle Room 4
Repopulate TablesRoom Guest
GuestNumber (Primary Key)
First Name LastName
1 Bob Hope
2 Tim Gall
3 Anne Example
RoomName(Primary Key)
GuestNumber(Foreign Key)
Oakley Room 1
Wood Room 2
Stoat Room 3
CO7101: Java & Databases For Bionformatics
243
4 Gilmore RunningEagle Room 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);
Relationships
SELECT RoomName, FirstName, LastName
FROM Guest NATURAL JOIN Room;
CO7101: Java & Databases For Bionformatics
244
Room Guest0..1 1..1
Relationships without Not Null
CREATE TABLE Room(RoomName VARCHAR(20) NOT NULL,GuestNumber INT, UNIQUE (GuestNumber), FOREIGN KEY (GuestNumber) REFERENCES Guest (GuestNumber), PRIMARY KEY (RoomName)) ENGINE=INNODB;
CO7101: Java & Databases For Bionformatics
245
Room Guest
0..1 0...1
Repopulate TablesRoom Guest
GuestNumber (Primary Key)
First Name LastName
1 Bob Hope
2 Tim Gall
3 Anne Example
4 Gilmore Running
RoomName(Primary Key)
GuestNumber(Foreign Key)
Oakley Room 1
Wood Room 2
Stoat Room 3
Eagle Room 4
CO7101: Java & Databases For Bionformatics
246
4 Gilmore RunningEagle Room 4
Haunted Room NULL
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);
42
Relationships
SELECT RoomName, FirstName, LastName
FROM Guest NATURAL JOIN Room;
CO7101: Java & Databases For Bionformatics
247
Room Guest1 0..1
Relationships
SELECT RoomName, FirstName, LastName FROM Room LEFT JOIN Guest ON Guest.GuestNumber=Room.GuestNumber;
CO7101: Java & Databases For Bionformatics
248
Room Guest1 0..1
Relationships
SELECT RoomName, FirstName, LastName FROM Guest RIGHT JOIN Room ON Guest.GuestNumber=Room.GuestNumber;
CO7101: Java & Databases For Bionformatics
249
Room Guest1 0..1
Relationships• MySQL only supports one‐to‐many or one‐to‐one relationships
• Implement many to many relationships via a third table
Room Guest0..* 0..*
is in MySQL a third table• Two one‐to‐many relationships A ‐> AB and B ‐> AB.
• The logical primary key for AB is formed from the two foreign keys
CO7101: Java & Databases For Bionformatics
250
Room(A) 0..1 0..*
Guest(B)
0..* 0..1RoomAllocation
(AB)
represented by
Redesigning TablesCREATE 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;
CO7101: Java & Databases For Bionformatics
251
Room(A) 0..1 0..*
Guest(B)
0..* 0..1Room
Allocation
(AB)
Repopulate Tables
Room GuestNumber (Primary Key)
First Name
LastName
1 Bob Hope
2 Tanya Hope
3 Anne Example
RoomName(Primary Key)
Oakley Room
Stoat Room
Eagle Room
Guest
RoomName(Composite Primary Key and Foreign Key)
GuestNumber(Composite PrimaryKey and Foreign Key)
Oakley Room 1
Oakley Room 2
Stoat Room 3
RoomAllocation
CO7101: Java & Databases For Bionformatics
252
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);
Eagle Room 3
43
RelationshipsSELECT FirstName, LastName, Room.RoomName FROM Guest NATURAL JOIN (Room NATURAL JOIN RoomAllocation);
CO7101: Java & Databases For Bionformatics
253
Room Guest0..* 0..*
Referential Integrityand Referential Actions
• Question: if a key attribute in the parent table is modified, what should happen in the child table ? ‐ SQL provides 4 alternative referential actions:
• ON UPDATE & ON DELETE specify referential actions which determines what happens when an attempt to UPDATE or DELETE a candidate key in a parent table which has matching rows in child table:
FOREIGN KEY (Key) REFERENCES Table [ON DELETE | UPDATE Action]– CASCADE ‐ apply changes to child rows (could trickle down)
254
CASCADE apply changes to child rows (could trickle down)– SET NULLDEFAULT ‐ set child keys to NULL– SET ‐ set child keys to DEFAULT value– NO ACTION ‐ reject the operation (default)
• Suppose a room’s name is changed. What is the most appropriate action?• Suppose a room is deleted. What is the most appropriate action?
Referential Integrityand Referential Actions
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;
255
RoomRoomName(Primary Key)
Oakley Room
Stoat Room
Eagle Room
RoomName(Composite Primary Key and Foreign Key)
GuestNumber(Composite PrimaryKey and Foreign Key)
Oakley Room 1
Oakley Room 2
Stoat Room 3
Eagle Room 3
RoomAllocation
Referential Integrityand Referential Actions
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 Room' WHERE
256
UPDATE Room SET RoomName = Condor Room WHERE RoomName = 'Oakley Room';
RoomRoomName(Primary Key)
Oakley Room
Stoat Room
Eagle Room
RoomName(Composite Primary Key and Foreign Key)
GuestNumber(Composite PrimaryKey and Foreign Key)
Oakley Room 1
Oakley Room 2
Stoat Room 3
Eagle Room 3
RoomAllocation
Referential Integrityand Referential Actions
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
257
UPDATE RoomAllocation SET RoomName = Condor Room' WHERE RoomName = 'Oakley Room';
RoomRoomName(Primary Key)
Condor Room
Stoat Room
Eagle Room
RoomName(Composite Primary Key and Foreign Key)
GuestNumber(Composite PrimaryKey and Foreign Key)
Oakley Room 1
Oakley Room 2
Stoat Room 3
Eagle Room 3
RoomAllocation
Referential Integrityand Referential Actions
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
258
UPDATE RoomAllocation SET RoomName = Condor Room' WHERE RoomName = 'Oakley Room';
RoomRoomName(Primary Key)
Condor Room
Stoat Room
Eagle Room
RoomName(Composite Primary Key and Foreign Key)
GuestNumber(Composite PrimaryKey and Foreign Key)
Condor Room 1
Condor Room 2
Stoat Room 3
Eagle Room 3
RoomAllocation
44
Enterprise Constraints(Business Rules)
• Sometimes, real‐world business rules involve constraints that refer to more than one table. Its useful to define enterprise constraints just once.
• Example: A member of staff may manage no more than 100 properties:
259
than 100 properties:CREATE ASSERTION StaffNotOverLoadedCHECK (NOT EXISTS(SELECT StaffNo FROM PropertyForRentGROUP BY StaffNo HAVING COUNT (*) > 100));CREATE TABLE PropertyForRent ( ...CONSTRAINT StaffNotOverLoaded);
Database Schemas Evolve Over Time
• Ideally, a database is created once and then used for many years ... BUT
• The data model may be improved (integrity, performance) ...
N f b dd d i l
260
• New features may be added in new releases ...
• Enterprise rules may change ...
• Therefore, SQL provides many options for changing tables:
• See ALTER TABLE in the MySQL Documentation
Summary So Far...
• DBs are ‘active’ or ‘alive’ ‐ contents always changing
• The structure of a DB can also evolve over time...
• DB contents should always be consistent ‐ integrity
• ANSI SQL provides several Integrity Enhancement Features (IEFs)
261
(IEFs)
• IEF => domain constraints, entity/referential integrity, business rules...
• IEFs imply additional design choices for new DBs
• One DBMS can manage multiple DBs ‐ notion of schemas & privileges
CO7101: Java & Databases For Bioinformatics
SQL 5: Views and the Data Control Language
CO7101: Java & Databases For Bionformatics
262
SQL 5: Views and the Data Control Language
Dr. Stuart Kerrigan
Previously on CO1019
• Data Definition Language– CREATE DATABASE, DROP DATABASE etc.
– CREATE TABLE, ALTER TABLE, DROPCREATE TABLE, ALTER TABLE, DROP TABLE
• Data Manipulation Language– SELECT, UPDATE, DELETE, INSERT
• What about Data Control Language?
263
In this lecture you will learn
• the principles of object (tables, etc.) ownership & privileges
• what virtual tables (views) are and why they are useful
h i d fi d & i i• how views are defined & some constraints on views
• how views can be implemented & some processing issues
• how views & privileges may be combined to provide access control
264
45
The Importance of Views & Privileges
• DBMSs are primarily used in organisations, and in large organisations, DBMSs are used by a range of staff:– directors, managers, analysts, engineers, personnel, secretarial, etc.
• Consequently, access to data in different tables may need to be controlled to:– provide access to authorised users
– restrict access to unauthorised users (security)…what could happen if a db was hacked?!
– enforce business rules or government regulations
• Views & privileges can help implement access control ...
265
SQL's Access Control Model
• Access Control in SQL is similar to multi‐user operating systems (e.g. Unix, Windows, ...)
• A user supplies an Authorisation Id and password to the DBMS
• The DBMS opens a session for the user• The DBMS runs SQL statements on behalf of the user
Th b th f bj t h t• The user becomes the owner of any objects he creates• By default, only the owner may access his objects• The owner may grant and revoke access privileges to other
users • This is discretionary access control• Mandatory access control: strictly ordered classification level
of db objects & users are given clearance levels (not supported by SQL)
266
Granting Privileges• Discretionary access based on authorization identifiers
(username&password), ownership (specified by auth.id.) & privileges (actions user can carry out on the given table, e.g., SELECT, etc.)
• GRANT { PrivilegeList | ALL PRIVILEGES } ON ObjectNameTO { AuthIdList | PUBLIC } [ WITH GRANT OPTION ]
• where (typically):– ObjectName is a table– PrivilegeList may be a combination of:
• SELECT, INSERT, UPDATE, DELETE (can specify column names)• REFERENCES (column names referenced by integrity constraints, e.g.,
check or foreign key constraints)• USAGE (use of domain definitions)• WITH GRANT OPTION means users in AuthIdList can pass on
privileges to others
267
Examples of UsingSQL Access Control
• Allow any member of staff (with an Auth ID) to access the Client table:
GRANT ALL PRIVILEGES ON Client TO PUBLIC
• Allow only personnel staff to hire staff or to change their salaries:
GRANT SELECT, INSERT, UPDATE (Salary) ON Staff TO personnel
• Privileges are revoked in a similar manner:REVOKE { PrivilegeList | ALL PRIVILEGES }ON ObjectNameFROM { AuthIdList | PUBLIC } [ RESTRICT | CASCADE ]Recall: CASCADE will delete all related objects which reference the table, and RESTRICT will reject the DROP if there are dependent objects
268
What are Views?
• A view is a virtual table, constructed from base tables• Why would we want to do this?• Only the definition of a view is stored permanently (as a
query)• A view is realised dynamically when it is first referenced
3 f i h i l i l d/j i d• 3 types of views: horizontal, vertical, grouped/joined• Views are manipulated like other DBMS objects:
CREATE VIEW ViewName ... (next slide)DROP VIEW ViewName;GRANT ALL PRIVILEGES ON ViewName TO PUBLIC;REVOKE ALL PRIVILEGES ON ViewName FROM PUBLIC;
269
Creating Views ‐ Horizontal Views
• A horizontal view restricts the rows that may be seen:CREATE VIEW Manager3Staff AS (subselect)
SELECT * FROM Staff WHERE BranchNo = 'B003'; (defining query)
• Then...SELECT * FROM Manager3Staff;So now branch manager can only see details of her own branch
Manager3Staff
StaffNo Fname Lname Position Sex Salary BranchNo
SG37 Ann Beech Assistant F 12000 B003
SG5 Susan Brand Manager F 24000 B003
270
46
Creating Views ‐ Vertical Views
• A vertical view restricts the columns that may be seen:CREATE VIEW Staff3 AS (subselect/defining query)SELECT StaffNo, Fname, Lname, Position FROMManager3Staff; notice the view here!
• Then...SELECT * FROM Staff3;
• So now the viewer can’t see the salary info of staff members (only the y ( ymanager sees this)…
Staff3
StaffNo Fname Lname PositionSG37 Ann Beech Assistant
SG5 Susan Brand Manager
271
General Syntax for Creating Views
• General syntax:CREATE VIEW ViewName [ (NewColNames) ] ASSubSelect;
• The SubSelect clause is called the defining query
• To create a view, a user must have SELECT privilege on the b blbase tables
• Once created, views often behave like ordinary base tables ...
• Views can be used in SELECT or JOIN clauses
• Views can be updated (with some restrictions)
• DROP VIEW ViewName [RESTRICT|CASCADE]
272
Grouped & Joined Views
• Views can be used to help simplify complex queries
• Example: create a view showing the number of properties managed by each member of staff and the branches they work at:
CREATE VIEW StaffProperties (StaffNo, BranchNo,Properties) ASSELECT s.StaffNo, s.BranchNo, COUNT (*)FROM St ff P t F R tFROM Staff s, PropertyForRent pWHERE s.StaffNo = p.StaffNoGROUP BY s.BranchNo, s.StaffNo; ‐‐GROUP BY stmt in subselect grouped view
‐‐Multiple tables in subselect joined view
‐‐Joined View simplifies querying; now we just query the view
• Can now query StaffProperties as if it’s a base tableSELECT * FROM StaffProperties;
273
How Are Views Implemented?
• Most DBMSs implement views using view resolution, which translates stored query into actual query on src tables specified in the view
• SQL re‐writes the view references back to the underlying base tables
• view materialisation: alternative implementation
• SQL populates a temporary table when the view is first referenced and keeps it up‐to‐date
• However, keeping the temporary table up‐to‐date can be difficult...
• View materialisation is an active area of DB research
274
How to Access Other Users' Objects
In SQL, the full name of a table has the form:server.schema.owner.tablee.g. achilles.mcscw3.sk223.student
If the System Administrator (user 'sa') owns all of the DreamHome tables and user 'sbrand' manages Branch 3DreamHome tables, and user sbrand manages Branch 3,
The sa might enter:USE Dreamhome;GRANT SELECT ON Manager3Staff TO sbrand;
Then, user sbrand could reference the view as:SELECT * FROM Dreamhome.sa.Manager3Staff;
Or equally:SELECT * FROM Dreamhome.Manager3Staff;
275
Restrictions on Views• With views, some queries are not permitted:–Queries that resolve to nested aggregates, e.g., SELECT COUNT(cnt) FROM StaffPropCnt; (cnt is based on an aggregated fn)
Q i th t i t i–Queries that give aggregates in a WHERE clause, e.g., SELECT * FROM StaffPropCnt WHERE cnt>2; (cnt derived from an aggregate fn)
–Grouped views can’t be joined with a base table or view
276
47
Restrictions on Views• Views can be updated provided:
– There are no aggregates in the columns to be updated and DISTINCT isn’t specified (can’t eliminate duplicate rows from query results)
– There are no GROUP BY or HAVING clauses because this info doesn’t say where it came from; in INSERT INTO StaffPropCnt VALUES(‘B003’,’SG5’,2) we don’t know which 2 properties SG5 manages (don’t know appropriate primary key values in PropertyForRent)
– The view contains only one source table (i.e., no joined views, Unions, Int’s or set diff. (EXCEPT)) with no nested SELECTs; also every elt in SELECT must appear only 1x, & can only be a col
– Can’t violate integrity constraints of base table either (e.g.: no NULLs where NULLS not allowed)
– Otherwise (i.e., if the row/col in view can be traced back to its source table), changes to view means changes to base tables (i.e., view can be updatable)
277
Updating ViewsAn Important Subtlety
SQL allows a view to be updated provided the changed rows in the base tables still satisfy all of the conditions of the defining query's WHERE clause.
For example:UPDATE Manager3Staff SET BranchNo = 'B005'WHERE StaffNo = 'SG37';
This would fail because the modified row (BranchNo = 'B005') would no longer be selected by the view definition (WHERE BranchNo = 'B003').)◦ WITH CHECK OPTION of CREATE VIEW stmt: View updates may not
allow rows to migrate out of the view ◦ WITH LOCAL CHECK OPTION means any updates on this or related obj
can’t cause rows to disappear from this view unless it also disappears from the other view
◦ WITH CASCADED CHECK OPTION (default) means any updates on this view & on related views can’t cause rows to disappear from this view
◦ Can exploit this behaviour to help enforce DB integrity◦ Put domain/business constraints into the view definition & only
update views
278
Summary of Views• Advantages:
– Views help provide granularity of access control– Views can help reduce complexity (simplify tables & (e.g.) multi‐table queries) and
improve access control, e.g., customization (same tables can be seen differently by
different users) & convenience (users see only what they need), improved security (views appropriate for user, restricts access to db), constancy (view shows part of base tables & if base cols not in view chg, no effect), currency (changes to base table accessed in view are immediately seen in view)
– Views can help maintain DB integrity (e.g. by doing updates via views, recall that if WITH CHECK OPTION is used, all updates must satisfy defining query’s WHERE clause)
• Disadvantages:• Disadvantages:– There are some restrictions on their use: some views can’t be updated. can’t do
aggregates on aggregates in SELECT clause or use an aggregate fn in WHERE clause; also grouped views can’t be joined with a base table/view, etc.
– Implementation: resolution method can cause a performance penalty (here defining query is run on base tables again each time; prob w/ frequent access)
– Structure restriction: downside of constancy (SELECT * FROM Foo only selects cols which were in Foo when View was created; view needs to be recreated for new cols in Foo to appear in View)
– Materialisation method can cause consistency problems (stores temp table on first view query, but hard to maintain currency if base tables updated)
279
SQL ‐ Overall Summary• SQL is a powerful relational DB query language
• SQL is declarative, not procedural (e.g. no variables)
• SQL is showing its age ... (e.g. quirky syntax, bolted‐on features)
• But despite being over 25 years old...
• SQL remains THE ‘world‐standard’ for DBMSsSQL remains THE world standard for DBMSs
• Make sure you understand SELECT, JOIN, UPDATE etc. and qualifications of these & can extract the info you want; make sure you can do everything we’ve done in the practicals at the least
280
Next…
The Internet (done)
HTML (done)
Relational Databases (done)
MySQL (done)
281
y Q ( )
PHP(combining HTML & MySQL)
Chapter 0
Introduction to Computers
and
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 0 - 282
Programming Languages
48
A History of Computers• Charles Babbage is credited as the father of computer. Although never
actually built, he proposed the computing machines called Difference Engine
and Analytical Engine that possessed the core characteristics of today’s
computers.
• Ada Lovelace, who wrote demonstration programs for Analytical Engine, is credited as the first programmer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 0 - 283
• The first modern computer was built by Atanasoff of Iowa State University in the late 1930s.
• An electromechanical computer MARK I was built by Howard Aiken of Harvard.
• The first completely electronic computer ENIAC I was built by Mauchly and Eckert of the University of Pennsylvania.
Computer Architecture
CPU
OutputDevices
Commu-i ti
RAM
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 0 - 284
CPUnicationDevices
InputDevices
StorageDevices
Progress of CPU Speed
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 0 - 285
For more information on Intel CPUs, click Intel Museum or Quick Reference Chart.
Programming Languages
• Three levels of programming languages:
– Machine Languages– Machine language instructions are binary coded and very low
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 0 - 286
Machine language instructions are binary coded and very low level.
– Assembly Languages– Assembly language allows symbolic programming. Requires an assembler to translate assembly programs into machine programs.
– High‐level Languages– High‐level language provides a very high conceptual model of computing. Requires a compiler to translate high‐level pograms into assembly programs.
Java
• Java is a high‐level object‐oriented language developed by Sun Microsystems.
• Java’s clean design and wide availability make it an ideal language for teaching the
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 0 - 287
it an ideal language for teaching the fundamentals of computer programming.
Chapter 1
Introduction to Object‐Oriented Programming and Software
Development
. 4th Ed Chapter 1 - 288
Animated Version
49
Objectives
After you have read and studied this chapter, you should be able to
• Name the basic components of object‐oriented programming
• Differentiate classes and objects.
• Differentiate class and instance methods• Differentiate class and instance methods.
• Differentiate class and instance data values.
• Draw program diagrams using icons for classes and objects
• Describe significance of inheritance in object‐oriented programs
• Name and explain the stages of the software lifecycle
. 4th Ed Chapter 1 - 289
Classes and Objects
• Object‐oriented programs use objects.
• An object is a thing, both tangible and intangible. Account, Vehicle, Employee, etc.
T t bj t i id th t• To create an object inside the computer program, we must provide a definition for objects—how they behave and what kinds of information they maintain —called a class.
• An object is called an instance of a class.
. 4th Ed Chapter 1 - 290
Graphical Representation of a Class
<Class Name> We use a rectangle to represent a class with its name appearing inside the rectangle.
. 4th Ed Chapter 1 - 291
The notation we used here is based on the industry standard notation called UML, which stands for Unified Modeling Language.
Example: Account Motorcycle
Graphical Representation of an Object
<Object Name>
We use a rectangle to represent an object and place the underlined name of the object inside the rectangle.
. 4th Ed Chapter 1 - 292
Example:
SV198This is an object named SV198.
An Object with the Class Name
<Object Name> : <Class Name>This notation indicates the class which the object is an instance.
. 4th Ed Chapter 1 - 293
This tells an object SV198 is an instance of the BankAccount class.
Example:
SV198 : BankAccount
Messages and Methods• To instruct a class or an object to perform a task, we send a
message to it.
• You can send a message only to the classes and objects that understand the message you sent to them.
• A class or an object must possess a matching method to be able to handle the received messageable to handle the received message.
• A method defined for a class is called a class method, and a method defined for an object is called an instance method.
• A value we pass to an object when sending a message is called an argument of the message.
. 4th Ed Chapter 1 - 294
50
Sending a Message
Message deposit with the argument 250.00 is sent to a BankAccount object SV198.
. 4th Ed Chapter 1 - 295
deposit 250.00SV198 : BankAccount
Sending a Message and Getting an Answer
getCurrentBalance()
Ask for the current balance of this particular account.
. 4th Ed Chapter 1 - 296
current balance
SV198 : BankAccount
The current balance of SV198 is returned.
Calling a Class Method
MobileRobot
Ask for the maximum possible speed for all MobileRobot objects is returned.
. 4th Ed Chapter 1 - 297
maximum speed
MobileRobot
getMaximumSpeed()
Class and Instance Data Values
• An object is comprised of data values and methods.
• An instance data value is used to maintain information specific to individual instances. For example, each BankAccount object maintains its balance.
• A class data value is used to maintain information shared by• A class data value is used to maintain information shared by all instances or aggregate information about the instances.
• For example, minimum balance is the information shared by all Account objects, whereas the average balance of all BankAccount objects is an aggregate information.
. 4th Ed Chapter 1 - 298
Sample Instance Data Value
SV098 : BankAccount SV211 : BankAccountSV129 : BankAccount
current balance current balance current balance
908.55 1304.98 354.00
. 4th Ed Chapter 1 - 299
All three BankAccountobjects possess the same instance data value current balance.
The actual dollar amounts are, of course, different.
Sample Class Data ValueBankAccount
minimum balance
100.00
There is one copy of minimum balance for the whole class and shared by all instances.
This line is an
. 4th Ed Chapter 1 - 300
SV098 : BankAccount SV211 : BankAccountSV129 : BankAccount
current balance current balance current balance
908.55 1304.98 354.00
This line is an instance-ofrelationship.
51
Object Icon with Class Data Value
When the class icon is not shown, we include
SV129 : BankAccount
minimum balance
100.00
. 4th Ed Chapter 1 - 301
the class data value in the object icon itself.current balance
908.55
Inheritance
• Inheritance is a mechanism in OOP to design two or more entities that are different but share many common features.
– Features common to all classes are defined in the– Features common to all classes are defined in the superclass.
– The classes that inherit common features from the superclass are called subclasses.
• We also call the superclass an ancestor and the subclass a descendant.
. 4th Ed Chapter 1 - 302
A Sample Inheritance
• Here are the superclass Account and its subclasses Savings and Checking.
Account
. 4th Ed Chapter 1 - 303
Checking Savings
Inheritance Hierarchy
• An example of inheritance hierarchy among different types of students.
Student
. 4th Ed Chapter 1 - 304
Graduate Undergrad
LawMasters Doctoral Commuting Resident
Software Engineering
• Much like building a skyscraper, we need a disciplined approach in developing complex software applications.
• Software engineering is the application of a systematic and disciplined approach to the development, testing, and maintenance of a program.
• In this class, we will learn how to apply sound software engineering principles when we develop sample programs.
. 4th Ed Chapter 1 - 305
Software Life Cycle
• The sequence of stages from conception to operation of a program is called software life cycle.
• Five stages are
– Analysis
– Design
– Coding
– Testing
– Operation and Maintenance
. 4th Ed Chapter 1 - 306
52
Chapter 2
Getting Started with Java
. 4th Ed Chapter 2 - 307
Objectives
After you have read and studied this chapter, you should be able to
• Identify the basic components of Java programs
• Write simple Java programs
• Describe the difference between object declaration and creation
• Describe the process of creating and running Java programs
• Use the Date, SimpleDateFormat, String, and JOptionPane standard classes
• Develop Java programs, using the incremental development approach
. 4th Ed Chapter 2 - 308
The First Java Program
• The fundamental OOP concept illustrated by the program:
An object‐oriented program uses objects.j
• This program displays a window on the screen.
• The size of the window is set to 300 pixels wide and 200 pixels high. Its title is set to My First Java Program.
. 4th Ed Chapter 2 - 309
Program Ch2Sample1
import javax.swing.*;class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
Declare a name
Create an object
. 4th Ed Chapter 2 - 310
myWindow new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);}
}
j
Use an object
Program Diagram for Ch2Sample1
myWindow : JFrame
Ch2Sample1
setTitle("My First Java Program")
. 4th Ed Chapter 2 - 311
myWindow : JFrame
Dependency Relationship
myWindow : JFrame
Ch2Sample1
. 4th Ed Chapter 2 - 312
Instead of drawing all messages, we summarize it by showingonly the dependency relationship. The diagram shows that Ch2Sample1 "depends" on the service provided by myWindow.
53
Object Declaration
JFrame myWindow;
Object NameOne object is declared here.
Class NameThis class must be defined before this declaration can be stated.
. 4th Ed Chapter 2 - 313
MoreExamples
Account personal;Student jan, jim, jon;Vehicle car1, car2;
Object Creation
myWindow = new JFrame ( ) ;
Object NameName of the object we are creating here.
Class NameAn instance of this class is created.
ArgumentNo arguments are used here.
. 4th Ed Chapter 2 - 314
MoreExamples
myCust = new Customer( );jon = new Student("John Java");car1 = new Vehicle( );
Declaration vs. Creation
Customer myCust;
myCust = new Customer( );
Customer myCust;
myCust = new Customer( );
1
2
. 4th Ed Chapter 2 - 315
1. The identifier myCust is declared and space is allocated in memory.
2. A Customer object is created and the identifier myCust is set to refer to it.
myCust
1
: Customer2
State‐of‐Memory vs. Program
myCust
myCust : Customer
. 4th Ed Chapter 2 - 316
: Customer
State-of-MemoryNotation
Program DiagramNotation
Name vs. Objects
Customer myCust;
myCust = new Customer( );
myCust = new Customer( );
Customer myCust;
myCust = new Customer( );
myCust = new Customer( );
. 4th Ed Chapter 2 - 317
myCust
: Customer : CustomerCreated with the first new.
Created with the second new. Reference to the first Customer object is lost.
Sending a Message
myWindow . setVisible ( true ) ;
Object NameName of the object to which we are sending a message.
Method NameThe name of the message we are sending.
ArgumentThe argument we are passing with the message.
. 4th Ed Chapter 2 - 318
y ( )
MoreExamples
account.deposit( 200.0 );student.setName("john");car1.startEngine( );
54
Execution Flow
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow
State-of-Memory Diagram
: JFrame
Program Code
. 4th Ed Chapter 2 - 319
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
width
height
title
visible
200
My First Java …
300
true
The diagram shows only four of the many data members of a JFrame object.
Program Components
• A Java program is composed of
– comments,
– import statements, and
– class declarations.
. 4th Ed Chapter 2 - 320
Program Component: Comment/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java*/
import javax.swing.*;
class Ch2Sample1 {
. 4th Ed Chapter 2 - 321
public static void main(String[ ] args) {
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);}
}
Comment
Matching Comment Markers/* This is a comment on one line */
/*
Comment number 1
*/
/*
Comment number 2
*/
. 4th Ed Chapter 2 - 322
/
/*
/*
/*
This is a comment
*/
*/
Error: No matching beginning marker.
These are part of the comment.
Three Types of Comments/*
This is a comment with
three lines of
text.
*/
Multiline Comment
. 4th Ed Chapter 2 - 323
Single line Comments
// This is a comment
// This is another comment
// This is a third comment
/**
* This class provides basic clock functions. In addition
* to reading the current time and today’s date, you can
* use this class for stopwatch functions.
*/
javadoc Comments
Import Statement/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java*/
import javax.swing.*;
class Ch2Sample1 {public static void main(String[ ] args) {
Import Statement
. 4th Ed Chapter 2 - 324
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);}
}
55
Import Statement Syntax and Semantics
<package name> . <class name> ;
Class NameThe name of the class we want to import. Use asterisks to import all classes.
Package NameName of the package that contains the classes we want to use.
. 4th Ed Chapter 2 - 325
e.g. dorm . Resident;
MoreExamples
import javax.swing.JFrame;import java.util.*;import com.drcaffeine.simplegui.*;
Class Declaration/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java*/
import javax.swing.*;
class Ch2Sample1 {public static void main(String[ ] args) {
Class Declaration
. 4th Ed Chapter 2 - 326
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);}
}
Method Declaration/* Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java */
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
Method Declaration
. 4th Ed Chapter 2 - 327
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);}
}
Method Declaration Elements
public static void main( String[ ] args ){
JFrame myWindow; Method Body
Modifier Modifier Return Type Method Name Parameter
. 4th Ed Chapter 2 - 328
y
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
}
y
Template for Simple Java Programs/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample2.java*/
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[ ] args) {
Import Statements
Class Name
Comment
. 4th Ed Chapter 2 - 329
JFrame myWindow;
myWindow = new JFrame( );
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
}}
Class Name
Method Body
Why Use Standard Classes
• Don’t reinvent the wheel. When there are existing objects that satisfy our needs, use them.
• Learning how to use standard Java classes is the first step toward mastering OOP. Before we can learn how to define our own classes we need tolearn how to define our own classes, we need to learn how to use existing classes
• We will introduce four standard classes here: – JOptionPane – String– Date– SimpleDateFormat.
. 4th Ed Chapter 2 - 330
56
JOptionPane
• Using showMessageDialog of the JOptionPaneclass is a simple way to display a result of a computation to the user.
JO ti P h M Di l ( ll
. 4th Ed Chapter 2 - 331
JOptionPane.showMessageDialog(null, "I Love Java");
This dialog will appear at the center of the screen.
Displaying Multiple Lines of Text
• We can display multiple lines of text by separating lines with a new line marker \n.JOptionPane.showMessageDialog(null,
"one\ntwo\nthree");
. 4th Ed Chapter 2 - 332
String• The textual values passed to the showMessageDialog method are instances of the String class.
• A sequence of characters separated by double quotes is a String constant.double quotes is a String constant.
• There are close to 50 methods defined in the String class. We will introduce three of them here: substring, length, and indexOf.
• We will also introduce a string operation called concatenation.
. 4th Ed Chapter 2 - 333
String is an Object
1. The identifier name is
1
2
name
String name;
name = new String("Jon Java");
String name;
name = new String("Jon Java");
. 4th Ed Chapter 2 - 334
declared and space is allocated in memory.
2. A String object is created and the identifier name is set to refer to it.
name
1
2: String
Jon Java
String Indexing
. 4th Ed Chapter 2 - 335
The position, or index, of the first character is 0.
Definition: substring• Assume str is a String object and properly initialized to a string.
• str.substring( i, j ) will return a new string by extracting characters of str from position i to j‐1 where 0 i length of str, 0 j length of str and i jof str, and i j.
• If str is "programming" , then str.substring(3, 7) will create a new string whose value is "gram" because g is at position 3 and m is at position 6.
• The original string str remains unchanged.
. 4th Ed Chapter 2 - 336
57
Examples: substring
String text = "Espresso";
text.substring(6,8) "so"
. 4th Ed Chapter 2 - 337
text.substring(0,8)
text.substring(1,5)
text.substring(3,3)
text.substring(4,2)
"Espresso"
"spre"
error
""
Definition: length• Assume str is a String object and properly initialized to a string.
• str.length( ) will return the number of characters in str.
• If str is "programming" , then str.length( ) will return 11 because there are 11 characters in it.
• The original string str remains unchanged.
. 4th Ed Chapter 2 - 338
Examples: lengthString str1, str2, str3, str4;str1 = "Hello" ;str2 = "Java" ;str3 = "" ; //empty stringstr4 = " " ; //one space
. 4th Ed Chapter 2 - 339
str1.length( )
str2.length( )
str3.length( )
str4.length( )
5
4
1
0
Definition: indexOf• Assume str and substr are String objects and properly initialized.
• str.indexOf( substr ) will return the first position substr occurs in str.
• If str is "programming" and substr is "gram" , h d f( b ) llthen str.indexOf(substr ) will return 3 because the position of the first character of substr in str is 3.
• If substr does not occur in str, then –1 is returned.
• The search is case‐sensitive.
. 4th Ed Chapter 2 - 340
Examples: indexOfString str;str = "I Love Java and Java loves me.";
3 7 21
. 4th Ed Chapter 2 - 341
str.indexOf( "J" )
str2.indexOf( "love" )
str3.indexOf( "ove" )
str4.indexOf( "Me" )
7
21
-1
3
Definition: concatenation• Assume str1 and str2 are String objects and properly initialized.
• str1 + str2 will return a new string that is a concatenation of two strings.
• If str1 is "pro" and str2 is "gram" , then str1 + str2 will return "program".
• Notice that this is an operator and not a method of the String class.
• The strings str1 and str2 remains the same.
. 4th Ed Chapter 2 - 342
58
Examples: concatenation
String str1, str2;str1 = "Jon" ;str2 = "Java" ;
"J J "
. 4th Ed Chapter 2 - 343
str1 + str2
str1 + " " + str2
str2 + ", " + str1
"Are you " + str1 + "?"
"JonJava"
"Jon Java"
"Java, Jon"
"Are you Jon?"
Date• The Date class from the java.util package is used to represent a date.
• When a Date object is created, it is set to today (the current date set in the computer)
• The class has toString method that converts the ginternal format to a string.
. 4th Ed Chapter 2 - 344
Date today;today = new Date( );today.toString( );
"Fri Oct 31 10:05:18 PST 2003"
SimpleDateFormat
• The SimpleDateFormat class allows the Dateinformation to be displayed with various format.
• Table 2.1 page 68 shows the formatting options.
Date today new Date( )
. 4th Ed Chapter 2 - 345
Date today = new Date( );SimpleDateFormat sdf1, sdf2;sdf1 = new SimpleDateFormat("MM/dd/yy");sdf2 = new SimpleDateFormat("MMMM dd,yyyy");
sdf1.format(today);
sdf2.format(today);
"10/31/03"
"October 31, 2003"
JOptionPane for Input
• Using showInputDialog of the JOptionPaneclass is a simple way to input a string.
String name;name = JOptionPane.showInputDialog
. 4th Ed Chapter 2 - 346
p p g(null, "What is your name?");
This dialog will appear at the center of the screen ready to accept an input.
Chapter 3
Numerical Data
4th Ed Chapter 3 - 347
Animated Version
ObjectivesAfter you have read and studied this chapter, you should be able to
• Select proper types for numerical data.• Write arithmetic expressions in Java.• Evaluate arithmetic expressions using the precedence rules.• Describe how the memory allocation works for objects and primitive data valuesprimitive data values.
• Write mathematical expressions, using methods in the Math class.
• Use the GregorianCalendar class in manipulating date information such as year, month, and day.
• Use the DecimalFormat class to format numerical data• Convert input string values to numerical data• Perform input and output by using System.in and System.out
4th Ed Chapter 3 - 348
59
Manipulating Numbers
• In Java, to add two numbers x and y, we write
x + y
• But before the actual addition of the two b t k l t d l th inumbers takes place, we must declare their
data type. If x and y are integers, we write
int x, y;
orint x;int y;
4th Ed Chapter 3 - 349
Variables
• When the declaration is made, memory space is allocated to store the values of x and y.
• x and y are called variables. A variable has three properties:three properties:
– A memory location to store the value,
– The type of data stored in the memory location, and
– The name used to refer to the memory location.
• Sample variable declarations:
int x;int v, w, y;
4th Ed Chapter 3 - 350
Numerical Data Types
• Six numerical datatypes: byte, short, int, long, float & double.
• Sample variable declarations:int i, j, k; float numberOne, numberTwo; , ;long bigInteger;double bigNumber;
• At the time a variable is declared, it also can beinitialized. For example, we may initialize the integervariables count and height to 10 and 34 as
int count = 10, height = 34;
4th Ed Chapter 3 - 351
Data Type Precisions
The six data types differ in the precision of values they can store in memory.
4th Ed Chapter 3 - 352
h t
int
long
float
double
byte
short
Assignment Statements
• We assign a value to a variable using an assignment statements.
• The syntax is
<variable> = <expression> ;
• Examples:
sum = firstNumber + secondNumber;avg = (one + two + three) / 3.0;
4th Ed Chapter 3 - 354
60
Arithmetic Operators
• The following table summarizes the arithmetic operators available in Java.
4th Ed Chapter 3 - 355
This is an integer division where the fractional part is truncated.
Arithmetic Expression
• How does the expressionx + 3 * y
get evaluated? Answer: x is added to 3*y.
• We determine the order of evaluation byWe determine the order of evaluation by following the precedence rules.
• A higher precedence operator is evaluated before the lower one. If two operators are the same precedence, then they are evaluated left to right for most operators.
4th Ed Chapter 3 - 356
Precedence Rules
4th Ed Chapter 3 - 357
Type Casting
• If x is a float and y is an int, what will be the data type of the following expression?
x * y
The answer is float.
Th b i i ll d i d i• The above expression is called a mixed expression.
• The data types of the operands in mixed expressions are converted based on the promotion rules. The promotion rules ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest precision.
4th Ed Chapter 3 - 358
Explicit Type Casting
• Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax:following syntax:( <data type> ) <expression>
• Example (float) y / 3
(int) (x / y * 3.0)
4th Ed Chapter 3 - 359
Type case y to float and then divide it by 3.
Type cast the result of the expression x / y * 3.0 to int.
Implicit Type Casting• Consider the following expression:
double x = 3 + 5;
• The result of 3 + 5 is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type double) ( yp ) p ( yp )before being assigned to x.
• Notice that it is a promotion. Demotion is not allowed.
int x = 3.5;
4th Ed Chapter 3 - 360
A higher precision value cannot be assigned to a lower precision variable.
61
Constants• We can change the value of a variable. If we want the value to remain the same, we use a constant.
final double PI = 3 14159;final double PI = 3.14159;final int MONTH_IN_YEAR = 12;final short FARADAY_CONSTANT = 23060;
4th Ed Chapter 3 - 361
These are constants, also called named constant.
The reserved word final is used to declare constants.
These are called literal constant.
Primitive vs. Reference
• Numerical data are called primitive data types.
• Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects areto memory locations where the objects are actually stored.
4th Ed Chapter 3 - 362
Primitive Data Declaration and Assignments
A
int firstNumber, secondNumber;firstNumber = 234;secondNumber = 87;
firstNumber
A. Variables are allocated in memory.
234
4th Ed Chapter 3 - 363
Code State of Memory
int firstNumber, secondNumber;firstNumber = 234;secondNumber = 87;
int firstNumber, secondNumber;
BfirstNumber = 234;secondNumber = 87;
secondNumber
B. Values are assigned to variables.
87
Assigning Numerical Data
int number;number = 237;number = 35; number
A. The variable is allocated in
23735
4th Ed Chapter 3 - 364
Code State of Memory
is allocated in memory.
B. The value 237is assigned to number.
int number;
number = 237;
number = 35;
Aint number;
Bnumber = 237;
Cnumber = 35;
C. The value 35overwrites the
previous value 237.
Assigning Objects
Customer customer;customer = new Customer( );customer = new Customer( );
customer
A The variable is
A
B
Customer Customer
4th Ed Chapter 3 - 365
Code State of Memory
A. The variable is allocated in memory.
Customer customer;
customer = new Customer( );
customer = new Customer( );
Customer customer;B
customer = new Customer( );
C
customer = new Customer( );B. The reference to the
new object is assigned to customer.
C. The reference to another object overwrites the reference in customer.
Having Two References to a Single Object
Customer clemens, twain;clemens = new Customer( );twain = clemens;
A
B A Variables are
clemens
twain
Customer
4th Ed Chapter 3 - 366
Code State of Memory
Customer clemens, twain,
clemens = new Customer( );
twain = clemens;
Customer clemens, twain; Bclemens = new Customer( );
C
twain = clemens;
A. Variables are allocated in memory.
B. The reference to the new object is assigned to clemens.
C. The reference in clemens is assigned to customer.
62
Type Mismatch
• Suppose we want to input an age. Will this work?
int age;
4th Ed Chapter 3 - 367
age = JOptionPane.showInputDialog(null, "Enter your age");
• No. String value cannot be assigned directly to an int variable.
Type Conversion
• Wrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value.
int age;
4th Ed Chapter 3 - 368
gString inputStr;
inputStr = JOptionPane.showInputDialog(
null, "Enter your age");
age = Integer.parseInt(inputStr);
Other Conversion Methods
4th Ed Chapter 3 - 369
Sample Code Fragment
//code fragment to input radius and output//area and circumferencedouble radius, area, circumference;
String radiusStr = JOptionPane.showInputDialog(null, "Enter radius: " );
radius = Double.parseDouble(radiusStr);
4th Ed Chapter 3 - 370
p ( );
//compute area and circumferencearea = PI * radius * radius;circumference = 2.0 * PI * radius;
JOptionPane.showMessageDialog(null, "Given Radius: " + radius + "\n" + "Area: " + area + "\n" + "Circumference: " + circumference);
Overloaded Operator +
• The plus operator + can mean two different operations, depending on the context.
• <val1> + <val2> is an addition if both are numbers. If either one of them is a String, the it is a concatenation.
• Evaluation goes from left to right.g g
4th Ed Chapter 3 - 371
output = "test" + 1 + 2; output = 1 + 2 + "test";
The DecimalFormat Class
• Use a DecimalFormat object to format the numerical output.
double num = 123.45789345;
DecimalFormat df = new DecimalFormat("0.000");// h d i l l
4th Ed Chapter 3 - 372
//three decimal places
System.out.print(num);
System.out.print(df.format(num));
123.45789345
123.458
63
Standard Output
• The showMessageDialogmethod is intended for displaying short one‐line messages, not for a general‐purpose output mechanism.
• Using System.out, we can output multiple lines of text to the standard output window.
4th Ed Chapter 3 - 373
Standard Output Window
• A sample standard output window for displaying multiple lines of text.
4th Ed Chapter 3 - 374
• The exact style of standard output window depends on the Java tool you use.
The print Method
• We use the printmethod to output a value to the standard output window.
• The printmethod will continue printing from the end of the currently displayed output.
• Example• Example System.out.print( "Hello, Dr. Caffeine." );
4th Ed Chapter 3 - 375
The println Method
• We use println instead of print to skip a line.
int x = 123, y = x + x;System.out.println( "Hello, Dr. Caffeine." );System.out.print( " x = " );System.out.println( x );System.out.print( " x + x = " );
4th Ed Chapter 3 - 376
System.out.print( x + x );System.out.println( y );System.out.println( " THE END" );
Standard Input
• The technique of using System.in to input data is called standard input.
• We can only input a single byte using System.in directly.
• To input primitive data values, we use the p p ,Scanner class (from Java 5.0).
4th Ed Chapter 3 - 377
Scanner scanner = new Scanner(System.in);int num = scanner.nextInt();
Common Scanner Methods:
Method Example
nextByte( ) byte b = scanner.nextByte( );
nextDouble( ) double d = scanner.nextDouble( );
nextFloat( ) float f = scanner.nextFloat( );
nextInt( ) int i = scanner.nextInt( );
nextLong( ) long l = scanner.nextLong( );
nextShort( ) short s = scanner.nextShort( );
next() String str = scanner.next();
4th Ed Chapter 3 - 378
64
The Math class
• The Math class in the java.lang package contains class methods for commonly used mathematical functions.
double num, x, y;x = ;
4th Ed Chapter 3 - 379
x …;y = …;num = Math.sqrt(Math.max(x, y) + 12.4);
• Table 3.6 in the textbook contains a list of class methods defined in the Math class.
Some Math Class MethodsMethod Description
exp(a) Natural number e raised to the power of a.
log(a) Natural logarithm (base e) of a.
floor(a) The largest whole number less than or equal to a.
max(a b) The larger of a and b.
4th Ed Chapter 3 - 380
max(a,b)
pow(a,b) The number a raised to the power of b.
sqrt(a) The square root of a.
sin(a) The sine of a. (Note: all trigonometric functions are computed in radians)
Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math class.
Chapter 4
Defining Your Own Classes
Part 1
4th Ed Chapter 4 - 381
Animated Version
ObjectivesAfter you have read and studied this chapter, you should be able to
• Define a class with multiple methods and data members
• Differentiate the local and instance variablesDifferentiate the local and instance variables
• Define and use value‐returning methods
• Distinguish private and public methods
• Distinguish private and public data members
• Pass both primitive data and objects to a method
Why Programmer‐Defined Classes
• Using just the String, GregorianCalendar, JFrameand other standard classes will not meet all of our needs. We need to be able to define our own classes customized for our applications. pp
• Learning how to define our own classes is the first step toward mastering the skills necessary in building large programs.
• Classes we define ourselves are called programmer‐defined classes.
4th Ed Chapter 4 - 383
First Example: Using the Bicycle Classclass BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2;
String owner1, owner2;
bike1 = new Bicycle( ); //Create and assign values to bike1
bike1.setOwnerName("Adam Smith");
4th Ed Chapter 4 - 384
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.");
}
}
65
The Definition of the Bicycle Classclass Bicycle {
// Data Member private String ownerName;//Constructor: Initialzes the data memberpublic Bicycle( ) {
ownerName = "Unknown";}
4th Ed Chapter 4 - 385
//Returns the name of this bicycle's ownerpublic String getOwnerName( ) {
return ownerName;}
//Assigns the name of this bicycle's ownerpublic void setOwnerName(String name) {
ownerName = name;}
}
Multiple Instances• Once the Bicycle class is defined, we can create multiple instances.
Bicycle bike1, bike2;
bike1 bike2
: Bicycle: Bicyclebik 1 i l ( )
4th Ed Chapter 4 - 386
y
ownerName
y
ownerName
"Adam Smith" "Ben Jones"
bike1 = new Bicycle( );
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( );
bike2.setOwnerName("Ben Jones");
Sample Code
The Program Structure and Source Files
BicycleRegistration Bicycle
There are two source files
4th Ed Chapter 4 - 387
There are two source 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)
Class Diagram for Bicycle
Bicycle
Bicycle( )
4th Ed Chapter 4 - 388
Method ListingWe list the name and the data type of an argument passed to the method.setOwnerName(String)
Bicycle( )
getOwnerName( )
Template for Class Definition
class {
Import Statements
Class Comment
Class Name
4th Ed Chapter 4 - 389
}
Data Members
Methods(incl. Constructor)
Data Member Declaration
<modifiers> <data type> <name> ;
Modifiers Data Type Name
4th Ed Chapter 4 - 390
private String ownerName ;
Modifiers Data Type Name
Note: There’s only one modifier in this example.
66
Method Declaration<modifier> <return type> <method name> ( <parameters> ){
<statements>
}
Modifier Return Type Method Name Parameter
4th Ed Chapter 4 - 391
public void setOwnerName ( String name ) {
ownerName = name;
}
Statements
yp
Constructor• A constructor is a special method that is executed when a new instance of the
class is created.
public <class name> ( <parameters> ){<statements>
}
4th Ed Chapter 4 - 392
public Bicycle ( ) {
ownerName = "Unassigned";
}Statements
Modifier Class Name Parameter
Second Example: Using Bicycle and Account
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";
bike = new Bicycle( ); bike setOwnerName(myName);
4th Ed Chapter 4 - 393
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");
}}
The Account Classclass Account {
private String ownerName;
private double balance;
public Account( ) {ownerName = "Unassigned";balance = 0.0;
}
public void add(double amt) {balance = balance + amt;
}
public void setInitialBalance(double bal) {
balance = bal;}
public void setOwnerName(String name) {
ownerName = name;}
}
4th Ed Chapter 4 - 394
public void deduct(double amt) {balance = balance - amt;
}
public double getCurrentBalance( ) {return balance;
}
public String getOwnerName( ) {
return ownerName;}
Page 1 Page 2
The Program Structure for SecondMain
SecondMain
Bicycle
Account
4th Ed Chapter 4 - 395
SecondMain.java Bicycle.java
To run the program: 1. javac Bicycle.java (compile)2. javac Account.java (compile)2. javac SecondMain.java (compile)3. java SecondMain (run)
Account.java
Note: You only need to compile the class once. Recompile only when you made changes in the code.
Arguments and Parametersclass Account {
. . .
public void add(double amt) {
balance = balance + amt;}
. . .}
class Sample {
public static void main(String[] arg) {
Account myAcct = new Account();. . .
myAcct.add(400);. . .
}
. . .}
argument
parameter
• An argument is a value we pass to a method
4th Ed Chapter 4 - 396
• A parameter is a placeholder in the called method to hold the value of the passed argument.
67
Matching Arguments and Parameters
• The number or arguments and the parameters must be the same
Demo myInst = new Demo( );
int i = 5; int k = 14;
myInst.compute(i, k, 20);3 arguments
• Arguments and parameters are Passing Side
4th Ed Chapter 4 - 397
class Demo {
public void compute(int i, int j, double x) {. . .
}} 3 parameters
• The matched pair must be assignment-compatible (e.g. you cannot pass a double argument to a int parameter)
ppaired left to right
Receiving Side
Memory Allocation
• Separate memory space is allocated for the receiving method.
i 5
k 14
20
i
j
x
5
14
20.0• Values of
4th Ed Chapter 4 - 398
Passing Side Receiving Side
Values of arguments are passed into memory allocated for parameters.Literal constant
has no name
Passing Objects to a Method
• As we can pass int and double values, we can also pass an object to a method.
• When we pass an object, we are actually passing the reference (name) of an objectpassing the reference (name) of an object
– it means a duplicate of an object is NOT created in the called method
4th Ed Chapter 4 - 399
Passing a Student Object
class LibraryCard {private Student owner;bli id tO (St d t t) {
LibraryCard card2;
card2 = new LibraryCard();
card2.setOwner(student);
Passing Side
student
card2
st1
1
2
4th Ed Chapter 4 - 400
public void setOwner(Student st) {
owner = st;}
}
Receiving Side
: LibraryCard
owner
borrowCnt
0
: Student
name
"Jon Java"
"[email protected]"Argument is passed1
2
2 Value is assigned to thedata member State of Memory
Sharing an Object
• We pass the same Student object to card1 and card2
4th Ed Chapter 4 - 401
• 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
Information Hiding and Visibility Modifiers
• The modifiers public and private designate the accessibility of data members and methods.
• If a class component (data member or method) is declared private, client classes cannot access it.declared private, client classes cannot access it.
• If a class component is declared public, client classes can access it.
• Internal details of a class are declared private and hidden from the clients. This is information hiding.
4th Ed Chapter 4 - 402
68
Accessibility Example
class Service {public int memberOne;private int memberTwo;
public void doOne() {
…
…
Service obj = new Service();
obj.memberOne = 10;
4th Ed Chapter 4 - 403
}private void doTwo() {
…
}
}
obj.memberTwo = 20;
obj.doOne();
obj.doTwo();
…
Client Service
Data Members Should Be private
• Data members are the implementation details of the class, so they should be invisible to the clients. Declare them private .
• Exception: Constants can (should) be declaredException: Constants can (should) be declared public if they are meant to be used directly by the outside methods.
4th Ed Chapter 4 - 404
Guideline for Visibility Modifiers
• Guidelines in determining the visibility of data members and methods: – Declare the class and instance variables private.
– Declare the class and instance methods private if pthey are used only by the other methods in the same class.
– Declare the class constants public if you want to make their values directly readable by the client programs. If the class constants are used for internal purposes only, then declare them private.
4th Ed Chapter 4 - 405
Diagram Notation for Visibility
4th Ed Chapter 4 - 406
public – plus symbol (+)private – minus symbol (-)
Class Constants• In Chapter 3, we introduced the use of constants.
• We illustrate the use of constants in programmer‐defined service classes here.
• Remember, the use of constants– provides a meaningful description of what the valuesprovides a meaningful description of what the values stand for. number = UNDEFINED; is more meaningful than number = ‐1;
– provides easier program maintenance. We only need to change the value in the constant declaration instead of locating all occurrences of the same value in the program code
4th Ed Chapter 4 - 407
A Sample Use of Constantsclass 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 NUMBER;
4th Ed Chapter 4 - 408
number = NO_NUMBER;}
//Rolls the dicepublic void roll( ) {
number = (int) (Math.floor(Math.random() * (MAX_NUMBER - MIN_NUMBER + 1)) +
MIN_NUMBER);}
//Returns the number on this dicepublic int getNumber( ) {
return number;}
}
69
Local Variables• Local variables are declared within a method declaration and used for temporary services, such as storing intermediate computation results.
public double convert(int num) {
4th Ed Chapter 4 - 409
double result;
result = Math.sqrt(num * num);
return result; }
local variable
Local, Parameter & Data Member
• An identifier appearing inside a method can be a local variable, a parameter, or a data member.
• The rules are– If there’s a matching local variable declaration or a parameter, then the identifier refers to the local variable or the parameter.
– Otherwise, if there’s a matching data member declaration, then the identifier refers to the data member.
– Otherwise, it is an error because there’s no matching declaration.
4th Ed Chapter 4 - 410
Sample Matching
class MusicCD {
private String artist;private String title;private String id;
public MusicCD(String name1, String name2) {
String ident;
4th Ed Chapter 4 - 411
artist = name1;
title = name2;
ident = artist.substring(0,2) + "-" +
title.substring(0,9);
id = ident;}...
}
Calling Methods of the Same Class• So far, we have been calling a method of another class (object).
• It is possible to call method of a class from another method of the same class.– in this case, we simply refer to a method without dot notation
4th Ed Chapter 4 - 412
Changing Any Class to a Main Class• Any class can be set to be a main class.
• All you have to do is to include the main method.
class Bicycle {
//definition of the class as shown before
4th Ed Chapter 4 - 413
//comes here//The main method that shows a sample//use of the Bicycle classpublic static void main(String[] args) {
Bicycle myBike;myBike = new Bicycle( );myBike.setOwnerName("Jon Java");System.out.println(myBike.getOwnerName()
+ "owns a bicycle"); }
}
Chapter 5
Selection Statements
4th Ed Chapter 5 - 414
Animated Version
70
Objectives
After you have read and studied this chapter, you should be able to
• Implement a selection control using if statements
• Implement a selection control using switch statements• Implement a selection control using switch statements
• Write boolean expressions using relational and boolean expressions
• Evaluate given boolean expressions correctly
• Nest an if statement inside another if statement
• Describe how objects are compared
• Choose the appropriate selection control statement for a given task
The if Statement
int testScore;
testScore = //get test score input
if (testScore < 70)
JOptionPane.showMessageDialog(null, This statement is executed if the testScoreis less than 70.
4th Ed Chapter 5 - 416
"You did not pass" );
else
JOptionPane.showMessageDialog(null,
"You did pass" );
This statement is executed if the testScoreis 70 or higher.
Syntax for the if Statementif ( <boolean expression> )
<then block>
else
<else block>Boolean Expression
4th Ed Chapter 5 - 417
if ( testScore < 70 )
JOptionPane.showMessageDialog(null,"You did not pass" );
else
JOptionPane.showMessageDialog(null,"You did pass " );
Then Block
Else Block
Control Flow
JOptionPane.showMessageDialog
falsetestScore < 70 ?
JOptionPane.showMessageDialog
true
4th Ed Chapter 5 - 418
s o essage a og(null, "You did pass");
s o essage a og(null, "You did not pass");
Relational Operators< //less than
<= //less than or equal to
== //equal to
!= //not equal to
> //greater than
>= //greater than or equal to
4th Ed Chapter 5 - 419
testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * Math.PI * radius <= 359.99
Compound Statements• Use braces if the <then> or <else> block has multiple statements.
if (testScore < 70)
{
JOptionPane.showMessageDialog(null,"You did not pass“ );
JOptionPane.showMessageDialog(null, Then Block
4th Ed Chapter 5 - 420
JOpt o a e.s o essage a og( u ,“Try harder next time“ );
}
else
{
JOptionPane.showMessageDialog(null, “You did pass“ );
JOptionPane.showMessageDialog(null, “Keep up the good work“ );
}
Else Block
71
Style Guideif ( <boolean expression> ) {
…
}
else {
…
}
Style 1
4th Ed Chapter 5 - 421
if ( <boolean expression> )
{
…
}
else
{
…
}
Style 2
The if‐then Statementif ( <boolean expression> )
<then block>
Boolean Expression
4th Ed Chapter 5 - 422
if ( testScore >= 95 )
JOptionPane.showMessageDialog(null,"You are an honor student");
Then Block
Control Flow of if‐then
testScore >= 95?
JOptionPane.showMessageDialog (null,
true
4th Ed Chapter 5 - 423
falses o essage a og ( u ,"You are an honor student");
The Nested‐if Statement• The then and else block of an if statement can contain any valid statements, including other if statements. An if statement containing another if statement is called a nested‐if statement.
if (testScore >= 70) {
4th Ed Chapter 5 - 424
( ) {
if (studentAge < 10) {
System.out.println("You did a great job");
} else {
System.out.println("You did pass"); //test score >= 70
} //and age >= 10
} else { //test score < 70
System.out.println("You did not pass");
}
Control Flow of Nested‐if Statement
messageBox.show("You did not pass");
false inner if
false
testScore >= 70 ?
true
studentAge < 10 ?
true
4th Ed Chapter 5 - 425
messageBox.show("You did pass");
messageBox.show("You did a great job");
Writing a Proper if Controlif (num1 < 0)
if (num2 < 0)
if (num3 < 0)
negativeCount = 3;
else
negativeCount = 2;
else
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 0;
if (num1 < 0)
negativeCount++;
if (num2 < 0)
negativeCount++;
if (num3 < 0)
negativeCount++;
4th Ed Chapter 5 - 426
negativeCount = 1;
else
if (num2 < 0)
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1;
else
if (num3 < 0)
negativeCount = 1;
else
negativeCount = 0;
The statement
negativeCount++;
increments the variable by one
72
if – else if Controlif (score >= 90)
System.out.print("Your grade is A");
else if (score >= 80)
System.out.print("Your grade is B");
else if (score >= 70)
Test Score Grade90 score A
80 score 90 B
4th Ed Chapter 5 - 427
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");
80 score 90 B
70 score 80 C
60 score 70 D
score 60 F
Matching else
if (x < y)
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");
A
Are and different?A B
if (x < y) {
if (x < z) {
System.out.print("Hello");
Both and means…A B
4th Ed Chapter 5 - 428
if (x < y)
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");
B
} else {
System.out.print("Good bye");
}
}
Boolean Operators
• A boolean operator takes boolean values as its operands and returns a boolean value.
• The three boolean operators are– and: &&
||– or: ||
– not !
4th Ed Chapter 5 - 429
if (temperature >= 65 && distanceToDestination < 2) {System.out.println("Let's walk");
} else {System.out.println("Let's drive");
}
Semantics of Boolean Operators
• Boolean operators and their meanings:
P Q P && Q P || Q !P
false false false false true
false true false true true
4th Ed Chapter 5 - 430
false true false true true
true false false true false
true true true true false
De Morgan's Law
• De Morgan's Law allows us to rewrite boolean expressions in different ways
Rule 1: !(P && Q) !P || !Q
Rule 2: !(P || Q) !P && !Q
4th Ed Chapter 5 - 431
( || Q) Q
!(temp >= 65 && dist < 2)
!(temp >=65) || !(dist < 2) by Rule 1
(temp < 65 || dist >= 2)
Short‐Circuit Evaluation
• Consider the following boolean expression:
x > y || x > z
• The expression is evaluated left to right. If x > y is true, then there’s no need to evaluate x > z because the whole expression will be true whether x > z is true or notexpression will be true whether x > z is true or not.
• To stop the evaluation once the result of the whole expression is known is called short‐circuit evaluation.
• What would happen if the short‐circuit evaluation is not done for the following expression?
z == 0 || x / z > 20
4th Ed Chapter 5 - 432
73
Operator Precedence Rules
4th Ed Chapter 5 - 433
Boolean Variables
• The result of a boolean expression is either true or false. These are the two values of data type boolean.
• We can declare a variable of data type b l d i b l l iboolean and assign a boolean value to it.
4th Ed Chapter 5 - 434
boolean pass, done;pass = 70 < x;done = true;if (pass) {
…} else {
…}
Boolean Methods• A method that returns a boolean value, such as
private boolean isValid(int value) {if (value < MAX_ALLOWED)
return true;} else {
return false;
4th Ed Chapter 5 - 435
}}
Can be used as
if (isValid(30)) {…
} else {…
}
Comparing Objects
• With primitive data types, we have only one way to compare them, but with objects (reference data type), we have two ways to compare themcompare them.
1. We can test whether two variables point to the same object (use ==), or
2. We can test whether two distinct objects have the same contents.
4th Ed Chapter 5 - 436
Using == With Objects (Sample 1)
String str1 = new String("Java");String str2 = new String("Java");
if (str1 == str2) {System.out.println("They are equal");
} else {System.out.println("They are not equal");
4th Ed Chapter 5 - 437
y p ( y q )}
They are not equal Not equal because str1 and str2 point to different String objects.
Using == With Objects (Sample 2)
String str1 = new String("Java");String str2 = str1;
if (str1 == str2) {System.out.println("They are equal");
} else {System.out.println("They are not equal");
4th Ed Chapter 5 - 438
y p ( y q )}
They are equal It's equal here because str1 and str2 point to the same object.
74
Using equals with String
String str1 = new String("Java");String str2 = new String("Java");
if (str1.equals(str2)) {System.out.println("They are equal");
} else {S t t i tl ("Th t l")
4th Ed Chapter 5 - 439
System.out.println("They are not equal");}
They are equal It's equal here because str1 and str2 have the same sequence of characters.
The Semantics of ==
4th Ed Chapter 5 - 440
In Creating String Objects
4th Ed Chapter 5 - 441
The switch Statementint gradeLevel;
gradeLevel = Integer.parseInt( JOptionPane.showInputDialog("Grade (Frosh-1,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;
This statement is executed if the gradeLevelis equal to 1.
4th Ed Chapter 5 - 442
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 gradeLevelis equal to 4.
Syntax for the switch Statement
switch ( gradeLevel ) {
switch ( <arithmetic expression> ) {
<case label 1> : <case body 1>
…
<case label n> : <case body n>
}Arithmetic Expression
4th Ed Chapter 5 - 443
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;
}
Case Body
Case Label
switch With No break Statements
switch ( N ) {
case 1: x = 10;
case 2: x = 20;
x = 10;
false
trueN == 1 ?
N ==true
4th Ed Chapter 5 - 444
case 3: x = 30;
}
x = 20;
x = 30;
N 2 ?
N == 3 ?
false
falsetrue
75
switch With break Statements
switch ( N ) {
case 1: x = 10;
break;
case 2: x = 20;
x = 10;
false
trueN == 1 ?
N ==true
break;
4th Ed Chapter 5 - 445
break;
case 3: x = 30;
break;
}
x = 20;
x = 30;
N == 2 ?
N == 3 ?
false
falsetrue
break;
break;
switch With the default Blockswitch (ranking) {
case 10:
case 9:
case 8: System.out.print("Master");
break;
case 7:
6
4th Ed Chapter 5 - 446
case 6: System.out.print("Journeyman");
break;
case 5:
case 4: System.out.print("Apprentice");
break;
default: System.out.print("Input error: Invalid
Data");
break;
}
Chapter 6
Repetition Statements
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 447
Animated Version
ObjectivesAfter you have read and studied this chapter, you should be able to
– Implement repetition control in a program using while statements.– Implement repetition control in a program using do‐while
statements.– Implement a generic loop‐and‐a‐half repetition control statement– Implement repetition control in a program using for statements.– Nest a loop repetition statement inside another repetition
statement.– Choose the appropriate repetition control statement for a given
task– Prompt the user for a yes‐no reply using the showConfirmDialog
method of JOptionPane.– (Optional) Write simple recursive methods
Definition• Repetition statements control a block of
code to be executed for a fixed number of times or until a certain condition is met.
• Count‐controlled repetitions terminate the execution of the block after it is executed for a fixed number of timesfor a fixed number of times.
• Sentinel‐controlled repetitions terminate the execution of the block after one of the designated values called a sentinel is encountered.
• Repetition statements are called loop statements also.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 449
The while Statement
int sum = 0, number = 1;
while ( number <= 100 ) {
sum = sum + number; These statements are executed as long as number is less than or
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 450
number = number + 1;
}
number is less than or equal to 100.
76
Syntax for the while Statementwhile ( <boolean expression> )
<statement>Boolean Expression
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 451
while ( number <= 100 ) {
sum = sum + number;
number = number + 1;
}
Statement(loop body)
Control Flow of while
int sum = 0, number = 1
number <= true
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 452
number <= 100 ?
falsesum = sum + number;
number = number + 1;
More ExamplesKeeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000.
int sum = 0, number = 1;
while ( sum <= 1000000 ) {
sum = sum + number;
number = number + 1;
}
1
2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 453
Computes the product of the first 20 odd integers.
int product = 1, number = 1,count = 20, lastNumber;
lastNumber = 2 * count - 1;
while (number <= lastNumber) {
product = product * number;
number = number + 2;
}
2
Finding GCD
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 454
Direct Approach More Efficient Approach
Example: Testing Input DataString inputStr;int age;
inputStr = JOptionPane.showInputDialog(null,"Your Age (between 0 and 130):");
age = Integer.parseInt(inputStr);
while (age < 0 || age > 130) {
Priming Read
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 455
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); }
Useful Shorthand Operatorssum = sum + number; sum += number;is equivalent to
Operator Usage Meaning
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 456
+= a += b; a = a + b;
-= a -= b; a = a – b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
77
Watch Out for Pitfalls1. Watch out for the off‐by‐one error (OBOE).
2. Make sure the loop body contains a statement that will eventually cause the loop to terminate.
3. Make sure the loop repeats exactly the correct number of times.
4. If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 457
Loop Pitfall ‐ 1
Infinite LoopsBoth loops will not
int product = 0;
while ( product < 500000 ) {
product = product * 5;
}
1
Both loops will not terminate because the boolean expressions will never become false.int count = 1;
while ( count != 10 ) {
count = count + 2;
}
2
Overflow
• An infinite loop often results in an overflow error.
• An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can holdvalue the variable can hold.
• In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 459
Loop Pitfall ‐ 2float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.3333333f;
} //seven 3s
1
Using Real NumbersLoop 2 terminates, but Loop 1 does not because only an approximation of a real
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 460
float count = 0.0f;
while ( count != 1.0f ) {
count = count + 0.33333333f;
} //eight 3s
2
number can be stored in a computer memory.
Loop Pitfall – 2aint result = 0; double cnt = 1.0;
while (cnt <= 10.0){
cnt += 1.0;
result++;
}
System.out.println(result);
1
Using Real NumbersLoop 1 prints out 10, as 10
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 461
int result = 0; double cnt = 0.0;
while (cnt <= 1.0){
cnt += 0.1;
result++;
}
System.out.println(result);
2
expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory.
11
Loop Pitfall ‐ 3• Goal: Execute the loop body 10 times.
count = 1;while ( count < 10 ){
. . .count++;
}
1 count = 1;while (count <= 10 ){
. . .count++;
}
2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 462
count = 0;while (count <= 10 ){
. . .count++;
}
3 count = 0;while (count < 10 ){
. . .count++;
}
4
1 3and exhibit off-by-one error.
78
The do‐while Statement
int sum = 0, number = 1;
do {
sum += number;These statements are executed as long as sum
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 463
number++;
} while ( sum <= 1000000 );
gis less than or equal to 1,000,000.
Syntax for the do‐while Statement
do {
do<statement>
while (<boolean expression>);
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 464
sum += number;number++;
}while (sum<=1000000);
Statement(loop body)
Boolean Expression
Control Flow of do‐while
int sum = 0, number = 1
sum += number;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 465
number++;
sum <= 1000000 ?
true
false
Loop‐and‐a‐Half Repetition Control
• Loop‐and‐a‐half repetition control can be used to test a loop’s terminating condition in the middle of the loop body.
• It is implemented by using reserved words while, if, and break.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 466
Example: Loop‐and‐a‐Half Control
String name;
while (true){
name = JOptionPane.showInputDialog(null,"Your name");
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 467
);
if (name.length() > 0) break;
JOptionPane.showMessageDialog(null, "Invalid Entry." + "You must enter at least one character.");
}
Pitfalls for Loop‐and‐a‐Half Control
• Be aware of two concerns when using the loop‐and‐a‐half control:– The danger of an infinite loop. The boolean expression of the while
statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop it will result in aninclude an if statement to break out of the loop, it will result in an infinite loop.
– Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (breaks). It is good
practice to enforce the one‐entry one‐exit control flow.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 468
79
Confirmation Dialog
• A confirmation dialog can be used to prompt the user to determine whether to continue a repetition or not.
JOptionPane.showConfirmDialog(null,
/*prompt*/ "Play Another Game?",
/*dialog title*/ "Confirmation",
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 469
/ g / ,
/*button options*/ JOptionPane.YES_NO_OPTION);
Example: Confirmation Dialog
boolean keepPlaying = true;int selection;
while (keepPlaying){
//code to play one game comes here// . . .
l ti JO ti P h C fi Di l (
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 470
selection = JOptionPane.showConfirmDialog( null,"Play Another Game?","Confirmation",JOptionPane.YES_NO_OPTION);
keepPlaying=(selection==JOptionPane.YES_OPTION);
}
The for Statement
int i, sum = 0, number;
for (i = 0; i < 20; i++) {
number = scanner.nextInt( );
sum += number;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 471
sum += number;
}These statements are executed for 20 times( i = 0, 1, 2, … , 19).
Syntax for the for Statementfor ( <initialization>; <boolean expression>; <increment> )
<statement>
InitializationBoolean
ExpressionIncrement
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 472
for ( i = 0 ; i < 20 ; i++ ) {
number = scanner.nextInt();
sum += number;
}
Statement(loop body)
Control Flow of for
i = 0;
falsei < 20 ?
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 473
number = . . . ;sum += number;
true
i ++;
More for Loop Examplesfor (int i = 0; i < 100; i += 5)1
i = 0, 5, 10, … , 95
for (int j = 2; j < 40; j *= 2)2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 474
j = 2, 4, 8, 16, 32
for (int k = 100; k > 0; k--) )3
k = 100, 99, 98, 97, ..., 1
80
The Nested‐for Statement• Nesting a for statement inside another for statement is commonly used technique in programming.
• Let’s generate the following table using nested‐for statement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 475
Generating the Table
int price;
for (int width = 11; width <=20, width++){
for (int length = 5, length <=25, length+=5){
price = width * length * 19; //$19 per sq ftR
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 476
price = width * length * 19; //$19 per sq. ft.
System.out.print (" " + price);
}
//finished one row; move on to next row
System.out.println("");
}
INN
ER
OU
TER
Formatting Output
• We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows the field width of 6.
• From Java 5.0, we can use the Formatter class. System.out(PrintStream) also includes the format method.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 477
The Formatter Class
• We use the Formatter class to format the output.
• First we create an instance of the class
Formatter formatter = new Formatter(System.out);
• Then we call its format method
int num = 467;
formatter.format("%6d", num);
• This will output the value with the field width of 6.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 478
The format Method of Formatter• The general syntax is
format(<control string>, <expr1>, <expr2>, . . . )
Example:int num1 = 34, num2 = 9;int num3 = num1 + num2;formatter.format("%3d + %3d = %5d", num1, num2, num3);
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 479
The format Method of PrintStream
• Instead of using the Formatter class directly, we can achieve the same result by using the format method of PrintStream (System.out)
Formatter formatter = new Formatter(System.out);formatter.format("%6d", 498);
is equivalent to
System.out.format("%6d", 498);
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 480
81
Control Strings
• Integers% <field width> d
• Real Numbers% <field width> . <decimal places> f
• Strings% s
• For other data types and more formatting options, please consult the Java API for the Formatter class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 481
Estimating the Execution Time
• In many situations, we would like to know how long it took to execute a piece of code. For example,– Execution time of a loop statement that finds the greatest common divisor of two very large numbers, or
– Execution time of a loop statement to display all prime numbers between 1 and 100 million
• Execution time can be measured easily by using the Date class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 482
Using the Date Class
• Here's one way to measure the execution time
Date startTime = new Date();
//code you want to measure the execution time
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 6 - 483
Date endTime = new Date();
long elapsedTimeInMilliSec =
endTime.getTime() – startTime.getTime();
Chapter 7
Defining Your Own Classes
Part 2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 484
Animated Version
Objectives
• After you have read and studied this chapter, you should be able to – Describe how objects are returned from methods
– Describe how the reserved word this is used
– Define overloaded methods and constructors
– Define class methods and variables
– Describe how the arguments are passed to the parameters using the pass‐by‐value scheme
– Document classes with javadoc comments
– Organize classes into a package
Returning an Object from a Method
• As we can return a primitive data value from a method, we can return an object from a method also.
• We return an object from a method we are• We return an object from a method, we are actually returning a reference (or an address) of an object.
– This means we are not returning a copy of an object, but only the reference of this object
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 486
82
Sample Object‐Returning Method
• Here's a sample method that returns an object:
public Fraction simplify( ) {
F ti i
Return type indicates the class of an object we're returning from the method.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 487
Fraction simp;
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
A Sample Call to simplify
f1 = new Fraction(24, 36);
f2 = f1.simplify();
public Fraction simplify( ) {
int num = getNumerator();int denom = getDenominator();int gcd = gcd(num, denom);
Fraction simp = new Fraction(num/gcd, denom/gcd);
return simp;}
f1simp
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 488
: Fraction
numerator
denominator36
24
f2
simp
: Fraction
numerator
denominator3
2
A Sample Call to simplify (cont'd) public Fraction simplify( ) {
int num = getNumerator();int denom = getDenominator();int gcd = gcd(num, denom);
Fraction simp = newFraction(num/gcd, denom/gcd);
return simp;}
f1 = new Fraction(24, 26);
f2 = f1.simplify();
f1simp
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 489
: Fraction
numerator
denominator3
2
: Fraction
numerator
denominator36
24
f2
simp
: Fraction
numerator
denominator3
2The value of simp, which is a reference, is returned and assigned to f2.
Reserved Word this
• The reserved word this is called a self‐referencing pointerbecause it refers to an object from the object's method.
: Object
this
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 490
this
• The reserved word this can be used in three different ways. We will see all three uses in this chapter.
The Use of this in the add Method
public Fraction add(Fraction frac) {
int a, b, c, d;Fraction sum;
a = this.getNumerator(); //get the receiving
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 491
b = this.getDenominator(); //object's num and denom
c = frac.getNumerator(); //get frac's numd = 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
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 492
this is referring to f1.
83
f3 = f2.add(f1)
This time, we're calling f2's method, so the reserved word this is referring to
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 493
this is referring to f2.
Using this to Refer to Data Members
• In the previous example, we showed the use of thisto call a method of a receiving object.
• It can be used to refer to a data member as well.
class Person {
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 494
class Person {
int age;
public void setAge(int val) {this.age = val;
}. . .
}
Overloaded Methods• Methods can share the same name as long as
– they have a different number of parameters (Rule 1) or
– their parameters are of different data types when the number of parameters is the same (Rule 2)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 495
public void myMethod(int x, int y) { ... }
public void myMethod(int x) { ... } Rule 1
public void myMethod(double x) { ... }
public void myMethod(int x) { ... } Rule 2
Overloaded Constructor• The same rules apply for overloaded constructors
– this is how we can define more than one constructor to a class
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 496
public Person( ) { ... }
public Person(int age) { ... } Rule 1
public Pet(int age) { ... }
public Pet(String name) { ... } Rule 2
Constructors and this
• To call a constructor from another constructor
public Fraction( ) { //creates 0/1this(0, 1);
}
public Fraction(int number) { //creates number/1this(number, 1);
}
of the same class, we use the reserved word this.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 497
public Fraction(Fraction frac) { //copy constructorthis(frac.getNumerator(),
frac.getDenominator());}
public Fraction(int num, int denom) {setNumerator(num);setDenominator(denom);
}
Class Methods
• We use the reserved word static to define a class method.
public static int gcd(int m, int n) {
//th d i l ti th E lid l ith
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 498
//the code implementing the Euclidean algorithm}
public static Fraction min(Fraction f1, Fraction f2) {
//convert to decimals and then compare
}
84
Call‐by‐Value Parameter Passing
• When a method is called,
– the value of the argument is passed to the matching parameter, and
– separate memory space is allocated to store this value.
• This way of passing the value of arguments is called a pass‐by‐value or call‐by‐value schemevalue or call by value scheme.
• Since separate memory space is allocated for each parameter during the execution of the method,
– the parameter is local to the method, and therefore
– changes made to the parameter will not affect the value of the corresponding argument.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 499
Call‐by‐Value Exampleclass Tester {
public void myMethod(int one, double two ) {one = 25;two = 35.4;
}}
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 500
Tester tester;int x, y;tester = new Tester();x = 10;y = 20;tester.myMethod(x, y);System.out.println(x + " " + y);
produces10 20
Memory Allocation for Parameters
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 501
Memory Allocation for Parameters (cont'd)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 502
Parameter Passing: Key Points
1. Arguments are passed to a method by using the pass‐by‐ value scheme.
2. Arguments are matched to the parameters from left to right.The data type of an argument must be assignment‐compatible with the data type of the matching parameter.
3. The number of arguments in the method call must match the number f h h d d fof parameters in the method definition.
4. Parameters and arguments do not have to have the same name.
5. Local copies, which are distinct from arguments,are created even if the parameters and arguments share the same name.
6. Parameters are input to a method, and they are local to the method.Changes made to the parameters will not affect the value of corresponding arguments.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 503
Organizing Classes into a Package
• For a class A to use class B, their bytecode files must be located in the same directory.– This is not practical if we want to reuse programmer‐defined classes in many different programs
• The correct way to reuse programmer‐defined classes from many different programs is to place reusable classes in a package.
• A package is a Java class library.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 504
85
Creating a Package• The following steps illustrate the process of creating a package name myutil that includes the Fraction class.1. Include the statement
package myutil;as the first statement of the source file for the Fraction class.
2 The class declaration must include the visibility modifier public as2. The class declaration must include the visibility modifier public as
public class Fraction {...
}3. Create a folder named myutil, the same name as the package name. In Java, the
package must have a one‐to‐one correspondence with the folder.4. Place the modified Fraction class into the myutil folder and compile it.5. Modify the CLASSPATH environment variable to include the folder that contains
the myutil folder.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 505
Using Javadoc Comments
• Many of the programmer‐defined classes we design are intended to be used by other programmers. – It is, therefore, very important to provide meaningful documentation
to the client programmers so they can understand how to use our classes correctly.
• By adding javadoc comments to the classes we design, we can provide a consistent style of documenting the classes.
• Once the javadoc comments are added to a class, we can generate HTML files for documentation by using the javadoc command.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 506
javadoc for Fraction
• This is a portion of the HTML documentation for the Fraction class shown in a browser.
• This HTML file is produced by processing the javadoc comments in the source file of the Fraction class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 507
javadoc Tags
• The javadoc comments begins with /** and ends with */
• Special information such as the authors, parameters, return values, and others are p , ,indicated by the @ marker
@param
@author
@return
etc
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 508
Example: javadoc Source
. . .
/*** Returns the sum of this Fraction* and the parameter frac. The sum* returned is NOT simplified.** @ f th F ti t dd t thi this javadoc
©The McGraw-Hill Companies, Inc. Permission required for
reproduction or display.4th Ed Chapter 7 - 509
* @param frac the Fraction to add to this* Fraction** @return the sum of this and frac*/public Fraction add(Fraction frac) {
...}. . .
this javadocwill produce
Example: javadoc Output
©The McGraw-Hill Companies, Inc. Permission required for
reproduction or display.4th Ed Chapter 7 - 510
86
javadoc Resources
• General information on javadoc is located at
http://java.sun.com/j2se/javadoc
• Detailed reference on how to use javadoc on Windows is located at
http://java.sun.com/j2se/1.5/docs/tooldocs/windows/javadoc.html
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 7 - 511
Chapter 8
Exceptions and Assertions
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 512
Objectives
• After you have read and studied this chapter, you should be able to
– Improve the reliability of code by incorporating exception‐handling and assertion mechanisms.exception handling and assertion mechanisms.
– Write methods that propagate exceptions.
– Implement the try‐catch blocks for catching and handling exceptions.
– Write programmer‐defined exception classes.
– Distinguish the checked and unchecked, or runtime, exceptions.
Definition
• An exception represents an error condition that can occur during the normal course of program execution.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 514
• When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception‐handling routine is then executed; we say the thrown exception is caught.
Not Catching Exceptions
String inputStr;
int age;
inputStr = JOptionPane.showInputDialog(null, "Age:");
age = Integer.parseInt(inputStr);
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 515
java.lang.NumberFormatException: tenat java.lang.Integer.parseInt(Integer.java:405)at java.lang.Integer.parseInt(Integer.java:454)at Ch8Sample1.main(Ch8Sample1.java:20)
Error message for invalid input
Catching an Exception
inputStr = JOptionPane.showInputDialog(null, "Age:");
try {
age = Integer.parseInt(inputStr);try
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 516
} catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "’" + inputStr
+ "‘ is invalid\n"
+ "Please enter digits only");
}
catch
87
try‐catch Control Flow
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 517
Getting Information
• There are two methods we can call to get information about the thrown exception:
– getMessage
printStackTrace
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 518
– printStackTracetry {
. . .
} catch (NumberFormatException e){
System.out.println(e.getMessage());
System.out.println(e.printStackTrace());
}
Multiple catch Blocks• A single try‐catch statement can include multiple catch blocks,
one for each type of exception.
try {
. . .
age = Integer.parseInt(inputStr);
. . .
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 519
val = cal.get(id); //cal is a GregorianCalendar
. . .
} catch (NumberFormatException e){
. . .
} catch (ArrayIndexOutOfBoundsException e){
. . .
}
Multiple catch Control Flow
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 520
The finally Block
• There are situations where we need to take certain actions regardless of whether an exception is thrown or not.
• We place statements that must be executed
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 521
• We place statements that must be executed regardless of exceptions in the finally block.
try‐catch‐finally Control Flow
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 522
88
Propagating Exceptions• Instead of catching a thrown exception by using the try‐
catch statement, we can propagate the thrown exception back to the caller of our method.
• The method header includes the reserved word throws.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 523
public int getAge( ) throws NumberFormatException {
. . .
int age = Integer.parseInt(inputStr);
. . .
return age;
}
Throwing Exceptions• We can write a method that throws an exception directly,
i.e., this method is the origin of the exception.
• Use the throw reserved to create a new instance of the Exception or its subclasses.
• The method header includes the reserved word throws.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 524
public void doWork(int num) throws Exception {
. . .
if (num != val) throw new Exception("Invalid val");
. . .
}
Exception Thrower
• When a method may throw an exception, either directly or indirectly, we call the method an exception thrower.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 525
• Every exception thrower must be one of two types:– catcher.
– propagator.
Types of Exception Throwers
• An exception catcher is an exception thrower that includes a matching catch block for the thrown exception.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 526
• An exception propagator does not contain a matching catch block.
• A method may be a catcher of one exception and a propagator of another.
Sample Call Sequence
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 527
Exception Types
• All types of thrown errors are instances of the Throwable class or its subclasses.
• Serious errors are represented by instances of the Error class or its subclasses.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 528
• Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses.
89
Throwable Hierarchy
• There are over 60 classes in the hierarchy.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 529
Checked vs. Runtime
• There are two types of exceptions:– Checked.
– Unchecked.
• A checked exception is an exception that is
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 530
checked at compile time.
• All other exceptions are unchecked, or runtime, exceptions. As the name suggests, they are detected only at runtime.
Different Handling Rules
• When calling a method that can throw checked exceptions – use the try‐catch statement and place the call in the try block, or
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 531
– modify the method header to include the appropriate throws clause.
• When calling a method that can throw runtime exceptions, it is optional to use the try‐catch statement or modify the method header to include a throws clause.
Handling Checked Exceptions
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 532
Handling Runtime Exceptions
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 533
Programmer‐Defined Exceptions
• Using the standard exception classes, we can use the getMessage method to retrieve the error message.
• By defining our own exception class, we can pack more useful information
– for example we may define a OutOfStock exception class and include
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 534
for example, we may define a OutOfStock exception class and include information such as how many items to order
• AgeInputException is defined as a subclass of Exception and includes public methods to access three pieces of information it carries: lower and upper bounds of valid age input and the (invalid) value entered by the user.
90
Assertions
• The syntax for the assert statement is
assert <boolean expression>;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 535
where <boolean expression>represents the condition that must be true if the code is working correctly.
• If the expression results in false, an AssertionError (a subclass of Error) is thrown.
Sample Use #1
public double deposit(double amount) {double oldBalance = balance;balance += amount;assert balance > oldBalance;
}
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 536
public double withdraw(double amount) {double oldBalance = balance;balance -= amount;assert balance < oldBalance;
}
Second Form
• The assert statement may also take the form:
assert <boolean expression>: <expression>;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 537
where <expression> represents the value passed as an argument to the constructor of the AssertionError class. The value serves as the detailed message of a thrown exception.
Sample Use #2
public double deposit(double amount) {
double oldBalance = balance;
balance += amount;
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 538
balance + amount;
assert balance > oldBalance :"Serious Error – balance did not " +" increase after deposit";
}
Compiling Programs with Assertions
• Before Java 2 SDK 1.4, the word assert is a valid nonreserved identifier. In version 1.4 and after, the word assert is treated as a regular identifier to ensure compatibility
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 539
identifier to ensure compatibility.
• To enable the assertion mechanism, compile the source file using
javac –source 1.4 <source file>
Running Programs with Assertions
• To run the program with assertions enabled, use
java –ea <main class>
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 540
j
• If the –ea option is not provided, the program is executed without checking assertions.
91
Different Uses of Assertions
• Precondition assertions check for a condition that must be true before executing a method.
• Postcondition assertions check conditions that must be true after a method is executed
©The McGraw-Hill Companies, Inc. Permission required for reproduction or di l
4th Ed Chapter 8 - 541
must be true after a method is executed.
• A control‐flow invariant is a third type of assertion that is used to assert the control must flow to particular cases.
Chapter 9
Characters and Strings
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 542
Objectives
• After you have read and studied this chapter, you should be able to – Declare and manipulate data of the char data type.– Write string processing program using String, StringBuilder and StringBuffer objectsStringBuilder, and StringBuffer objects.
– Differentiate the three string classes and use the correct class for a given task.
– Specify regular expressions for searching a pattern in a string.
– Use the Pattern and Matcher classes.– Compare the String objects correctly.
Characters
• In Java, single characters are represented using the data type char.
• Character constants are written as symbols enclosed in single quotes.
• Characters are stored in a computer f f dmemory using some form of encoding.
• ASCII, which stands for American Standard Code for Information Interchange, is one of the document coding schemes widely used today.
• Java uses Unicode, which includes ASCII, for representing char constants.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 544
ASCII Encoding
9
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 545
For example, character 'O' is 79 (row value 70 + col value 9= 79).
O70
Unicode Encoding
• The Unicode Worldwide Character Standard(Unicode) supports the interchange, processing, and display of the written texts of diverse languages.
• Java uses the Unicode standard for representing char constants.
char ch1 = 'X';
System.out.println(ch1);System.out.println( (int) ch1);
X88
92
Character ProcessingDeclaration and initialization
char ch1, ch2 = ‘X’;
Type conversion between
System.out.print("ASCII code of character X is " + (int) 'X' );
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 547
int and char.System.out.print("Character with ASCII code 88 is " + (char)88 );
This comparison returns true because ASCII value of 'A' is 65 while that of 'c'is 99.
‘A’ < ‘c’
Strings
• A string is a sequence of characters that is treated as a single value.
• Instances of the String class are used to represent strings in Javarepresent strings in Java.
• We can access individual characters of a string by calling the charAt method of the Stringobject.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 548
Accessing Individual Elements• Individual characters in a String accessed with the charAt
method.
String name = "Sumatra";
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 549
0 1 2 3 4 5 6
S u m a t r a
nameThis variable refers to the whole string.
name.charAt( 3 )The method returns the character at position # 3.
Example: Counting Vowelschar letter;
String name = JOptionPane.showInputDialog(null,"Your name:");
int numberOfCharacters = name.length();
int vowelCount = 0;
for (int i = 0; i < numberOfCharacters; i++) {
letter = name.charAt(i);
if ( l tt ' ' || l tt 'A' ||
Here’s the code to count the number of vowels in the input string.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 550
if ( letter == 'a' || letter == 'A' ||
letter == 'e' || letter == 'E' ||
letter == 'i' || letter == 'I' ||
letter == 'o' || letter == 'O' ||
letter == 'u' || letter == 'U' ) {
vowelCount++;
}
}
System.out.print(name + ", your name has " + vowelCount + " vowels");
g
Example: Counting ‘Java’ int javaCount = 0;
boolean repeat = true;
String word;
while ( repeat ) {
word = JOptionPane.showInputDialog(null,"Next word:");
Continue reading words and count how many times the word Java occurs in the input, ignoring the case.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 551
if ( word.equals("STOP") ) {
repeat = false;
} else if ( word.equalsIgnoreCase("Java") ) {
javaCount++;
}
}
Notice how the comparison is done. We are not using the == operator.
Other Useful String OperatorsMethod Meaning
compareTo Compares the two strings.str1.compareTo( str2 )
substring Extracts the a substring from a string.str1.substring( 1, 4 )
trim Removes the leading and trailing spaces.str1 trim( )
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 552
str1.trim( )
valueOf Converts a given primitive data value to a string.String.valueOf( 123.4565 )
startsWith Returns true if a string starts with a specified prefix string.str1.startsWith( str2 )
endsWith Returns true if a string ends with a specified suffix string.str1.endsWith( str2 )
• See the String class documentation for details.
93
Pattern Example• Suppose students are assigned a three‐digit code:
– The first digit represents the major (5 indicates computer science);
– The second digit represents either in‐state (1), out‐of‐state (2), or foreign (3);
– The third digit indicates campus housing:
• On‐campus dorms are numbered 1‐7.
d l ff d b h d• Students living off‐campus are represented by the digit 8.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 553
The 3-digit pattern to represent computer science majors living on-campus is
5[123][1-7]
firstcharacter
is 5second
characteris 1, 2, or 3
thirdcharacter
is any digit between 1 and 7
Regular Expressions
• The pattern is called a regular expression.
• Rules– The brackets [ ] represent choices
– The asterisk symbol * means zero or more occurrences.
– The plus symbol + means one or more occurrences.
– The hat symbol ^ means negation.
– The hyphen – means ranges.
– The parentheses ( ) and the vertical bar | mean a range of choices for multiple characters.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 554
Regular Expression Examples
Expression Description[013] A single digit 0, 1, or 3.
[0-9][0-9] Any two-digit number from 00 to 99.
[0-9&&[^4567]] A single digit that is 0, 1, 2, 3, 8, or 9.
[a-z0-9] A single character that is either a lowercase letter or a digit.g
[a-zA-Z][a-zA-Z0-9_$]*
A valid Java identifier consisting of alphanumeric characters, underscores, and dollar signs, with the first character being an alphabet.
[wb](ad|eed) Matches wad, weed, bad, and beed.
(AZ|CA|CO)[0-9][0-9] Matches AZxx,CAxx, and COxx, where x is a single digit.
©The McGraw-Hill Companies, Inc. Permission required for
reproduction or display.4th Ed Chapter 9 - 555
The replaceAll Method• The replaceAll method replaces all occurrences of a substring that matches a given regular expression with a given replacement string.
Replace all vowels with the symbol @
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 556
String originalText, modifiedText;
originalText = ...; //assign string
modifiedText = originalText.replaceAll("[aeiou]","@");
The Pattern and Matcher Classes
• The matches and replaceAll methods of the String class are shorthand for using the Pattern and Matcher classes from the java.util.regex package.
• If str and regex are String objects, then
str.matches(regex);g
is equivalent to
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
matcher.matches();
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 557
The compile Method• The compile method of the Pattern class converts the stated regular expression to an internal format to carry out the pattern‐matching operation.
• This conversion is carried out every time the matches method of the String class is executed, so it is more efficient to use the compile method when we search for the same pattern multiple times.
• See the sample programs Ch9MatchJavaIdentifier2 and Ch9PMCountJava
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 558
94
The find Method
• The find method is another powerful method of the Matcher class.– It searches for the next sequence in a string that matches the pattern, and returns true if the pattern is foundfound.
• When a matcher finds a matching sequence of characters, we can query the location of the sequence by using the start and end methods.
• See Ch9PMCountJava2
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 559
The String Class is Immutable
• In Java a String object is immutable– This means once a String object is created, it cannot be changed, such as replacing a character with another character or removing a character
– The String methods we have used so far do not change the original string. They created a new string from the original. For example, substring creates a new string from a given string.
• The String class is defined in this manner for efficiency reason.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 560
Effect of Immutability
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 561
We can do thisbecause Stringobjects areimmutable.
The StringBuffer Class
• In many string processing applications, we would like to change the contents of a string. In other words, we want it to be mutable.
• Manipulating the content of a string such as• Manipulating the content of a string, such as replacing a character, appending a string with another string, deleting a portion of a string, and so on, may be accomplished by using the StringBuffer class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 562
StringBuffer Example
Changing a string Java to Diva
word
: StringBuffer
Java
word
: StringBuffer
Diva
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 563
StringBuffer word = new StringBuffer("Java");word.setCharAt(0, 'D');word.setCharAt(1, 'i');
Before
Diva
After
Sample ProcessingReplace all vowels in the sentence with ‘X’.
char letter;
String inSentence = JOptionPane.showInputDialog(null, "Sentence:");
StringBuffer tempStringBuffer = new StringBuffer(inSentence);
int numberOfCharacters = tempStringBuffer.length();
for (int index = 0; index < numberOfCharacters; index++) {
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 564
letter = tempStringBuffer.charAt(index);
if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' ||
letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' ||
letter == 'u' || letter == 'U' ) {
tempStringBuffer.setCharAt(index,'X');
}
}
JOptionPane.showMessageDialog(null, tempStringBuffer );
95
The append and insert Methods
• We use the append method to append a String or StringBuffer object to the end of a StringBuffer object. – The method can also take an argument of the primitive data type.
– Any primitive data type argument is converted to a string before it is appended to a StringBuffer object.
• We can insert a string at a specified position by using the insert method.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 565
The StringBuilder Class
• This class is new to Java 5.0 (SDK 1.5)
• The class is added to the newest version of Java to improve the performance of the StringBuffer class.
• StringBuffer and StringBuilder support exactly the same set of methods so they are interchangeablemethods, so they are interchangeable.
• There are advanced cases where we must use StringBuffer, but all sample applications in the book, StringBuilder can be used.
• Since the performance is not our main concern and that the StringBuffer class is usable for all versions of Java, we will use StringBuffer only in this book.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or
display.4th Ed Chapter 9 - 566
Chapter 10
Arrays
4th Ed Chapter 10 - 567
Animated Version
Objectives
• After you have read and studied this chapter, you should be able to – Manipulate a collection of data values, using an array.– Declare and use an array of primitive data types in writing a program.Declare and use an array of objects in writing a– Declare and use an array of objects in writing a program
– Define a method that accepts an array as its parameter and a method that returns an array
– Describe how a two‐dimensional array is implemented as an array of arrays
– Manipulate a collection of objects, using lists and maps
Array Basics
• An array is a collection of data values.
• If your program needs to deal with 100 i 00 bj 36 lintegers, 500 Account objects, 365 real numbers, etc., you will use an array.
• In Java, an array is an indexed collection of data values of the same type.
4th Ed Chapter 10 - 569
Arrays of Primitive Data Types
• Array Declaration<data type> [ ] <variable> //variation 1
<data type> <variable>[ ] //variation 2
• Array Creation<variable> = new <data type> [ <size> ]
• ExampleExample
4th Ed Chapter 10 - 570
double[ ] rainfall;
rainfall
= new double[12];
Variation 1
double rainfall [ ];
rainfall
= new double[12];
Variation 2
An array is like an object!
96
Accessing Individual Elements• Individual elements in an array accessed with the indexed
expression.
double[] rainfall = new double[12];
rainfall0 1 2 3 4 5 6 7 8 9 10 11
4th Ed Chapter 10 - 571
The index of the firstposition in an array is 0.
0 1 2 3 4 5 6 7 8 9 10 11
rainfall[2]This indexed expression refers to the element at position #2
Array Processing – Sample1double[] rainfall = new double[12];
double annualAverage,
sum = 0.0;
for (int i = 0; i < rainfall.length; i++) {
rainfall[i] = Double.parseDouble(
The public constant length returns the capacity of an array.
4th Ed Chapter 10 - 572
JOptionPane.showInputDialog(null,
"Rainfall for month " + (i+1) ) );
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
Array Processing – Sample 2double[] 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.
4th Ed Chapter 10 - 573
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.
Array Processing – Sample 3• Compute the average rainfall for each quarter.
//assume rainfall is declared and initialized properly
double[] quarterAverage = new double[4];
4th Ed Chapter 10 - 574
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 3; j++) { //compute the sum of
sum += rainfall[3*i + j]; //one quarter
}
quarterAverage[i] = sum / 3.0; //Quarter (i+1) average
}
Array Initialization• Like other data types, it is possible to declare and initialize an array at the same time.
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 };
4th Ed Chapter 10 - 575
String[] monthName = { "January", "February", "March","April", "May", "June", "July","August", "September", "October","November", "December" };
number.lengthsamplingData.length
monthName.length
49
12
Variable‐size Declaration• In Java, we are not limited to fixed‐size array declaration.
• The following code prompts the user for the size of an array and declares an array of designated size:i t i
4th Ed Chapter 10 - 576
int size;
int[] number;
size= Integer.parseInt(JOptionPane.showInputDialog
(null, "Size of an array:"));
number = new int[size];
97
Arrays of Objects
• In Java, in addition to arrays of primitive data types, we can declare arrays of objects
• An array of primitive data is a powerful tool, but an array of objects is even more powerful.an array of objects is even more powerful.
• The use of an array of objects allows us to model the application more cleanly and logically.
4th Ed Chapter 10 - 577
The Person Class• We will use Person objects to illustrate the use of an array of
objects.
Person latte;
latte = new Person( );The Person class supports the set methods and get methods.
4th Ed Chapter 10 - 578
latte.setName("Ms. Latte");
latte.setAge(20);
latte.setGender('F');
System.out.println( "Name: " + latte.getName() );
System.out.println( "Age : " + latte.getAge() );
System.out.println( "Sex : " + latte.getGender() );
and get methods.
Creating an Object Array ‐ 1
Code Person[ ] myPerson;
myPerson = new Person[20];
myPerson[0] = new Person( );
AOnly the name myPerson is declared, no array is allocated yet.
myPerson
4th Ed Chapter 10 - 579
State of Memory
After is executedA
Creating an Object Array ‐ 2
myPerson
Code Person[ ] myPerson;
myPerson = new Person[20];
myPerson[0] = new Person( );
BNow the array for storing 20 Person objects is created, but the Person objects themselves are not yet created.
myPerson
4th Ed Chapter 10 - 580
on
State of Memory
After is executedB
0 1 2 3 4 16 17 18 19
Creating an Object Array ‐ 3
Code Person[ ] myPerson;
myPerson = new Person[20];
myPerson[0] = new Person( );C
One Person object is created and the reference to this object is placed in position 0.
myPersonmyPerson
4th Ed Chapter 10 - 581
State of Memory
0 1 2 3 4 16 17 18 19
on
0 1 2 3 4 16 17 18 19
After is executedC
Person
Person Array Processing – Sample 1• Create Person objects and set up the myPerson array.
String name, inpStr;
int age;
char gender;
for (int i = 0; i < myPerson.length; i++) {
name = inputBox.getString("Enter name:"); //read in data values
i ( )
4th Ed Chapter 10 - 582
age = inputBox.getInteger("Enter age:");
inpStr = inputBox.getString("Enter gender:");
gender = inpStr.charAt(0);
myPerson[i] = new Person( ); //create a new Person and assign values
myPerson[i].setName ( name );
myPerson[i].setAge ( age );
myPerson[i].setGender( gender );
}
98
Person Array Processing – Sample 2• Find the youngest and oldest persons.
int minIdx = 0; //index to the youngest myPerson
int maxIdx = 0; //index to the oldest myPerson
for (int i = 1; i < myPerson.length; i++) {
if ( myPerson[i].getAge() < myPerson[minIdx].getAge() ) {
//
4th Ed Chapter 10 - 583
minIdx = i; //found a younger myPerson
} else if (myPerson[i].getAge() > myPerson[maxIdx].getAge() ) {
maxIdx = i; //found an older myPerson
}
}
//myPerson[minIdx] is the youngest and myPerson[maxIdx] is the oldest
Object Deletion – Approach 1
int delIdx = 1;
myPerson[delIdx] = null;Delete Person B by setting the reference in position 1 to null.
myPerson
A
myPerson
4th Ed Chapter 10 - 584
0 1 2 3
A B C D
0 1 2 3
A C D
Before is executedA After is executedA
Object Deletion – Approach 2
int delIdx = 1, last = 3;
myPerson[delIdx] = myPerson[last];
myPerson[last] = null;
Delete Person B by setting the reference in position 1 to the last person.
myPerson
A
myPerson
4th Ed Chapter 10 - 585
0 1 2 3
A B C D
0 1 2 3
A CD
Before is executedA After is executedA
Person Array Processing – Sample 3• Searching for a particular person. Approach 2 Deletion is used.
int i = 0;
while ( myPerson[i] != null && !myPerson[i].getName().equals("Latte") ) {
i++;
}
4th Ed Chapter 10 - 586
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);
}
Passing Arrays to Methods ‐ 1CodeminOne = searchMinimum(arrayOne);
public int searchMinimum(float[] number)){
…
}
A
4th Ed Chapter 10 - 587
State of Memory
At before searchMinimumA
arrayOneA. Local variable number does not exist before the method execution
Passing Arrays to Methods ‐ 2CodeminOne = searchMinimum(arrayOne);
public int searchMinimum(float[] number)){
…
}
B
4th Ed Chapter 10 - 588
State of Memory
arrayOnearrayOne
The address is copied at B
numberB. The value of the argument, which is an address, is copied to the parameter.
99
Passing Arrays to Methods ‐ 3
Whil t i id th th dC
CodeminOne = searchMinimum(arrayOne);
public int searchMinimum(float[] number)){
…
}
C
4th Ed Chapter 10 - 589
arrayOne number
While at inside the methodC
State of Memory
C. The array is accessed via number inside the method.
Passing Arrays to Methods ‐ 4CodeminOne = searchMinimum(arrayOne);
public int searchMinimum(float[] number)){
…
}
D
hMi iD
4th Ed Chapter 10 - 590
arrayOne
At after searchMinimumD
number
State of Memory
D. The parameter is erased. The argument still points to the same object.
arrayOne
At after searchMinimumD
Two‐Dimensional Arrays• Two‐dimensional arrays are useful in representing tabular information.
4th Ed Chapter 10 - 591
Declaring and Creating a 2‐D Array
Declaration
<data type> [][] <variable> //variation 1<data type> <variable>[][] //variation 2
Creation
<variable> = new <data type> [ <size1> ][ <size2> ]
4th Ed Chapter 10 - 592
Example
double[][] payScaleTable;
payScaleTable
= new double[4][5];
3
2
1
0
43210payScaleTable
Accessing an Element• An element in a two‐dimensional array is accessed by its row and column index.
4th Ed Chapter 10 - 593
Sample 2‐D Array Processing• Find the average of each row.
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++) {
4th Ed Chapter 10 - 594
average[i] += payScaleTable[i][j];
}
average[i] = average[i] / payScaleTable[i].length;
}
100
Java Implementation of 2‐D Arrays
• The sample array creation
payScaleTable = new double[4][5];
is really a shorthand foris really a shorthand for
payScaleTable = new double [4][ ];
payScaleTable[0] = new double [5];payScaleTable[1] = new double [5];payScaleTable[2] = new double [5];payScaleTable[3] = new double [5];
Two‐Dimensional Arrays
• Subarrays may be different lengths. • Executing
triangularArray = new double[4][ ];for (int i = 0; i < 4; i++)triangularArray[i] = new double [i + 1];
results in an array that looks like:
4th Ed Chapter 10 - 596
y
Lists and Maps
• The java.util standard package contains different types of classes for maintaining a collection of objects.
• These classes are collectively referred to as• These classes are collectively referred to as the Java Collection Framework (JCF).
• JCF includes classes that maintain collections of objects as sets, lists, or maps.
4th Ed Chapter 10 - 597
Java Interface
• A Java interface defines only the behavior of objects
– It includes only public methods with no method bodies.
– It does not include any data members except public constants
– No instances of a Java interface can be created
4th Ed Chapter 10 - 598
JCF Lists
• JCF includes the List interface that supports methods to maintain a collection of objects as a linear list
L = (l0, l1, l2, . . . , lN)
• We can add to, remove from, and retrieve objects in a given list.
• A list does not have a set limit to the number of objects we can add to it.
4th Ed Chapter 10 - 599
List Methods
• Here are five of the 25 list methods:
boolean add ( Object o )
Adds an object o to the list
void clear ( )
Clears this list i e make the list empty
4th Ed Chapter 10 - 600
Clears this list, i.e., make the list empty
Object get ( int idx )
Returns the element at position idx
boolean remove ( int idx )
Removes the element at position idx
int size ( )
Returns the number of elements in the list
101
Using Lists
• To use a list in a program, we must create an instance of a class that implements the List interface.
• Two classes that implement the List interface:– ArrayList
Li k dLi– LinkedList
• The ArrayList class uses an array to manage data.
• The LinkedList class uses a technique called linked‐node representation.
4th Ed Chapter 10 - 601
Sample List Usage• Here's an example of manipulating a list:
import java.util.*;
List friends;
Person myPerson;
4th Ed Chapter 10 - 602
friends = new ArrayList( );
myPerson = new Person("jane", 10, 'F');
friends.add( myPerson );
myPerson = new Person("jack", 6, 'M');
friends.add( myPerson );
Person p = (Person) friends.get( 1 );
JCF Maps
• JCF includes the Map interface that supports methods to maintain a collection of objects (key, value) pairs called map entries.
key value
k v one entry
4th Ed Chapter 10 - 603
k0
k1
kn
v0
v1
vn
.
.
.
.
.
.
one entry
Map Methods
• Here are five of the 14 list methods:
void clear ( )
Clears this list, i.e., make the map empty
boolean containsKey ( Object key )
Returns true if the map contains an entry with a given
4th Ed Chapter 10 - 604
Returns true if the map contains an entry with a given key
Object put (Object key, Object value)
Adds the given (key, value) entry to the map
boolean remove ( Object key )
Removes the entry with the given key from the map
int size ( )
Returns the number of elements in the map
Using Maps
• To use a map in a program, we must create an instance of a class that implements the Map interface.
• Two classes that implement the Mapfinterface:
– HashMap
– TreeMap
4th Ed Chapter 10 - 605
Sample Map Usage• Here's an example of manipulating a map:
import java.util.*;
Map catalog;
catalog = new TreeMap( );
catalog.put("CS101", "Intro Java Programming");catalog.put( CS101 , Intro Java 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");
}
102
Database ProgrammingWith Java
Dr Stuart Kerrigan
In this lecture you will learn
• The components of the JDBC interface to DBMSs
• How to connect to a database from Java
• How to send SQL statements from Java to a DBMS
• The concepts of ResultSet object and a Cursor• The concepts of ResultSet object and a Cursor
• How to navigate and update a ResultSet from Java
608
JDBC
• JDBC is the Java Database Connectivity API– Allows Java program to access data stored in tabular format, such as in RDBMS and spreadsheets.
– DB driver written by the DB vendor and implemented as a class which is loaded prior to using the JDBCas a class which is loaded prior to using the JDBC methods it provides.
– Driver and supporting classes and information typically packaged in jar file.
– MySQL Connector/J
• JDBC is the driver for MySQL
609
The JDBC Programming Model
• The JDBC uses a client‐server programming model:– Client makes a connection to the
DB (the server)– Client sends SQL statement(s) to
the DBManipulate database metadata– Manipulate database metadata
– DB sends back a Result Set– Client processes Result Set– Client disconnects from the DB
• Points to note:– Result Set includes query results
and metadata– JDBC throws an exception
whenever there's an error
610
Using JDBC
• Import JDBC library– import java.sql.*;
• DriverManager provides DB interface methods• Most Java programs use import to load a class• With JDBC, usually load driver class at runtime:
import java.lang.*;p j gimport java.sql.*;public static void main (String args[]) {try { // this loads & initialises the driverClass.forName("com.mysql.jdbc.Driver");// now connect to DB ...} catch (ClassNotFoundException e) {
System.err.println(e.getMessage());e.printStackTrace();System.exit(1);
} }
611
What Does Try Mean?
• Errors always occur in software programs.
• Database programs may be critical applications.
• Errors should be caught and handled gracefully.
P h ld d l h d b• Programs should recover and leave the database in a consistent state.
• Use Java exception handlers to detect errors.
• Read Wu Chapter 8
612
103
Making a JDBC‐ODBCDatabase Connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","yourusername", "yourpassword");// make more calls to JDBC methods here...con.close();
• Need to put your own username (typically root) and password (your MySQL password) into the getConnection method
613
Statement and ResultSet Objects
Statement stmt = con.createStatement();String sql = "SELECT * FROM Staff;";ResultSet rs = stmt.executeQuery(sql);print_rs(rs); // shown laterrs.close(); // free memorystmt close();stmt.close();
• Can pass any legal SQL query to executeQuery()
• Here, rs holds the entire results table (Staff)...
614
ResultSets and Cursors
• Each ResultSet contains:
– Numbered Fields (columns)
– Field names & types (metadata)
The ResultSet object is a ‘container’ for the results of a query (table):
– A Cursor (current row)
615
•First cursor position is BEFORE FIRST ROW• Rows and columns COUNT FROM ONE
ResultSet Metadata
• We can find the number of columns, the column names and data types (REAL, CHAR, etc.) from the ResultSet metadata:
ResultSetMetaData md = rs.getMetaData();int num columns = md.getColumnCount();int num_columns md.getColumnCount();for (int i=1; i<=num_columns; i++) {
System.out.println("Column Number = " + i);System.out.println("Column Name = " + md.getColumnLabel(i));System.out.println("Column Type = " + md.getColumnTypeName(i));
}
616
Example: Printing a ResultSet
• We can move through the rows using the next() method:private void print_rs(ResultSet rs) throwsSQLException {
ResultSetMetaData md = rs.getMetaData();int num_columns = md.getColumnCount();while (rs.next()) {
ffString row_buffer = "";for (int i=1; i<=num_columns; i++) {
row_buffer += row_buffer + " " + rs.getString(i);
}System.out.println(row_buffer);
} }
• Note use of metadata and getString() method
617
Handling ResultSet Field Types
• There is a ‘get’ function for each of the main SQL data types (each needs a column no. or a column name):– getString()
– getInt()
– getDouble()
D ()– getDate()
– in general getxxxx()
• To do arithmetic on field values, need to extract into appropriate type:– double ave = rs.getDouble("Rent") /rs.getInt("Rooms");
618
104
Updatable & Scrollable Cursors
• There are several types of ‘cursor’. The type we get is controlled by the call to createStatement():stmt = con.createStatement(int scrolling, int concurrency);
• scrolling:– ResultSet.TYPE_FORWARD_ONLY ‐ the default!
– ResultSet.TYPE_SCROLL_INSENSITIVE ‐ use this
– ResultSet.TYPE_SCROLL_SENSITIVE ‐ advanced
• concurrency:– ResultSet.CONCUR_READ_ONLY ‐ the default!
– ResultSet.CONCUR_UPDATABLE
619
Scrollable Cursor Method Functions
• Scrollable cursors have a rich set of method functions:– Boolean next(), previous()– void absolute(int row_num), – void relative(int row_increment),– Boolean first(), last()– void beforeFirst(), afterLast()
• You can also ask where the cursor is currently positioned:– Boolean isFirst(), isLast()– Boolean isBeforeFirst(), isAfterLast()
620
Inserting or Deleting Rows
• For queries that do not return a ResultSet, use the executeUpdate() method:Statement stmt = con.createStatement();String sql = "DELETE FROM Client " +"WHERE ClientNo = " +"'CR56' ""'CR56';";int num_rows = stmt.executeUpdate(sql);
• If successful, get num_rows = 1 (no. rows changed)
• Could use "INSERT INTO Client..." in the same way...
• Health warning:– TAKE SPECIAL CARE WITH SPACES AND QUOTES
621
Updating an Existing Row
• To update a row, first get it into the ResultSet:Statement stmt = con.createStatement();String code = "CR56";String sql = "SELECT * FROM Client" +" WHERE ClientNo ="+
" '" + code + "'" + ";";" '" + code + "'" + ";";ResultSet rs = stmt.executeQuery(sql);rs.absolute(1); // move to first \& only rowrs.updateDouble("MaxRent", 500.0);rs.updateString("PrefType", "House");rs.updateRow();rs.close();
• Here, ResultSet must contain the primary key ‐ why?
622
Handling NULLs
• The JDBC API handles NULLs using a special method function: wasNull()– Have to "get" a field value, and then test for NULL ...String x = rs getString("City");String x = rs.getString( City );if (rs.wasNull()) x = "NULL";int i = rs.getInt("Rooms");if (rs.wasNull()) i = -1; // or whatever
• Your code can then test for special value later...
623
Summary
• Programming model:
• Client (Java) sends SQL strings to server (DBMS)
• Server (DBMS) sends a ResultSet back to client...
• Programming features:
• JDBC is strongly typed: getString() getInt()• JDBC is strongly typed: getString(), getInt()...
• JDBC throws exceptions whenever there's a error
• Consider type of cursor: scrollable/updateable?
• ResultSet rows & columns count from ONE
• ResultSet cursor starts BEFORE the first row
624