CIS 068 – Section 1

Download Report

Transcript CIS 068 – Section 1

CIS 068 – Section 1 + 2
Review of Java
Copyright © 2003 Pearson Education, Inc.
Slide 1
Topics to be Covered
• Using Primitive Data Types and Using
Classes
• Object-Oriented Design and Writing Worker
Classes
• Control Structures: Decisions and Loops
• Arrays
Copyright © 2003 Pearson Education, Inc.
Slide 2
Using Primitive Data Types and Using Classes
•
•
•
•
•
Primitive Data Types
Processing Numeric Data
Introduction to Methods
The String Class
Anatomy of a Java Program
Copyright © 2003 Pearson Education, Inc.
Slide 3
Data Types
• A data type represents a particular kind of
information and the operations that can be
performed. Formally:
– A set of elements (objects)
– The operations (methods)
• Two kinds
– Primitive: build into the run-time environment (also
known as the Java Virtual Machine)
– Classes: user defined build from other data types
Copyright © 2003 Pearson Education, Inc.
Slide 4
Primitive Data Types
Type
Integer types
byte
short
int
long
Floating types
float
double
Description
Range of Values
8-bit integer
16-bit integer
32-bit integer
64-bit integer
-128
-32768
-2147483648
-263
Single precision (32bit) floating point
Double precision (64bit) floating point
2-126 (10-38) … 2127 (1038) 24-bits (6
digits) of precision
2-1022 (10-308) … 21023(10308) 53-bits
(15 digits) of precision
Logical type
boolean Truth value
Character type
char
Text characters
encoded using the
UCF-16 format.
Copyright © 2003 Pearson Education, Inc.
…
+127
…
+32767
… +2147483647
…
+263-1
true false
0 … 65535
Slide 5
Integer types
long
63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
int
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
short
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
byte
7 6 5 4 3 2 1 0
Copyright © 2003 Pearson Education, Inc.
Slide 6
Float (real) types
double
s
exp
mantissa
63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
value = -1s  2(exp-1023)  (1 + mantissa/253)
float
s
exp
mantissa
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
value = -1s  2(exp-127)  (1 + mantissa/223)
Copyright © 2003 Pearson Education, Inc.
Slide 7
Variables
• Variable: a kind of data whose content can change during
program execution. The type of a variable can be a
primitive type or a class.
• Data declarations can be used to declare variables.
• Examples of variable declarations:
int kids = 2;
double bankBalance = 500.45;
char firstLetter = 'a';
boolean married = true;
Copyright © 2003 Pearson Education, Inc.
Slide 8
Variable Declaration
• Form: typeName variableName [= value];
• Example: int pennies;
int kids = 3;
• Interpretation: The data type of variableName is specified as
typeName where typeName is either predefined in Java or is the
name of a class that has been defined by Java programmers. If
typeName is a primitive type and value is specified, it must be a
literal (constant) of data type typeName. If typeName is a class
type and value is specified, it must be a object of data type
typeName
Copyright © 2003 Pearson Education, Inc.
Slide 9
Integer Literals
• An Integer Literal is one of the following:
– A Decimal Integer Literal
– A Hex Integer Literal
– An Octal Integer Literal
• All three of these may optionally end with
an Integer Type Suffix.
Copyright © 2003 Pearson Education, Inc.
Slide 10
Integer Type Suffix
• An Integer Type Suffix is
L
– or
l
• If the Integer Type Suffix is present, then the
Integer Literal represents a long value, otherwise it
represents an int value.
• Note since l looks a lot like 1, the use of L is
encouraged.
Copyright © 2003 Pearson Education, Inc.
Slide 11
Decimal Literal
• A Decimal Literal is one of the following:
– The single digit 0
– A digit in the range 1 … 9 optionally followed
by one or more digits in the range 0 … 9.
Copyright © 2003 Pearson Education, Inc.
Slide 12
Hex Literal
• A Hex Literal begins with
0x
– or
0X
• Followed by one or more hex digits.
• The hex digits are
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
Copyright © 2003 Pearson Education, Inc.
Slide 13
Octal Literal
• An Octal literal begins with the digit 0
• Followed by one or more octal digits.
• The octal digits are:
0 1 2 3 4 5 6 7
Copyright © 2003 Pearson Education, Inc.
Slide 14
Min and Max int values
Min
Max
Decimal
-2147483648
2147483647
Hex
0x80000000
0x7fffffff
Octal
020000000000 017777777777
Note: 2147483648 may only appear as the operand of the unary – operator.
Copyright © 2003 Pearson Education, Inc.
Slide 15
Floating Point Literals
• A FloatingPointLiteral is one of the
following:
–
–
–
–
Digits . Digitsopt ExponentPartopt FloatTypeSuffixopt
. Digits ExponentPartopt FloatTypeSuffixopt
Digits ExponentPart FloatTypeSuffixopt
Digits ExponentPartopt FloatTypeSuffix
• The opt indicates that the item is optional
Copyright © 2003 Pearson Education, Inc.
Slide 16
Floating Point Literals (2)
• Exponent part is
– Exponent Indicator followed by a Signed Integer
• An Exponent Indicator is e or E
• A Signed Integer is a sequence of digits optionally
preceded by + or –
• A Float Type Suffix is f F d or D.
– If no Float Type Suffix is specified, the literal is considered to by
of type double.
– Otherwise f or F indicates float and d or D indicates double.
Copyright © 2003 Pearson Education, Inc.
Slide 17
Valid and invalid double values
Valid
Invalid
3.14159
0.005
.12345
12345.0
16.
15.0e-04
2.345e2
1.15e-3
12e+5
-15e-0.3 (0.3 invalid exponent)
12.5e.3 (.3 invalid exponent)
e32 (doesn’t start with a digit)
a34e03 (doesn’t start with a digit)
(value is 0.0015)
(value is 234.5)
(value is 0.00115)
(value is 1200000.0)
3E3
(value is 3000.0)
Copyright © 2003 Pearson Education, Inc.
Slide 18
Character Literals
• A character literal is
' any single character except ' or \ '
or
' an escape sequence.'
Copyright © 2003 Pearson Education, Inc.
Slide 19
Escape Sequences
• A escape sequence is one of the following:
\b
\t
\n
\f
\r
\"
\'
\\
Octal escape
\u0008 backspace BS
\u0009 horizontal tab HT
\u000a line feed LF
\u000c form feed FF
\u000d carriage return CR
\u0022 double quote
\u0027 single quote
\u005c backslash
\u0000 to \u00ff
• An Octal escape is a sequence of up to 3 octal digits. If
three digits are present, the first digit must be a 0, 1, or 2.
Copyright © 2003 Pearson Education, Inc.
Slide 20
Unicode Characters
• The sequence \uxxxx where xxxx is four hex
digits is internally converted to the equivalent
Unicode character as part of the input process.
• Thus Unicode characters can appear in variable
names.
• Also the sequence '\u000a' is not a valid
character literal since the \u000a will be
converted to a line-feed character before
considering the enclosing '.
Copyright © 2003 Pearson Education, Inc.
Slide 21
Processing Numeric Data
• One of the common applications of
computers is to do arithmetic.
Operator
Meaning
+
*
5 + 2
Addition
5.0 – 2.0
Subtraction
Multiplication 5 * 2
/
Division
5/2
5.0 / 2.0
%
Remainder
5 % 2
Copyright © 2003 Pearson Education, Inc.
Example
Slide 22
Division and Remainder
• Integer division
– If both operands are integers, the result is the integer part of the
quotient.
– The result is truncated toward zero.
• Floating division
– If both operands are floating point values, the result is a floating
point value.
• Remainder
– The following identity holds:
a%b == (a/b)*b
– The remainder operator applies to floating point values.
• The results of the division are truncated to an integer and then the
above formula is applied.
Copyright © 2003 Pearson Education, Inc.
Slide 23
Statements and Expressions
• Statement: an instruction that performs an
operation. There are two kinds of statements:
– data declarations - tell the Java compiler what kind of
storage locations to allocate
– executable statements - instruct the computer how to
process the information in storage
• Expression: Java code that produces a result.
Expressions are used mostly as parts of
statements.
Copyright © 2003 Pearson Education, Inc.
Slide 24
Assignment Statement
• Form: variable = expression;
• Example: x = y + z;
• Interpretation: If variable is declared as a primitive type, the
value of the expression is stored in variable. If variable is a
declared as a class type, a reference to the object formed by
expression is stored in variable.
• The previous value of variable is lost.
• The expression can be a variable, a constant, a literal,
a method call returning a value, or a combination of
the above connected by appropriate operators (such as
+, -, * and / ).
Copyright © 2003 Pearson Education, Inc.
Slide 25
Assignment Compatability
• In an assignment statement, the value of the
expression must be assignment compatible with the
variable, meaning that:
• Either the data types of the expression and variable are
the same, or
• The expression’s type can be converted to the variable’s
type. If this condition is met, the conversion (which is
named assignment conversion) is performed
automatically.
Copyright © 2003 Pearson Education, Inc.
Slide 26
Effect of assignment statements
sum = sum + item;
before assignment: sum = 25.0; item = 5.0
after assignment: sum = 30.0; item = 5.0
newx = -x;
before assignment: newx = 0.0; x = -5.123;
after assignment: newx = 5.123; x = -5.123;
Copyright © 2003 Pearson Education, Inc.
Slide 27
Data Type of Arithmetic Operation
• The type of the result of an arithmetic
operation is double if an operand is type
double. e.g., 1+ 2.0 is 3.0
• If both operands are type int, then the
result is type int. e.g., 1 / 2 is 0.
Copyright © 2003 Pearson Education, Inc.
Slide 28
Mixed-type assignments
• Mixed-type assignment statement: the assignment of an expression of one
type to a variable of another type.
• Assignment conversion: automatic conversion of the expression value
(after the expression was completely evaluated) to the variable type. Such a
conversion must be a widening one (e.g., from int to double).
int m = 3;
int n = 2;
double x, y;
y = m + n;
assignment conversion: y becomes 5.0 (not 5)
x = y + m / n; m / n is 1 (not 1.5), 5.0 + 1 is 6.0, assign 6.0 to x
• Example of invalid assignments due to possible loss of the fractional part
(narrowing conversion is not allowed)
•
int count;
count = 3.6;
invalid: can’t assign double to int
count = count + 1.0; invalid: expr. result is double
Error: Incompatible type for =. Explicit cast needed to convert double to int.
Copyright © 2003 Pearson Education, Inc.
Slide 29
Type casting
• Casting: the most general form of conversion in Java. A cast is a Java operator
specified by a type in parentheses, that is applied to the value of an expression.
Form: (type) value
Example: double cost; int dollars;
dollars = (int) cost;
Interpretation: The cast in the example creates an int value by converting cost
to an integer (which truncates any fractional part). The content of cost remains
unchanged.
• More type casting examples:
int count;
count = (int) 3.6;
int m = 7; int n = 2;
double x;
x = (double) m / n;
int m = 7; int n = 2;
double x;
x = (double) (m /n);
Copyright © 2003 Pearson Education, Inc.
the cast operator creates an int value (i.e. 3),
which is assigned to count
• the cast operator creates a double value (i.e., 7.0)
• n is converted to a double by arithmetic promotion
• division produces the result 3.5, which is assigned to x
• the integer division 7 / 2 gives the result 3
• the cast operator creates a double value (i.e., 3.0),
which is assigned to x
Slide 30
Rules for Evaluating Expressions
• Parentheses rule: Evaluate expressions in
parentheses separately. Evaluate nested parens from
the inside out.
• Operator precedence rule: Operators in the same
expression are evaluated in the order determined by
their precedence (from the highest to the lowest).
method
call
Operator
- (unary)
new, type cast
*, /, %
+, - (binary)
=
highest
precedence
Precedence
lowest precedence
• Left associative rule: Operators in the same
expression and at the same precedence level are
Copyright © 2003 Pearson Education, Inc.
Slide 31
2.3 Methods
• Change the state of an object; i.e., change the information
stored in an object
 Calculate a result (returns a result)
 Retrieve a particular data item that is stored in an object
(returns a result)
 Get data from the user
• Display the result of an operation
Copyright © 2003 Pearson Education, Inc.
Slide 32
Dot notation
• A call to an object's method has the form:
objectName.methodName()
• This form is called dot notation and it tells
the Java compiler to call method
methodName() of object objectName.
i.e., method methodName() is applied to
object objectName.
Copyright © 2003 Pearson Education, Inc.
Slide 33
Method call with Argument list
objectName.methodName(argumentList)
• Evaluate the argumentList of methodName() and pass this
information to the method. An argumentList can contain a single
argument or multiple arguments separated by commas.
• Example:
System.out.println("First number is " + num1);
• Effect: Java calls method println() of object
System.out (the console window) using the argument shown
in parentheses. The argument is evaluated and the result is
appended as a new line to object System.out .
• If a method has no arguments, its name is followed by empty
parentheses ().
Copyright © 2003 Pearson Education, Inc.
Slide 34
Instance methods and class methods
• Method println() is an instance method because it belongs
to an object instance and is applied to an object
(System.out).
• Class methods belong to the class rather than to individual class
instances (objects).
• Class methods are not applied to an object. We prefix the
method name with the class name instead of an object name:
ClassName.methodName(argumentList)
Copyright © 2003 Pearson Education, Inc.
Slide 35
Syntax display for method call
• Form: objectName.methodName(argumentList)
ClassName.methodName(argumentList)
• Example:
System.out.println(
"I like studying Java");
Math.sqrt(15.0)
• Interpretation: For instance method, apply method methodName
of object objectName, passing in the value of each argument in
argumentList .
• Interpretation: For class method, apply method methodName of
class ClassName, passing in the value of each argument in
argumentList .
Copyright © 2003 Pearson Education, Inc.
Slide 36
2.4 String class
• A class (data type) that can be used to store and manipulate
sequences of characters.
• Use the String class to process text data instead of the more
limited char data type which stores only single characters.
• String variables reference objects that contain sequences of
characters.
Copyright © 2003 Pearson Education, Inc.
Slide 37
Declaring String Variables
• The declaration statements
String name;
String flower;
declare two variables, name and flower, that can reference
String objects.
• Currently, no String objects exist. The values of name and
flower are both null, which means they do not reference an
object.
Copyright © 2003 Pearson Education, Inc.
Slide 38
new operator creates objects
• The statements
name = new String("Dustin");
flower = new String("Rose");
create two String objects using the new operator. The first
String object contains the letters Dustin, and it is referenced
by variable name; the second String object contains the letters
Rose, and it is referenced by variable flower.
• The process of creating an object using the new operator is
called instantiation.
• An object is an instance of a class or a class instance.
Copyright © 2003 Pearson Education, Inc.
Slide 39
constructor
• The statement
name = new String("Dustin");
calls a constructor which is a special method that has the same
name as the class.
• The constructor method stores the initial data in the object. The
constructor argument provides information that the
constructor needs to set up the object.
• The argument is the string literal "Dustin" and it specifies
the sequence of characters to be stored in the new object.
Copyright © 2003 Pearson Education, Inc.
Slide 40
Syntax for Class Instantiation
• Form: variableName = new className(arguments);
• Example:
flower = new String("rose");
• Interpretation: An object of class className, is created which
will be referenced by variableName. The data type of
variableName must be type className. The constructor
className stores the data specified by the arguments in the
new object.
Copyright © 2003 Pearson Education, Inc.
Slide 41
Combining Variable Declaration and Object Creation
• The statements
String name = new String("Dustin");
String flower = new String("Rose");
create two string objects referenced by name and flower.
•
The data in quotes is stored in these objects
Copyright © 2003 Pearson Education, Inc.
Slide 42
Special Properties of Strings
• The characters stored in a String object cannot be changed. For
most classes, you can change the data stored in an object.
• You can create a new String object just by writing the sequence
of characters it contains as a literal (value).
String name = "Robin";
String flower = "Rose";
• We will use String literals to designate new String objects rather
than explicitly calling the String constructor. However, you must
use constructors to create objects of other class types.
Copyright © 2003 Pearson Education, Inc.
Slide 43
2.7 Anatomy of a Program
• Multi-line comments
/*
* PigLatinApp.java Authors: Koffman & Wolz
* Generates the pig Latin form of a word
*/
• Single line Comment
// Get a word to translate to pig Latin
• Comment at the end of a Line
String word; // word being translated
Copyright © 2003 Pearson Education, Inc.
Slide 44
Parts of a Class definition
1. A header declaration
2. The class body in braces
2.1 The data field declarations of the class
2.2 The method definitions of the class
• Form:
[visibility] class ClassName {classBody}
• Example:
public class PigLatinApp{classBody}
• Interpretation: The word public specifies that class
ClassName has public visibility. The square brackets indicate
that the visibility may be omitted. If so, the class can be
referenced only by other classes defined in the same package as
one. Education, Inc.
Copyright ©this
2003 Pearson
Slide 45
Method main() definition
public static void main(String[] args) {body}
• The keywords public static void have the following
meaning:
 public means that the method can be accessed outside of
the class (main() is called by the operating system).
 static means that main() is not applied to an object
when it is invoked.
 void means that main() does not return a result but is
executed for its effect.
• The parameter list (String[] args) indicates that method
main() has an array of String objects as its argument.
Copyright © 2003 Pearson Education, Inc.
Slide 46
Java keywords (reserved words)
Keyword
Meaning
boolean
The data type used for storing and processing
boolean values.
The data type used for storing and processing
single characters.
Indicates the start of a class definition.
char
class
double
real
import
int
The data type used for storing and processing
numbers.
Makes the classes in a particular package
accessible to the classes in the current file.
The data type used for storing and processing
integers.
Copyright © 2003 Pearson Education, Inc.
Slide 47
Java keywords, contd.
Keyword
Meaning
new
Creates a new object instance.
private
Accessibility is restricted to the class defining this
item.
Accessibility is unrestricted.
public
static
void
There is exactly one method or data field with this
identifier for the class. A static (class) method is
not applied to an object.
Method is executed for effect; it returns no value.
Copyright © 2003 Pearson Education, Inc.
Slide 48
Java Conventions for Identifiers
Identifier type
Convention and
Examples
• Class name
A noun that starts with uppercase;
begin a
new word with an uppercase
letter.
Examples: PigLatinApp,
String, InOut
• Variable or data field A noun that starts with lowercase;
begin a new word with uppercase
letter.
Examples: sum, miles,
squareFeet
• method
A verb phrase or prepositional phrase
that
starts with lowercase; begin a new
word
with uppercase letter.
Examples: readString, print, toMeters
Copyright © 2003 Pearson Education, Inc.
Slide 49
Conventions for Identifiers, contd.
Identifier type
• package
• constant
Copyright © 2003 Pearson Education, Inc.
Convention and
Examples
A noun that starts with lowercase; begin a
new word with an uppercase letter.
Examples: swing, psJava
A noun that has all uppercase letters. Use
underscore symbol between words.
Examples: PI, FEET_PER_METER
Slide 50
Chapter 3 Object-oriented Design and
Writing Worker Classes
• Review of Class Definitions
• Review of Method Definitions
• Calling methods
Copyright © 2003 Pearson Education, Inc.
Slide 51
Review of Class Definitions
1.
Class header
2.
Class body
2.1 The data field declarations for the class
2.2 The method definitions of the class
• The data fields of a class (also called instance variables)
store the information associated with an object of that class. The
data fields may be referenced throughout the class. The values
stored in an object's data fields represent the state of that
object.
• The methods specify the operations that objects of the class
can peform.
We design worker classes or support classes that support the
application class or client class .
Copyright © 2003 Pearson Education, Inc.
Slide 52
Data field declarations in FoodItem
public class FoodItem {
// data
private
private
private
fields
String description;
double size;
double price;
• These data field declarations resemble variable
declarations except they begin with the visibility modifier
private.
• A private data field can be accessed directly in the class
in which it is defined, but not outside the class.
• Other classes can manipulate data field price, for
example, only through the methods of class FoodItem.
Copyright © 2003 Pearson Education, Inc.
Slide 53
Syntax for Data field Declaration
• Form: [visibility] typeName datafieldName = [value];
Example:
private int pennies;
private String month;
• Interpretation: The data type of datafieldName is specified as
typeName where typeName is a predefined Java type or a class
that has been defined by Java programmers. If value is present,
it must be a literal of data type typeName. The visibility may be
specified as private (accessible only within the class),
public (accessible anywhere), or protected (accessible
only within the class and by subclasses of the class). If omitted,
it has default visibility which means it can be accessed by any
class in the same folder as the current class.
Copyright © 2003 Pearson Education, Inc.
Slide 54
Method Definitions
Method definitions have the form
method header {
method body
}
parameters
header public static void main(String[] args) {
body
System.out.println("Hello world");
System.out.println("Java is fun");
}
Copyright © 2003 Pearson Education, Inc.
Slide 55
Method Header
• The method header gives the method name, the data type of the value
returned by the method (if any), and its parameters in parentheses.
Form: visibility [static] resultType methodName
([parameterList])
Examples:
public static void main(String[] args)
public double getPrice()
public void setPrice(double aPrice)
• Interpretation: The type of result returned is resultType where
void means the method does not return a result. The method
parameters appear in the parameterList. This list contains individual
data declarations (data type, identifier pairs) separated by commas.
Empty parentheses () indicate that a method has no parameters.
Copyright © 2003 Pearson Education, Inc.
Slide 56
Method header, cont’d.
• The method definition specifies visibility with modifier
keywords (for example, public, private) that precede the
resultType. The visibility specifies whether the method may be
called from outside the class (public visibility) or just within
the class (private visibility). Most methods we write have
public visibility.
• The keyword static indicates that a method is a class
method, not an instance method. Most methods we write are
instance methods.
Copyright © 2003 Pearson Education, Inc.
Slide 57
Methods for Class FoodItem
For most classes, we need to provide methods that perform tasks
similar to the ones below:
• a method to create a new FoodItem object with a specified
description, size, and price (constructor)
• methods to change the description, size, or price of an existing
FoodItem object (mutators)
• methods that return the individual attributes such as
description, size, or price of an existing FoodItem object
(accessors)
• a method that returns the object state as a string (a
toString() method).
Copyright © 2003 Pearson Education, Inc.
Slide 58
Method Headers for
Class FoodItem
Method
public
FoodItem(String,
double, double)
public void
setDesc(String)
public void
setSize(double)
Copyright © 2003 Pearson Education, Inc.
Description
• Constructor - creates a new
object whose three data
fields have the values
specified by its three
arguments.
• Mutator - sets the value of
data field description to
the value indicated by its
argument. Returns no value.
• Mutator - sets the value of
data field size to the value
indicated by its argument.
Returns no value.
Slide 59
Method Headers for
Class FoodItem, cont’d.
Method
public void
setPrice(double)
public String
getDesc()
public double
getSize()
Copyright © 2003 Pearson Education, Inc.
Description
• Mutator - sets the value of
data field price to the
value indicated by its
argument. Returns no value.
• Accessor - returns a
reference to the string
referenced by data field
description.
• Accessor - returns the value
of data field size.
Slide 60
Method Headers for
Class FoodItem, cont’d.
Method
public double
getPrice()
Description
• Accessor - returns the value
of data field price.
public String
toString()
• Returns a string representing
the state of this object.
public double
calcUnitPrice()
• Returns the unit price (price /
size) of this item.
Copyright © 2003 Pearson Education, Inc.
Slide 61
Class FoodItem
/*
* FoodItem.java
Author: Koffman and Wolz
* Represents a food item at a market
*/
public class FoodItem {
// data
private
private
private
fields
String description;
double size;
double price;
Copyright © 2003 Pearson Education, Inc.
Slide 62
Class FoodItem, cont’d.
// methods
// postcondition: creates a new object with data
//
field values as specified by the arguments
public FoodItem(String desc, double aSize,
double aPrice) {
description = desc;
size = aSize;
price = aPrice;
}
// postcondition: sets description to argument
//
value
public void setDesc(String desc) {
description = desc;
}
Copyright © 2003 Pearson Education, Inc.
Slide 63
Class FoodItem, cont’d.
// postcondition: sets size to argument value
public void setSize(double aSize) {
size = aSize;
}
// postcondition: sets price to argument value
public void setPrice(double aPrice) {
price = aPrice;
}
// postcondition: returns the item description
public String getDesc() {
return description;
}
// postcondition: returns the item size
public double getSize() {
return size;
}
Copyright © 2003 Pearson Education, Inc.
Slide 64
Class FoodItem, cont’d.
// postcondition: returns the item price
public double getPrice() {
return price;
}
// postcondition: returns string representing
// the item state
public String toString() {
return description + ", size : " + size +
", price $" + price;
}
// postcondition: calculates & returns unit price
public double calcUnitPrice() {
return price / size;
}
}
Copyright © 2003 Pearson Education, Inc.
Slide 65
void Methods
void
setSize(double
aSize) {
• Thepublic
mutator
methods
are void methods.
size = aSize;
}
• Method setSize() sets the value of data field size to the
value passed to parameter aSize.
• A void method is executed for its effect because it does not
return a value; however, it may change the state of an object or
cause some information to be displayed.
Copyright © 2003 Pearson Education, Inc.
Slide 66
The return Statement
• Each FoodItem method that is not a void method or a
constructor returns a single result.
public double getPrice() {
return price;
}
The return statement above returns the value of data field
price as the function result.
• Form: return expression;
• Example: return x + y;
• Interpretation: The expression after the keyword return is
returned as the method result. Its data type must be assignment
compatible with the type of the method result.
Copyright © 2003 Pearson Education, Inc.
Slide 67
toString() Method
• A toString() method returns a reference to a String
object that represents an object's state.
public String toString() {
return description + ", size : " + size +
", price $" + price;
}
The expression after return specifies the characters stored in
the String object returned as the method result. It starts with
the characters in description followed by the characters ,
size : followed by characters representing the value of data
field size and price; e.g.,
"apples, Macintosh, size: 2.5, price $1.25"
Copyright © 2003 Pearson Education, Inc.
Slide 68
Calling methods
• Because a void method does not return a value, a call to a void
method is a Java statement all by itself. If myCandy is type
FoodItem, an example would be
myCandy.setDescription("Snickers, large");
• Because a non-void method returns a value, a call to a nonvoid method must occur in an expression:
"price is $" + myCandy.getPrice()
• The result returned by the call to method getPrice() (type
double) is appended to the string that starts with the characters
price is $
Copyright © 2003 Pearson Education, Inc.
Slide 69
Call to Constructor
public FoodItem(String desc, double aSize,
double aPrice) {
description = desc;
size = aSize;
price = aPrice;
}
• A constructor executes when a new object is created and
initializes the object’s data fields. A call to this constructor
always follows the word new and has the form:
FoodItem myCandy = new FoodItem("Snickers",
6.5, 0.55);
Copyright © 2003 Pearson Education, Inc.
Slide 70
Argument/Parameter Correspondence
Method call
FoodItem("Snickers",
6.5, 0.55);
Method heading
public FoodItem(String desc,
double aSize, double aPrice)
Parameters
Arguments
"Snickers"
6.5
0.55
desc (references "Snickers")
aSize (value is 6.5)
aPrice(value is 0.55)
Primitive type arguments are passed by value which
means the method cannot change the argument value.
Copyright © 2003 Pearson Education, Inc.
Slide 71
Testing the class FoodItem
UML class diagram
client
(application) class
TestFoodItem
UML sequence diagram
TestFoodItem
main()
new()
association
relationship
description: String
size: double
price: double
FoodItem()
setDesc()
setSize()
setPrice()
getDesc()
getSize()
getPrice()
calcUnitPrice()
toString()
Program classes and their relationships
Copyright © 2003 Pearson Education, Inc.
myCandy:
FoodItem
creation of a
new object
mySoup:
FoodItem
new()
FoodItem
toString()
time axis
worker
class
classes/
objects
object
lifeline
calculateUnitPrice()
toString()
calculateUnitPrice()
method
call
method
execution
return from
method (may
not be shown)
Collaboration between objects (classes) at runtime
Slide 72
Application or Client of FoodItem
/*
* TestFoodItem.java
Author: Koffman and Wolz
* Tests class FoodItem
*/
public class TestFoodItem {
public static void main(String[] args) {
FoodItem myCandy = new FoodItem("Snickers", 6.5,
0.55);
FoodItem mySoup = new FoodItem(
"Progresso Minestrone",
16.5, 2.35);
System.out.println(myCandy.toString());
System.out.println(" -- unit price is $" +
myCandy.calcUnitPrice());
System.out.println(mySoup.toString());
System.out.println(" -- unit price is $" +
mySoup.calcUnitPrice());
}
}
Copyright © 2003 Pearson Education, Inc.
Slide 73
Sample Run of Class TestFoodItem
Copyright © 2003 Pearson Education, Inc.
Slide 74
Transfers of Control for
System.out.println(myCandy.toString());
...(myCandy.toString());
» Call method toString() of object myCandy
» Execute method body
» Return string result and transfer control back to
calling statement
System.out.println( . . . );
• Call method println() of object System.out with result of
myCandy.toString() as argument
• Execute method body to display string argument
• Transfer control back to calling statement in method
main()
• Execute next statement in method main()
Copyright © 2003 Pearson Education, Inc.
Slide 75
Diagram of object myCandy
myCandy
reference to a
FoodItem object
data
datafields
fields
description
description::
size
size: :6.5
6.5
price
:
price:0.55
0.55
methods
methods
FoodItem()
FoodItem()
setDescription()
setDescription()
and
andother
othermutators
mutators
getDescription()
getDescription()
and
andother
otheraccessors
accessors
calcUnitPrice()
calcUnitPrice()
toString()
toString()
Copyright © 2003 Pearson Education, Inc.
reference to a
String object
data
datafields
fields
the
thecharacters
characters Snickers
Snickers
methods
methods
charAt()
charAt()
indexOf()
indexOf()
length()
length()
substring()
substring()
toUpperCase()
toUpperCase()
Slide 76
Program Style: Separation of Concerns
• Each class was relatively easy to design and
implement. By splitting the problem solution up into
three classes, we were able to keep things simple.
• The Circle class focused on those tasks that were
relevant to Circle objects
• The Washer class focused on those tasks that were
relevant to Washer objects.
• Also, we now have two more reusable classes, Circle
and Washer, which may turn out to be handy in other
problem solutions.
Copyright © 2003 Pearson Education, Inc.
Slide 77
4.1 Control Structures
• compound statement or block
{
statement1;
statement2;
...
statementn;
}
• selection control structures
– if statement
– switch statement
• loop statement
– while statement
– for statement
Copyright © 2003 Pearson Education, Inc.
Slide 78
4.2 Boolean Expressions
• The simplest boolean expression is a boolean variable, whose
type is the primitive type boolean
– just two possible values: true and false
– logical operations: and, or, not
Ex. of variable declarations: boolean eligible;
boolean flag;
boolean leapYear = true;
Copyright © 2003 Pearson Education, Inc.
Slide 79
Relational operators
• Relational operators: used to compare two expressions which are type
compatible (same type or one can be promoted to the other without loss
of information )
Operator
Meaning
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
==
equals
!=
does not equal
Example
Value
pressure < MaxPressure
kTemp <= kIce
init > ‘K’
250 >= kTemp
init == ‘Q’
kIce != kTemp
true
true
false
true
false
true
The variables used in the examples above have the following types and values:
kIce 273
kTemp 250
init J
pressure 37.2
MaxPressure 38.5
• Comparing real numbers:
– it is not recommended to compare two real values for equality x ==
approx (they may be very close, but not exactly equal due to
rounding errors)
– use instead the condition |x - approx| < 10-12 written in Java as
Copyright © 2003 Pearson Education, Inc.
Slide 80
Math.abs (x - approx) < 1e-12
Reading boolean data
• Using method JOptionPane.showConfirmDialog()
int happyNum = JOptionPane.showConfirmDialog(null,
” Are you happy?", "true/false",
JOptionPane.YES_NO_OPTION);
boolean happyMood = (happyNum == 0);
0
1
2
• Using method KeyIn.readBoolean()
import psJava.*;
...
boolean happyMood = KeyIn.readBoolean("Are you happy?");
Copyright © 2003 Pearson Education, Inc.
Slide 81
Logical operators
Logical operators: and &&, or ||, not !
operand1
operand2
false
false
true
true
false
true
false
true
operand
false
true
! operand
true
false
operand1 && operand2
false
false
false
true
operand1 || operand2
false
true
true
true
Short-circuit evaluation of boolean expressions
Boolean expressions of the form p && q and p || q
are evaluated from left to right, and only as much of the
expression is evaluated as is necessary to know the result.
Examples
0 <= n && n <= 100 represents the condition 0 <= n <= 100
(‘a’ <= c && c <= ‘z’) || (‘A’ <= c && c <= ‘Z’) means c is a letter
‘0’ <= c && c <= ‘9’ means c is digit, where c is of type char
Copyright © 2003 Pearson Education, Inc.
Slide 82
Operator precedence revisited
Operator
Method call
! + (unary) -(unary)
Type cast
* / %
+ < <= >= >
== !=
&&
||
=
Precedence
highest
lowest
Examples:
parentheses: x + a < y + b is equivalent to (x + a) < (y + b)
 boolean assignment:
inRange = (n > -10) && (n < 10);
flag = (y != x);
 order of evaluation:
!flag || y + z >= x - z
!( flag || y + z >= x - z )

Copyright © 2003 Pearson Education, Inc.
Slide 83
Comparing strings
• Comparing strings for equality:
String first = “ace”;
String second = “aces”;
first.equals (second)
“ace”.equals (first)
first.equals (“ACES”)
second.equals (first + “s”)
first.equals (second.substring(0,3))
false
true
false
true
true
• Lexicographic comparisons (as they would appear in a dictionary)
compareTo(): returns a negative, zero or positive value if the string is
smaller, equal or larger than the argument, respectively
String text = “XYZ”;
“XYZ”.compareTo (“ABC”)
test.compareTo (“XYZ”)
“XYZ”.compareTo (“xyz”)
“acts”.compareTo (“aces”)
“ace”.compareTo (“aces”)
“aces”.compareTo (“ace”)
“1234”.compareTo(“56”)
Copyright © 2003 Pearson Education, Inc.
positive value: ‘X’ > ‘A’
zero: “XYZ” equals “XYZ”
negative value: ‘X’ < ‘x’
positive value: ‘t’ > ‘e’
negative value: “ace” is shorter
positive value: “aces” is longer
negative value: ‘1’ < ‘5’
Slide 84
4.3 if statement
• Syntax: if statement with one consequent
if (condition)
statement
simple or
compound
statement
condition
false
if ( count > 0 )
average = sum / count;
System.out.println (average);
true
statement
• Syntax: if statement with two alternatives (if-else)
if (condition)
statementT
else
statementF
simple or
compound
statement
true
condition
statementT
false
statementF
if ( count > 0 )
average = sum / count;
else
average = 0.0;
System.out.println (average);
Copyright © 2003 Pearson Education, Inc.
Slide 85
if statement to order x and y
if (x > y) {
// Switch x and y
temp = x;
x = y;
y = temp;
}
// Stores old x in temp.
// Stores old y in x.
// Stores old x in y.
Trace of if statement
Statement part
x
12.5
if (x > y)
temp = x;
x = y;
y = temp;
Copyright © 2003 Pearson Education, Inc.
5.1
y
5.1
temp Effect
?
12.5 > 5.1 is true.
12.5
Stores old x in temp.
Stores old y in x.
12.5
Stores old x in y.
Slide 86
if statement syntax (one consequent)
• if Statement (One Consequent)
• Form:
if (condition) {
statementT;
}
• Example:
if (x > 0.0) {
posProd = posProd * x;
}
• Interpretation: If condition evaluates to true, then statementT (the true
task) is executed; otherwise, statementT is skipped.
Note: if statementT is a single statement, the enclosing braces {} may
be omitted.
Copyright © 2003 Pearson Education, Inc.
Slide 87
if statement syntax (two alternatives)
• if Statement (Two Alternatives)
• Form:
if (condition) {
statementT;
}
else {
statementF;
}
• Example:
if (x >= 0.0) {
System.out.println("Positive or zero");
}
else {
System.out.println("Negative");
}
• Interpretation: If condition evaluates to true, then statementT (the true
task) is executed and statementF is skipped; otherwise, statementT is
skipped and statementF (the false task) is executed.
• Note: if statementT or statementF is a single statement, the enclosing
braces {} around it may be omitted.
Copyright © 2003 Pearson Education, Inc.
Slide 88
4.4 Decision Steps in Algorithms
Problem: For the Pig Latin
algorithm on the right , write a
method that tests if first letter is vowel.
First variant of the test
private boolean FirstLetterIsAVowel() {
char first = word.charAt(0);
if (first == ‘a’ || first == ‘e’ || first == ‘i’ ||
first == ‘o’ || first == ‘u’ || first == ‘y’ ||
first == ‘A’ || first == ‘E’ || first == ‘I’ ||
first == ‘O’ || first == ‘U’ || first == ‘Y’)
return true;
else return false;
}
Second variant of the test
private boolean FirstLetterIsAVowel() {
char first = word.charAt(0);
return (first==‘a’ || first==‘e’ || first==‘i’||
first == ‘o’ || first == ‘u’ || first == ‘y’ ||
first == ‘A’ || first == ‘E’ || first == ‘I’ ||
first == ‘O’ || first == ‘U’ || first == ‘Y’);
}
Copyright © 2003 Pearson Education, Inc.
if (the first letter of word is a vowel)
return word as it is
else modify word and return it
Third variant of the test
private boolean FirstLetterIsAVowel(){
string vowels = “aeiouyAEIOUY”;
char first = word.charAt(0);
return (vowels.indexOf(first) > -1);
}
Method translateWord()
public void translateWord() {
if (FirstLetterIsAVowel() )
return (word);
else
return(word.substring(1) +
word.charAt(0) +
“ay”);
}
Slide 89
4.5 Nested if-else and switch statements
Simple if-else format
if (condition)
statementT
else
statementF
Nested if -else format
if (condition1 )
if (condition2 )
statementT2
else
statementF2
else
if (condition3 )
statementT3
else
statementF3
Matching rule: in a nested if-else statement, an else is matched with
the closest preceding if that is not matched yet.
if ( x > 0 )
if (y > 0) {
z = sqrt (x) + sqrt (y);
System.out.println(“z = “ + z);
} else
System.out.println( “*** can’t compute z”);
Copyright © 2003 Pearson Education, Inc.
Slide 90
Multiple-alternative selection


Multiple-alternative selection: choose exactly one alternative out of
more than two mutually-exclusive alternatives.
Implementation: either as a nested if-else structure (where new decisions
fall on else branches), or as an equivalent if-else if structure.
Nested if -else format
if (condition1 )
statement1
else
if (condition2 )
statement2
else
if (condition3 )
statement3
else .
..
if (conditionn )
statementn
else
statementn+1
Copyright © 2003 Pearson Education, Inc.
Equivalent if -else if format
if (condition1 )
statement1
else if (condition2 )
statement2
else if (condition3 )
statement3
else if
.
.
.
else if (conditionn )
statementn
else
statementn+1
Slide 91
Example of multiple-alternative
selection
neutral
very acidic
acidic
alkaline
Solution pH:
3
pH < 3
false
false
very acidic
true
acidic
pH>=7
pH ==7
false
true
neutral
pH >7
pH<12
false
12
pH
true
pH>=3
pH<7
7
very alkaline
true
alkaline
pH>=12
very alkaline
Copyright © 2003 Pearson Education, Inc.
if (pH < 3)
System.out.println( "Solution is very acidic.”);
else if (pH < 7)
System.out.println( "Solution is acidic.”);
else if (pH == 7)
System.out.println(”Solution is neutral.");
else if (pH < 12)
System.out.println( "Solution is alkaline.”);
else
System.out.println( "Solution is very alkaline.”);
if (pH >= 12)
System.out.println( "Solution is very alkaline.”);
else if (pH > 7)
System.out.println( "Solution is alkaline.”);
else if (pH == 7)
System.out.println(”Solution is neutral.");
else if (pH >= 3)
System.out.println( "Solution is acidic.”);
else
System.out.println( "Solution is very acidic.”);
Slide 92
Inefficient coding of multiple-alternative selection
neutral
very acidic
acidic
3
alkaline
7
very alkaline
12
pH
Inefficient solution: a sequence of separate if stmts instead of a nested structure.
 It executes slower than a nested if-else structure, because the if statements in the
sequence are always executed (i.e., all the conditions are tested) no matter when
the only true condition is found. For example, even if the first condition is
found to be the one that’s true, all the other are tested anyway.
 Repeated conditions: we should test either pH < 12 or pH >= 12, not both.
if (pH < 3)
System.out.println( "Solution is very acidic.”);
if (pH >= 3 && pH < 7)
System.out.println( "Solution is acidic.”);
if (pH == 7)
System.out.println(”Solution is neutral.");
if (pH > 7 && pH < 12)
System.out.println( "Solution is alkaline.”);
if (pH >= 12)
System.out.println( "Solution is very alkaline.”);
Copyright © 2003 Pearson Education, Inc.
Slide 93
Decision table for a payroll system
Salary range
0.00 - 1,499.99
1,500.00 - 2,999.99
3,000.00 - 4,999.99
5,000.00 - 7,999.99
8,000.00 and over
Base tax
0.00
225.00
465.00
825.00
1425.00
Percentage of excess
15 %
16 %
18 %
20 %
25 %
if (salary < 0.00)
// error
System.out.println( ”*** Error: negative salary $” + salary);
else if (salary < 1500.00) // first range
tax = 0.15 * salary;
else if (salary < 3000.00) // second range
tax = 225.00 + (salary - 1500.00) * 0.16;
else if (salary < 5000.00) // third range
tax = 465.00 + (salary - 3000.00) * 0.18;
else if (salary < 8000.00) // fourth range
tax = 825.00 + (salary - 5000.00) * 0.20;
else
// fifth range
tax = 1425.00 + (salary - 8000.00) * 0.25;
Copyright © 2003 Pearson Education, Inc.
Slide 94
Nested if with independent conditions
false
apply to local
college
earnings>2000
false
true
SAT>1300
true
apply to parents apply to first
alma mater
choice college
if (earnings > 2000.00) {
if (SAT > 1300)
System.out.println( ”Apply to first choice college”);
else
// SAT <= 1300
braces { }
System.out.println( ”Apply to parents alma mater”);
not necessary
} else
// earnings <= 2000
System.out.println( ”Apply to local college”);
Copyright © 2003 Pearson Education, Inc.
Slide 95
Compare date objects d1 and d2 (year, month, day)
true
false
d1.y <d2.y
true
d1.y ==d2.y
false
d1 before d2
d1 after d2
true
d1.m <d2.m
false
true
d1.m ==d2.m
false
d1 before d2
true
d1.d <d2.d
true
d1 before d2
Copyright © 2003 Pearson Education, Inc.
d1 after d2
false
d1d ==d2.d
d1 equal to d2
false
d1 after d2
Slide 96
Nested multiple-alternative selection
if (d1.year < d2.year)
// first date < second date
System.out.print( ”The first date is before the second.");
else if (d1.year == d2.year)
// must compare months, days
if (d1.month < d2.month)
// first date < second date
System.out.print( ”The first date is before the second.");
else if (d1.month == d2.month) // must compare days
if (d1.day < d2.day)
// first date < second date
System.out.print( ”The first date is before the second.");
else if (d1.day == d2.day)
// dates are equal
System.out.print( ”The two dates are equal." );
else
// here (d1.day > d2.day)
System.out.print( " The first date is after the second.");
else
// here (d1.month > d2.month)
System.out.print( " The first date is after the second."););
else
// here (d1.year > d2.year)
System.out.print( " The first date is after the second.");
Copyright © 2003 Pearson Education, Inc.
Slide 97
Switch statement
Switch statement syntax:
Interpretation:

switch (selector ) {
case label11:
case label12:
...
case label1k: statements1
break;
.
.
.
case labeln1:
case labeln2:
...
case labelnm: statementsn
break;
default:
statementsd
}




Type of selector and of labels



Copyright © 2003 Pearson Education, Inc.
value of selector is evaluated and compared to
each label in turn
when a matching label is found, the
statements that follow that label are executed
until a break or a return statement is reached;
all the other statements in the switch block are
skipped
if no matching label is found, the statements
following default are executed.
default clause is optional; if it’s missing, no
statement is executed in the cases when no
matching label was found.
if a break (return) statement is missing,
execution “falls through” to the statements
associated with the next set of labels.
must be an ordinal type (in Java, ordinal types
are: integer types, bool and char)
cannot be a floating point type, nor a string of
characters
each label must be a unique value of the same
type as the selector
Slide 98
Switch statement examples
// Set price for a light bulb of
//
40, 60, 75, 100 or 150 watts
switch (watts) {
case 40: price = 0.50;
break;
case 60: price = 0.69;
break;
case 75: price = 0.85;
break;
case 100:
case 150: price = 1;
break;
default: price = 0;
System.out.print (“No bulb ”
+watts + “watts in stock”);
} // end switch
same effect
// Method to return the price of a light bulb
public double bulbPrice (int watts) {
switch (watts) {
case 40:
return 0.50;
case 60:
return 0.69;
case 75:
return 0.85;
case 100:
case 150:
return 1;
default:
return 0;
} // end switch
if (watts == 40)
price = 0.50;
else if (watts== 60) price = 0.69;
else if (watts == 75) price = 0.85;
else if (watts == 100 || watts==150) price = 1;
else { price = 0;
System.out.print (“No bulb ”+watts + “watts in stock”);
}
Copyright © 2003 Pearson Education, Inc.
Slide 99
4.6 Counting loops, while and for statements
A loop that executes a prespecified number of times is called a
counting loop (or counter-controlled loop).
Algorithm for payroll computation for a group of employees
1. Get the number of employees
2. for each employee starting with the first and ending with the last
2.1
Get the current employee's payroll data.
2.2
Store the current employee's payroll data.
2.3
Compute the current employee's gross and net pay.
2.4
Display the current employee's gross and net pay.
Algorithm for payroll computation with counter
1. Get the number of employees
2. Set the counter to 0
3. While the counter is less than the number of employees
3.1
Get the current employee's payroll data.
3.2
Store the current employee's payroll data.
3.3
Compute the current employee's gross and net pay.
3.4
Display the current employee's gross and net pay.
3.5
Add 1 to counter.
Copyright © 2003 Pearson Education, Inc.
Slide 100
Elements of a loop
sum = 0
count = 0
count < n
Flowchart
notation
repeat
the loop



initialization
section
false
true
enter a score
sum = sum + score
count = count + 1
loop-repetition
condition
loop body
exit the loop
loop body: the part that is repeated in the loop
loop-repetition condition: decides when to repeat the loop and when to
exit; the condition tests one or more variables (at least one modified in
the loop body).
initialization section: assigns initial values to the variables tested in the
loop condition (such as count) and to other variables that are used before
being given a value in the loop body (such as sum).
Copyright © 2003 Pearson Education, Inc.
Slide 101
Loops: while statement
Format
while (condition)
statement





part of the loop
not contained in
the while stmt.
initialization
A while statement implements a prefalse
condition
test loop which is repeated as long as
the condition is true.
true
The repetition ends when the condition
is found to be false, and the execution repeat
statement
continues with the statement that
the loop
follows the loop body.
The body of the loop must eventually
cause the condition to become false,
exit the loop
otherwise an infinite loop results.
The loop body is a simple or a
Important: do not confuse
the while statement (a loop)
compound statement.
with the if statement (a
a while loop may be executed zero
selection which does not
times if the condition is found false
imply any repetition).
when tested for the first time.
Copyright © 2003 Pearson Education, Inc.
Slide 102
Accumulating a sum
int next;
int sum = 0;
int count = 0;
while (count < MAX) {
readInt(next);
sum = sum + next;
count = count + 1;
} // end loop
// the next number
// the sum so far
// initialize loop counter
// test loop counter
// get next number
// add next number to sum
// increment loop counter
Trace of while loop
next
after initialization ?
after 1st iter.
15
after 2nd iter.
20
after 3rd iter.
-5
...
sum
0
15
35
30
Copyright © 2003 Pearson Education, Inc.
count
0
1
2
3
sum and count set to 0, next undefined
15 read into next and added to sum
20 read into next and added to sum
-5 read into next and added to sum,
Slide 103
Example of counter-controlled while loop
Method main of the payroll problem is modified to accept more than one
employee and to compute the total salary paid to all employees.
Note 1: method main uses System.out.println() for displaying the results.
Note 2: a better designed solution will be presented later.
public class PayAmounts {
public static void main (String[] args) {
// Create an Employee object.
Employee programmer = new Employee();
double payroll = 0;
// init sum of all salaries
int countEmp = 0;
// init loop counter
while (countEmp < 7) {
programmer.enterEmpData(); // get current employee data
programmer.showEmp();
// compute and display empl. info
payroll = payroll + programmer.computeGross(); // add to sum
countEmp = countEmp + 1;
// increment loop counter
} // end loop
System.out.println (“Total salaries: $” + payroll);
}
} // Class PayAmounts
Copyright © 2003 Pearson Education, Inc.
Slide 104
for statement
Format
initialization
of loop control
variable
for (initialization; condition; update)
statement



A for loop is a loop structure which is
mainly used to implement counter-controlled
loops
a for loop may be executed zero times if the
condition is false when first tested
Example: two equivalent counter-controlled
loops: one with for and the other with while
for (int i = initial ; i <= final; i = i+step) {
// insert loop body here
var i defined
}
only inside the
loop body
int i = initial ;
while (i <= final) {
// insert loop body here
i = i + step;
}
Copyright © 2003 Pearson Education, Inc.
false
condition
true
loop body
update
loop control
variable
exit the loop
Slide 105
Increment and Decrement operators
Increment operator ++ and decrement operator -

apply to a single operand which must be a variable (not an expression!)
have double effect:
 use the value of the operand to evaluate the expression in which they appear
 side effect: change the value of the operand (sometimes used only for the side
effect)
Ex:
count++; equivalent to count = count + 1;
Format
 prefix: ++variable

--variable
postfix: variable++
increment/decrement variable then use
the new value in the expression
use old value of variable in the expression
then increment/decrement variable)
variable--
Comparison of prefix and postfix increments:
Before:
Expressions:
After:
Copyright © 2003 Pearson Education, Inc.
i
2
k
3
j
?
j = ++i * k;
j = i++ * k;
i
3
i
3
k
3
k
3
j
9
j
6
Slide 106
Compound assignment operators
Format
variable op= expression equivalent to variable = variable op (expression)


Compound assignment operators op= are defined in Java for all five
arithmetic operators:
+= -=
*=
/=
%=
Purpose: more concise notation, more efficient implementation
Examples of equivalent statements
Simple assignment operator
Compound assignment operator
count = count + 1;
time = time -1;
count += 1;
time -= 1;
sum = sum + data;
factorial = factorial * (i + 1);
x = x / (i * (i+1));
sum += data;
factorial *= (i + 1);
x /= i * (i+1);
r = r % base;
r %= base;
name = name + “ending”
name += “ending” // concatenation
Copyright © 2003 Pearson Education, Inc.
Slide 107
4.7 State-controlled loops
In a state-controlled loop, or general conditional loop, repetition stops when a state is
reached that causes the loop-repetition condition to become false.
State-controlled loop with a boolean loop control variable
Set the loop control variable to true
while the loop control variable is true {
Execute the steps in the loop body
Update the loop control variable
}
// initialize
// test
// update
boolean moreEmp = true;
while (moreEmp) {
// Compute and display current employee's information.
. . .
moreEmp = Keyboard.readBoolean("Any more employees?");
}
Copyright © 2003 Pearson Education, Inc.
Slide 108
Sentinel-controlled loops
Sentinel-controlled loop
Get the first data item or the sentinel
while the data item is not the sentinel {
Process the current data item
Get the next data item or the sentinel
}
// initialize
// test
// update
Sentinel value: a pre-defined value entered after the last data item to indicate the end of
input data. The sentinel value is not processed as “real” input data.
// precondition: count and sum are zero
// postcondition: data field sum stores the sum of scores
//
data field count stores the count of scores
public void findSumAndCount() {
int score;
int SENTINEL = -1;
// sentinel value
score = readInt("Enter next score or " + SENTINEL +
" to stop");
// initialize lcv
while (score != SENTINEL) {
// test lcv
sum += score;
// add current score to sum
count++;
// increase count by 1
System.out.println("score: " + score);
score = readInt("Enter next score or " + SENTINEL +
" to stop");
// update lcv
}
}
Copyright © 2003 Pearson Education, Inc.
Slide 109
Comparison of methods for loop control
Counter-controlled
loop
initialization
count = first
State-controlled or
Conditional loop
initialization
(condition variables
included)
count<=final false
true
loop body
count = count+step
exit the loop
The loop is executed for
the following values of
the variable count:
first, first+step, ... , last
where: (last <= final)
and (last+step > final)
Copyright © 2003 Pearson Education, Inc.
condition
false
true
loop body
(condition variables
are updated)
Sentinel-controlled
loop
initialization
enter first value
value !=
sentinel
true
false
loop body
enter next value
exit the loop
exit the loop
The loop is controlled by
the values entered by the
The loop is executed until
user. The loop body is
a certain state is reached
executed as long as the
that causes the condition
most recent value is
to become false
different from a pre-defined
sentinel value.
Slide 110
5.1 Array Declarations
Array = a collection of data items of the same type.
Array declaration syntax:
elementType [ ] arrayName = new elementType [size];
elementType [ ] arrayName = { list_of_values };
Examples:
double[ ] salary = new double[50];
int[ ] coinValues = {1, 5, 10, 25, 50};
Interpretation: arrayName represents a collection of array
Array x
of 12 elements
x[0]
7.3
x[1]
3.9
x[2]
..
.
5.3
..
.
x[11] 12.7
elements, each of which can store an item of elementType.
The elementType can be any primitive type or class. index: from
0 to size-1
If it’s a class, the array contains references to objects of
memory
that class. Memory must be allocated separately for each
out of range
of these objects (to be discussed later).
The size may de specified, or implied by the size of list_of_values.
Separating array declaration and memory allocation
double[ ] salary;
salary = new double[50];
double[ ] salary;
salary = new double[readInt(“How many salaries?”)];
constant size
Copyright © 2003 Pearson Education, Inc.
size obtained at run time
Slide 111
Manipulating an array y
double
y
y[] = {16, 12, 6, 8, 2.5, 12, 14, -54.5};
y[0]
16.0
y[1]
12.0
y[2]
y[3]
6.0
8.0
y[2]
y[3]
28.0
25.0
y[4]
y[5]
y[6]
y[7]
12.0
14.0
-54.5
y[4]
y[5]
y[6]
y[7]
14.0
14.0
14.0
26.0
2.5
y[3] = 25.0;
y[7] = y[3] + 1.0;
y[2] = y[0] + y[1];
int i = 5;
y[i] = y[i + 1];
y[i - 1] = y[i];
y
y[0]
16.0
y[1]
12.0
Copyright © 2003 Pearson Education, Inc.
Slide 112
5.2 Processing Arrays and Array Elements
public class ArrayCubes {
// data fields
private int[] cubes; // a reference to array of ints
// methods
// postcondition: creates an array of size numCubes
public ArrayCubes(int numCubes) {
cubes = new int[numCubes];
}
Set size of array
// postcondition: Each element of cubes stores the
//
cube of its subscript: 0, 1, 8, 27, and so on.
public void fillCubes() {
// Fill array cubes.
for (int i = 0; i < cubes.length; i++) {
cubes[i] = i * i * i;
cubes.length
}
}
is array size
// postcondition: Returns string containing the cubes
//
separated by spaces
public String toString () {
String cubeStr = "";
for (int i = 0; i < cubes.length; i++) {
cubeStr = cubeStr + cubes[i] + "
";
}
return cubeStr;
Concatenate result
}
}
Copyright © 2003 Pearson Education, Inc.
string with next element
and some spaces
Slide 113
Class TestArrayCubes and sample run
import javax.swing.*;
public class TestArrayCubes {
public static void main (String[] args) {
// Get array size.
String numStr =
JOptionPane.showInputDialog("How many cubes?");
int numCubes = Integer.parseInt(numStr);
// Create an ArrayCubes object with an array of this size.
ArrayCubes aC = new ArrayCubes(numCubes);
// Fill the array.
aC.fillCubes();
// Display the array contents.
JOptionPane.showMessageDialog(null,
"The first " + numCubes +
" cubes are: \n" + aC.toString());
}
}
Copyright © 2003 Pearson Education, Inc.
Slide 114
Calculating exam statistics
PROBLEM: Your computer science instructor needs a simple program for computing
exam statistics. This program should read the scores for an exam and then compute and
display various exam statistics such as the mean score, standard deviation, low score,
and high score for the exam.
ANALYSIS: The problem inputs consist of the count of scores and the exam scores. The
outputs are all the exam statistics.
Data Requirements
Problem Inputs
count of scores
exam scores
Problem Outputs
the exam statistics
Relevant Formulas
mean = sum of array values / count of elements
standard deviation = square root(sum of squares of values / count of elements
- mean2)
Copyright © 2003 Pearson Education, Inc.
Slide 115
Design of class ExamStatistics
Data fields
int[] scores
Methods
void readScores()
int findMin()
int findMax()
double computeMean()
double
computeStandDev(double)
String toString()
Attributes
An array of exam scores.
Behavior
Reads the exam data.
Find the smallest score.
Finds the largest score.
Calculates the mean score.
Calculates the standard deviation.
Returns a string representing the
array of scores.
Classes Used
KeyIn
Copyright © 2003 Pearson Education, Inc.
Slide 116
Design of class ExamStatistics, cont’d.
Algorithm for readScores()
1.
for each student who took the exam
Read the next score.
Algorithm for findMin()
1.
2.
Set minSoFar to the first exam score.
for each student who took the exam after the first one
if the current score is less than minSoFar
Set minSoFar to the current score
Algorithm for computeMean()
1.
2.
3.
Set sum of scores to zero.
for each student who took the exam
Add the current score to sum.
Divide sum by the number of students who took the exam.
Algorithm for computeStandDev()
1.
2.
3.
Set sum of squares to zero.
for each student who took the exam
Add the current score squared to sum of squares.
Divide sum of squares by count of students, subtract the mean
squared, and take the square root of the result.
Copyright © 2003 Pearson Education, Inc.
Slide 117
Class ExamStatistics
import psJava.KeyIn;
public class ExamStatistics {
// Data Fields
private int[] scores;
// scores is an array of ints
// Methods
// postcondition: scores references an array object with num
//
type int elements.
public ExamStatistics(int num) {
// Allocate storage for the array.
scores = new int[num];
}
// postcondition: reads data into array scores.
public void readScores() {
// Read the scores
for (int i = 0; i < scores.length; i++)
scores[i] = KeyIn.readInt("Score for next student:");
}
// postcondition: returns the mean of the scores
public double computeMean() {
int sum = 0;
for (int i = 0; i < scores.length; i++)
sum += scores[i];
}
if (scores.length > 0)
return (double) sum / (double) scores.length;
else
return 0;
Copyright © 2003 Pearson Education, Inc.
Slide 118
Class ExamStatistics, cont’d.
// postcondition: returns the largest score.
public int findMax() {
// Find largest score if array is not empty.
if (scores.length > 0) {
int maxSoFar = scores[0];
// Remember first score
// Remember any larger scores.
for (int i = 1; i < scores.length; i++) {
if (scores[i] > maxSoFar)
maxSoFar = scores[i];
}
return maxSoFar;
}
}
else
return 0;
// array is empty
// postcondition: returns the smallest score.
public int findMin() {
// Find smallest score if array is not empty.
if (scores.length > 0) {
int minSoFar = scores[0];
// Remember first score
// Remember any smaller scores.
for (int i = 1; i < scores.length; i++) {
if (scores[i] < minSoFar)
minSoFar = scores[i];
}
return minSoFar;
}
}
else
return 0;
Copyright © 2003 Pearson Education, Inc.
// array is empty
Slide 119
Class ExamStatistics, cont’d.
// precondition: the mean score is defined.
// postcondition: returns the standard deviation.
public double computeStandDev(double mean) {
// Compute sum of scores-squared
int sumSquares = 0;
for (int i = 0; i < scores.length; i++)
sumSquares += (scores[i] * scores[i]);
}
if (scores.length > 0)
return Math.sqrt((double) sumSquares / scores.length mean * mean);
else
return 0;
// postcondition: returns a String containing exam scores.
public String toString () {
}
}
String examStr = "";
for (int i = 0; i < scores.length; i++) {
examStr = examStr + scores[i] + "
";
}
return examStr;
Copyright © 2003 Pearson Education, Inc.
Slide 120
Class RunExamStatistics
import psJava.KeyIn;
public class RunExamStatistics {
public static void main(String[] args) {
// Compute statistics if array is created.
ExamStatistics ex =
new ExamStatistics(KeyIn.readInt("How many scores?"));
// Read the scores
ex.readScores();
// Show results of statistics calculations
System.out.println("The scores are:\n" + ex.toString());
System.out.println("\nMinimum score: " + ex.findMin());
System.out.println("\nMaximum score: " + ex.findMax());
double mean = ex.computeMean();
System.out.println("\nMean score: " + mean);
System.out.println("\nStandard deviation: " +
ex.computeStandDev(mean));
}
}
Copyright © 2003 Pearson Education, Inc.
Slide 121
5.3 Operations on whole arrays
Array assignment
1. Effect of declaration:
y
int[ ] y = new int[5];
y[0]
y[1]
?
?
x[0]
x[1]
?
?
y[2]
y[3]
?
?
Array y
3. Effect of assignment:
y[4]
?
x = y;
2. Effect of declaration:
int[ ] x = new int[5];
x
x[2]
x[3]
?
?
Old array x
x[4]
?
Copying arrays
We can copy some or all the elements of an array to another array
containing the same type of elements by using the following Java
method:
System.arraycopy (sourceArray, sourcePosition,
destinationArray, destinationPosition, count);
Interpretation: Copies a number of count elements from the array
sourceArray, starting at the position sourcePosition to the array
destinationArray starting at the position destinationPosition.
Example: System.arraycopy (y, 0, x, 2, 3);
Copyright © 2003 Pearson Education, Inc.
Slide 122
Arrays as method arguments
/* postcondition: returns true if both array arguments have same
array
* length and values
parameters
arguments
*/
public static boolean equalArray(int[ ] a, int[ ] b) {
// Check for unequal lengths.
if (a.length != b.length)
return false;
// Return false if any pair of elements a[i], b[i] doesn't match.
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
} // end for
// All pairs matched.
return true;
}
array
array
arguments
arguments
Example of call: if (IntArray.equalArray( x, y))
System.out.println(“Arrays have the same values”);
Copyright © 2003 Pearson Education, Inc.
Slide 123
Returning an array as a result
/* Returns a reference to an array that contains the sum of
* corresponding pairs of elements of its array arguments.
* The first element in the result array is a[0] + b[0],
* the second element is a[1] + b[1], ... .
*/
result is
] array
public static int[int[
] addArray(int[
] a, int[ ] b) {
int[ ] c = new int[Math.min(a.length, b.length)]; // array c will store the sum
for (int i = 0; i < c.length; i++)
c[i] = a[i] + b[i];
return c;
// return the array containing the sum
}
Example of call:
int[ ] z = addArray (x, y); // where x, y are arrays of integers
z[i] = x[i] + y[i]
Copyright © 2003 Pearson Education, Inc.
Slide 124
5.4 Searching and sorting an array
Algorithm:
1. for each array element
1.1. if the current element matches the target
1.1.1. return the index of the current element
2. return -1to signal that target was not found
/* Part of class IntArray in package psJava.
* Searches for the first element of the array x that matches the target.
* Returns the index of the first occurrence, or -1 if target is not found.
*/
public static int search(int[ ] x, int target) {
for (int i = 0; i < x.length; i++)
if (x[i] == target)
return i;
//index of target is returned
// All elements tested without success
return -1;
}
Example of call:
argument types are never given
explicitly in a method call
index = IntArray.search(scores, s);
if (index > -1)
System.out.println(“Found a score of “ + s + “at position” + index);
else System.out.println(“Nobody got a score of “ + s);
Copyright © 2003 Pearson Education, Inc.
Slide 125
Sorting algorithms: Selection Sort
fill
pMin




find min exchange
find min exchange
find min no exchg.
find min exchange
83
25
25
25
25
25
25
25
69
69
fill
69
51
51
51
51
51
51
51
pMin
51
69
69
69
69
69
25
83
83
83
83
83
fill
83
78
78
78
78
78
78
78
pMin
78
83
fill
pMin
Note: at any moment, the subarray shown in yellow, from position 0 to position fill -1
(where fill-1 >= 0) is sorted in proper order.
Algorithm
1. for each index fill taking values from the first position to the
next to last position
1.1. find the index pMin of the smallest element in the subarray
starting at fill
1.2. exchange the element at index fill with the one at
index pMin
Copyright © 2003 Pearson Education, Inc.
Slide 126
Selection sort
// Sorts the data in its array argument in increasing order by selection sort
public static void selectSort(int[ ] x) {
int posMin;
// index of the next smallest element
int temp;
// temporary value for exchange
for (int fill = 0; fill < x.length-1; fill++) {
// invariant: elements in x[0] thru x[fill-1] are sorted and fill < x.length
// Find index of smallest element in subarray starting at position fill
posMin = findPosMin(x, fill);
// Exchange elements at positions fill and posMin
temp = x[fill];
x[fill] = x[posMin];
x[posMin] = temp;
}
}
public static int findPosMin(int[ ] x, int fill) {
int posMinSoFar = fill;
start search for
for (int i = fill + 1; i < x.length; i++)
smallest at fill
if (x[i] < x[posMinSoFar])
posMinSoFar = i;
return posMinSoFar;
}
Copyright © 2003 Pearson Education, Inc.
Slide 127
Find the Median value in an array of integers
Algorithm:
1. create a copy of the array
2. sort the copy of the array
3. if (even number of elements)
3.1. return the average of the two middlemost
elements rounded to the closest integer
else
3.2. return the middle element
// Part of class IntArray in package psJava.
// Returns the median value in its array argument.
// Array argument is not changed.
public static int findMedian(int[ ] x) {
// Create a copy of array x.
int[ ] copyX = new int[x.length];
System.arraycopy(x, 0, copyX, 0, x.length);
selectSort(copyX);
// Sort array copyX
// Return the median value of the array
if (x.length % 2 == 0)
// even number of elements
return round((copyX[x.length /2 -1] + copyX[x.length/2]) / 2.0);
else // odd number of elements
Average
return copyX[(x.length -1) / 2];
of 2 middle
}
elements
Copyright © 2003 Pearson Education, Inc.
Slide 128
Another sorting algorithm: Bubble Sort
first pass
...
second pass
last pass
83
69
69
69
69
69
51
51
25
69
83
51
51
51
51
69
25
51
51
51
83
25
25
25
25
69
25
25
25
83
78
78
78
78
78
78
78
78
78
83
83
83
83
83
...
69
Note: The most recently exchanged values are shown in yellow. An exchange happens
only when two consecutive elements are out of order.
Approach

perform a “pass” as follows:
compare all pairs of consecutive
elements x[i] and x[i+1]
 if x[i]> x[i+1] then exchange
their values


keep doing passes until a
complete pass is done without
any exchange
Copyright © 2003 Pearson Education, Inc.
Algorithm
1. do
2. start a pass: exchangeFlag = false
3. for all pairs of consecutive elements
4. if (x[i] > x[i+1])
5. exchange values of x[i], x[i+1]
6. exchangeFlag = true
while (an exchange was made in this pass)
test condition
after a pass
Slide 129
Bubble Sort
// Sorts the data in its array argument in increasing order by bubble sort
public static void bubbleSort(int[ ] x) {
boolean exchangeFlag;
// boolean flag used for loop control
int temp;
// temporary value for exchange
// Loop for repeating passes
do {
exchangeFlag = false;
// no exchange occurred in this pass yet
// Loop for performing a “pass”
for (int i = 0; i< x.length - 2; i++) {
if (x[i] > x[i+1]) {
// values are out of order ?
temp = x[fill];
x[fill] = x[posMin];
x[posMin] = temp;
// exchange
exchangeFlag = true;
// an exchange has occurred
}
} // end for
} while (exchangeFlag); // repeat if an exchange was made in this pass
} // end bubbleSort
Copyright © 2003 Pearson Education, Inc.
do {
...
} while (condition) ;
Slide 130
5.5 Arrays of objects
Array of strings
String[ ] names = {"Sally", "Jim", "Jane", "Jane"};
names
names[0] names[1] names[2] names[3]
Sally
Copyright © 2003 Pearson Education, Inc.
Jim
Jane
Jane
Slide 131
Menus
A menu is a list of choices. We can display a menu dialog
window using method showOptionDialog() (class swing.JOptionPane)
or method readChoice() (class psJava.KeyIn).
String[ ] coffeeChoices = {"Regular", "Decaf", "Expresso", "Latte"};
int coffeeKind = KeyIn.readChoice("Select a coffee", coffeeChoices);
coffeeKind
is 0
coffeeKind
is 3
String[ ] coffeeChoices = {"Regular", "Decaf", "Expresso", "Latte"};
int coffeeKind = JOptionPane.showOptionDialog(null, "Select a coffee",
"Menu",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null,
coffeeChoices, coffeeChoices[0]);
Copyright © 2003 Pearson Education, Inc.
Slide 132
Command line arguments
Using the JDK, the statement
java MyApplication this is way cool;
calls the main method for class MyApplication. It passes the 4 items listed after
MyApplication as an argument (array of strings) to the main method parameter
String[ ] args:
public void static main(String[ ] args) {
Notice that quotes are not required around the strings “this”, “is”, etc. Inside
method main(), args[0] is “this”, args[1] is “is”, etc. Because strings can be
converted to any primitive type, you can use command line arguments to pass
other kinds of information to an application. Programmers sometimes use this
technique to pass the name of a data file to an application.
Copyright © 2003 Pearson Education, Inc.
Slide 133
Processing an array of Employee objects
The line
Employee[ ] employees = new Employee[5];
declares an array employees that can reference 5 Employee objects. Initially,
all references are null.
The statements below define the first 3 elements of this array (subscripts 0, 1,
2). Elements 3 and 4 are still null.
employees[0] = new Employee(“Jane”, 40, 15.50);
employees[1] = new Employee(“Sally”, 20, 10.00);
employees[2] = new Employee(“Jim”, 40, 14.25);
The for loop below stores the sum of all employee salaries in payroll:
payroll = 0;
for (int i = 0; i < 3; i++)
payroll += (employees[i].getHours() * employees[i].getRate());
Copyright © 2003 Pearson Education, Inc.
Slide 134