Review

245
2005 Pearson Education, Inc. All rights rese 1 Revie w Introduction

description

Review. Introduction. 1.2 What Is a Computer?. Computer Performs computations and makes logical decisions Millions / billions times faster than human beings Hardware: physical devices of computer system Computer programs Sets of instructions for which computer processes data - PowerPoint PPT Presentation

Transcript of Review

Page 1: Review

2005 Pearson Education, Inc. All rights reserved.

1

Review

Review

Introduction

Page 2: Review

2005 Pearson Education, Inc. All rights reserved.

2

1.2 What Is a Computer?

• Computer – Performs computations and makes logical decisions

– Millions / billions times faster than human beings

– Hardware: physical devices of computer system

• Computer programs– Sets of instructions for which computer processes data

– Software: programs that run on computers

Page 3: Review

2005 Pearson Education, Inc. All rights reserved.

3

1.3 Computer Organization

Peripherals

Page 4: Review

2005 Pearson Education, Inc. All rights reserved.

4

1.7 Machine Languages, Assembly Languages and High-Level Languages

• Machine language– “Natural language” of computer component

– Machine dependent

• Assembly language– English-like abbreviations represent computer operations

– Translator programs convert to machine language

• High-level language– Allows for writing more “English-like” instructions

• Contains commonly used mathematical operations

– Compiler converts to machine language

• Interpreter– Execute high-level language programs without compilation

Page 5: Review

2005 Pearson Education, Inc. All rights reserved.

5

1.9 History of Java

• Objects– Reusable software components that model real-world items

• Java– Originally for intelligent consumer-electronic devices

– Then used for creating Web pages with dynamic content

– Now also used to:• Develop large-scale enterprise applications

• Enhance WWW server functionality

• Provide applications for consumer devices (cell phones, etc.)

Page 6: Review

2005 Pearson Education, Inc. All rights reserved.

6

1.10 Java Class Libraries

• Classes– Include methods that perform tasks

• Return information after task completion

– Used to build Java programs

– A “blueprint” for creating (instantiating) objects

• Java provides class libraries– Known as Java APIs (Application Programming

Interfaces)

Page 7: Review

2005 Pearson Education, Inc. All rights reserved.

7

Fig. 1.1 | Typical Java development environment.

Page 8: Review

2005 Pearson Education, Inc. All rights reserved.

8

1.13 Typical Java Development Environment (Shell Window)

Page 9: Review

2005 Pearson Education, Inc. All rights reserved.

9

1.13 Typical Java Development Environment (IDE)

Page 10: Review

2005 Pearson Education, Inc. All rights reserved.

10

Review

Review

Operators (ch2)

Page 11: Review

2005 Pearson Education, Inc. All rights reserved.

11

Fig. 2.11 | Arithmetic operators.

Java operation

Arithmetic operator

Algebraic expression

Java expression

Addition + f + 7 f + 7

Subtraction – p – c p - c

Multiplication * Bm b * m

Division / x / y or or x ÷ y

x / y

– Integer division truncates remainder

7 / 5 evaluates to 1

– Remainder operator % returns the remainder

7 % 5 evaluates to 2

Page 12: Review

2005 Pearson Education, Inc. All rights reserved.

12

2.7 Arithmetic (Cont.)

• Operator precedence – Some arithmetic operators act before others (i.e.,

multiplication before addition)• Use parenthesis when needed

– Example: Find the average of three variables a, b and c• Do not use: a + b + c / 3

• Use: ( a + b + c ) / 3

Page 13: Review

2005 Pearson Education, Inc. All rights reserved.

13

Fig. 2.12 | Precedence of arithmetic operators.

Operator(s) Operation(s) Order of evaluation (precedence)

*

/

%

Multiplication

Division

Remainder

Evaluated first. If there are several operators of this type, they are evaluated from left to right.

+

-

Addition

Subtraction

Evaluated next. If there are several operators of this type, they are evaluated from left to right.

– Example: Find the average of three variables a, b and c• Do not use: a + b + c / 3

• Use: ( a + b + c ) / 3

– Use parentheses !!!

Page 14: Review

2005 Pearson Education, Inc. All rights reserved.

14

2.8 Decision Making: Equality and Relational Operators

• Condition– Expression can be either true or false

• if statement– Simple version in this section, more detail later

– If a condition is true, then the body of the if statement executed

– Control always resumes after the if statement

– Conditions in if statements can be formed using equality or relational operators (next slide)

Page 15: Review

2005 Pearson Education, Inc. All rights reserved.

15

Figure 2.14 Decision Making: Equality and Relational Operators

Standard algebraic equality or relational operator

Java equality or relational operator

Sample Java condition

Meaning of Java condition

Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > x > y x is greater than y < x < y x is less than y >= x >= y x is greater than or equal to y ≤ <= x <= y x is less than or equal to y

Page 16: Review

2005 Pearson Education, Inc. All rights reserved.

16

Fig. 2.5 | Some common escape sequences.

Escape sequence

Description

\n Newline. Position the screen cursor at the beginning of the next line.

\t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of the

current line—do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.

\\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double-quote character. For example,

System.out.println( "\"in quotes\"" );

displays

"in quotes"

Page 17: Review

2005 Pearson Education, Inc. All rights reserved.

17

2.5 Import Declarations

• Used by compiler to identify and locate classes used in Java programs

• All import declarations must appear before the first class declaration in the file. Placing an import declaration inside a class declaration’s body or after a class declaration is a syntax error.

• Forgetting to include an import declaration for a class used in your program typically results in a compilation error containing a message such as “cannot resolve symbol.”

3 import java.util.Scanner; // program uses class Scanner

Page 18: Review

2005 Pearson Education, Inc. All rights reserved.

18

Notes on Import Declarations

•java.lang is implicitly imported into every program

• Default package– Contains classes compiled in the same directory– Implicitly imported into source code of other files in

directory

• Packages unnecessary if fully-qualified names are used

Page 19: Review

2005 Pearson Education, Inc. All rights reserved.

19

Software Engineering Observation 3.2

• The Java compiler does not require import declarations in a Java source code file if the fully qualified class name is specified every time a class name is used in the source code.

• But most Java programmers consider using fully qualified names to be cumbersome, and instead prefer to use import declarations.

Page 20: Review

2005 Pearson Education, Inc. All rights reserved.

20

Review

Review

Data Types (ch3)

Page 21: Review

2005 Pearson Education, Inc. All rights reserved.

21

Primitive Types vs. Reference Types

• Types in Java– Primitive

• boolean, byte, char, short, int, long, float, double

• The AP exam tests int, double, boolean

– Reference (sometimes called nonprimitive types)• Objects

• Default value of null• Used to invoke an object’s methods

Page 22: Review

2005 Pearson Education, Inc. All rights reserved.

22

Software Engineering Observation 3.4

• A variable’s declared type (e.g., int, double or some object) indicates whether the variable is of a primitive or a reference type.

• If a variable’s type is not one of the eight primitive types, then it is a reference type.

Page 23: Review

2005 Pearson Education, Inc. All rights reserved.

23

Pop quiz – Intro / Operators / data types

AreviewQuizHardwareOperatorsDataTypes.doc

Page 24: Review

2005 Pearson Education, Inc. All rights reserved.

24

Review

Review

Classes and Objects (ch3)

Page 25: Review

2005 Pearson Education, Inc. All rights reserved.

25

3.2 Classes, Objects, Methods and Instance Variables

• Class provides one or more methods

• Method represents task in a program– Describes the mechanisms that actually perform its tasks

– Hides from its user the complex tasks that it performs

– Method call tells method to perform its task

Page 26: Review

2005 Pearson Education, Inc. All rights reserved.

26

3.2 Classes, Objects, Methods and Instance Variables (Cont.)

• Classes contain one or more attributes– Specified by instance variables.

– Carried with the object as it is used

– In other words the variable is part of the object when the object is “instantiated”.

Page 27: Review

2005 Pearson Education, Inc. All rights reserved.

27

3.3 Declaring a Class

• Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the .java file-name extension.

• keyword public is an access modifier

• Class declarations include:– Access modifier

– Keyword class

– Pair of left and right braces

Page 28: Review

2005 Pearson Education, Inc. All rights reserved.

28

Instantiating an Object of a Class

• Java is extensible– We write classes (“blueprints”). If programmers want to

use them in their application, they need to create an object.

– Programmers can create or “instantiate” new objects with a particular class blueprint.

• Just like declaring variables, we need to declare objects in Java

– recall reference data types include objects

• Class instance (object) creation expression– Keyword new

– Then name of object to create and parentheses

Page 29: Review

2005 Pearson Education, Inc. All rights reserved.

29

Method Declaration and Call• Keyword public indicates method is available to

public

• Keyword void indicates no return type

• Access modifier, return type, name of method and parentheses comprise method header

• Calling a method– Object name, then dot separator (.)

– Then method name and parentheses

• Method parameters– Additional information passed to a method, comma separated

– Supplied in the method call with arguments

Page 30: Review

2005 Pearson Education, Inc. All rights reserved.

30

UML Class Diagrams

• UML class diagrams– Top compartment contains name of the class

– Middle compartment contains class’s attributes or instance variables

– Bottom compartment contains class’s operations or methods

• Plus sign indicates public methods

Page 31: Review

2005 Pearson Education, Inc. All rights reserved.

31

3.5 Instance Variables, set Methods and get Methods

• Variables declared in the body of method– Called local variables– Can only be used within that method

• Variables declared in a class declaration– Called fields or instance variables– Each object of the class has a separate instance of

the variable

Page 32: Review

2005 Pearson Education, Inc. All rights reserved.

32

Access Modifiers public and private

• private keyword– Used for most instance variables

– private variables and methods are accessible only to methods of the class in which they are declared

– Declaring instance variables private is known as data hiding (can’t see the variable from an application that uses that object)

• Return type– Indicates item returned by method

– Declared in method header

Page 33: Review

2005 Pearson Education, Inc. All rights reserved.

33

Software Engineering Observation 3.3

• Precede every field and method declaration with an access modifier.

• As a rule of thumb, instance variables should be declared private and methods should be declared public.

Page 34: Review

2005 Pearson Education, Inc. All rights reserved.

34

Set (mutator) and get (accessor) methods

•private instance variables– Cannot be accessed directly by clients of the object

– Use set methods to alter the value – called an mutator or “setter”

– Use get methods to retrieve the value – called an accessor or “getter”

– Why do have mutators and accessors?• So don’t have to declare everything public (a security

violation)

• Allows controlled access. May want the user to input a username and password if the application calls a getter.

Page 35: Review

2005 Pearson Education, Inc. All rights reserved.

35

3.7 Initializing Objects with Constructors

• Constructors– Initialize an object of a class– Java requires a constructor for every class– Java will provide a default no-argument

constructor if none is provided– Called when keyword new is followed by the

class name and parentheses

Page 36: Review

2005 Pearson Education, Inc. All rights reserved.

36

UML Diagram with Constructors

Page 37: Review

2005 Pearson Education, Inc. All rights reserved.

37

Pop quiz1. public class GradeBook2. {3. private String courseName; 4. public GradeBook( String name )5. {6. courseName = name; 7. } 8. public void setCourseName( String name )9. {10. courseName = name; 11. } 12. public String getCourseName()13. {14. return courseName;15. } 16. public void displayMessage()17. {18. System.out.printf( “Grade book for 19. \n%s!\n", getCourseName() );20. } 21. } //end class GradeBook

Questions:1. Identify the access modifier

for the GradeBook class.

2. Identify the name of the instance variable for the GradeBook class

3. Identify the name of the constructor for the GradeBook class

4. Identify the name of an accessor in the GradeBook class

5. Identify the name of a mutator in the GradeBook class

6. Draw a UML diagram for the GradeBook class

Page 38: Review

2005 Pearson Education, Inc. All rights reserved.

38

Review

Review

Control Structures (ch4)

Page 39: Review

2005 Pearson Education, Inc. All rights reserved.

39

4.4  Control Structures (Cont.)

• Selection Statements– if statement

• Single-selection statement

– if…else statement• Double-selection statement

– switch statement• Multiple-selection statement

Page 40: Review

2005 Pearson Education, Inc. All rights reserved.

40

4.4  Control Structures (Cont.)

• Repetition statements– Also known as looping statements

– Repeatedly performs an action while its loop-continuation condition remains true

– while statement• Performs the actions in its body zero or more times

– do…while statement• Performs the actions in its body one or more times

– for statement• Performs the actions in its body zero or more times

Page 41: Review

2005 Pearson Education, Inc. All rights reserved.

41

4.5  if Statements

•if statements (single selection)– Execute an action if the specified condition is true

•if…else statement (double selection)– Executes one action if the specified condition is true or a

different action if the specified condition is false

• Conditional Operator ( ? : )– Compact alternative

Page 42: Review

2005 Pearson Education, Inc. All rights reserved.

42

Good Programming Practice 4.4• Always using braces in an if...else (or other)

statement helps prevent their accidental omission, especially when adding statements to the if-part or the else-part at a later time.

• To avoid omitting one or both of the braces, some programmers type the beginning and ending braces of blocks before typing the individual statements within the braces.

Page 43: Review

2005 Pearson Education, Inc. All rights reserved.

43

4.7  while Repetition Statement

•while statement– Repeats an action while its loop-continuation condition

remains true

– Use a counter variable to count the number of times a loop is iterated

– Or use Sentinel-controlled repetition• Also known as indefinite repetition

• Sentinel value also known as a signal, dummy, flag, termination value

– Uses a merge symbol in its UML activity diagram

Page 44: Review

2005 Pearson Education, Inc. All rights reserved.

44

4.8 Casting• Unary cast operator

– Creates a temporary copy of its operand with a different data type

• example: (double) will create a temporary floating-point copy of its operand

– Converting values to lower types results in a compilation error, unless the programmer explicitly forces the conversion to occur

• Place the desired data type in parentheses before the value

– example: ( int ) 4.5

• Promotion– Converting a value (e.g. int) to another data type (e.g. double)

to perform a calculation

– Values in an expression are promoted to the “highest” type in the expression (a temporary copy of the value is made)

Page 45: Review

2005 Pearson Education, Inc. All rights reserved.

45Fig. 6.5 | Promotions allowed for primitive types.

Type Valid promotions

double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double (but not char) byte short, int, long, float or double (but not char) boolean None (boolean values are not considered to be numbers in Java)

Page 46: Review

2005 Pearson Education, Inc. All rights reserved.

46

4.11  Compound Assignment Operators

•Compound assignment operatorsexample: c = c + 3; can be written as c += 3;

• This statement adds 3 to the value in variable c and stores the result in variable cs

Assignment operator

Sample expression

Explanation Assigns

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 C = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f

%= g %= 9 g = g % 9 3 to g

Page 47: Review

2005 Pearson Education, Inc. All rights reserved.

47

4.12  Increment and Decrement Operators

•Unary increment and decrement operators–Unary increment operator (++) adds one to its operand

–Unary decrement operator (--) subtracts one from its operand

Operator Called Sample expression

Explanation

++ prefix increment ++a Increment a by 1, then use the new value of a in the

expression in which a resides.

++ postfix increment a++ Use the current value of a in the expression in which a resides,

then increment a by 1.

-- prefix decrement --b Decrement b by 1, then use the new value of b in the

expression in which b resides.

-- postfix decrement b-- Use the current value of b in the expression in which b resides,

then decrement b by 1.

Page 48: Review

2005 Pearson Education, Inc. All rights reserved.

48

Review

Review

Control Structures-2 (ch5)

Page 49: Review

2005 Pearson Education, Inc. All rights reserved.

49

Fig. 5.3 | for repetition statement

Page 50: Review

2005 Pearson Education, Inc. All rights reserved.

50

5.3 for Repetition Statement (Cont.)

for ( initialization; loopContinuationCondition; increment )

statement;

can usually be rewritten as:

initialization;while ( loopContinuationCondition )

{ statement; increment;}

Page 51: Review

2005 Pearson Education, Inc. All rights reserved.

51

5.4 Examples Using the for Statement

for ( int i = 1; i <= 100; i++ )

• How would we write the following with a for statement?

– Vary control variable to count 100 times in increments of 1 using a zero based counter

– Vary control variable from 1 to 100 in increments of 1

for ( int i = 0; i < 100; i++ )

– Vary control variable from 7 to 77 in increments of 7

for ( int i = 100; i >= 1; i-- )

– Vary control variable from 100 to 1 in increments of –1

for ( int i = 7; i <= 77; i += 7 )– Vary control variable from 20 to 2 in decrements of 2

for ( int i = 20; i >= 2; i -= 2 )– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20

for ( int i = 2; i <= 20; i += 3 )– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0for ( int i = 99; i >= 0; i -= 11 )

Page 52: Review

2005 Pearson Education, Inc. All rights reserved.

52

5.4 Examples Using the for Statement (Cont.)

• Initialization and increment expression can be comma-separated lists of expressions

for ( int number = 2; number <= 20; total += number, number += 2 )

{

//statements here…;

}

• What does this loop do?

Page 53: Review

2005 Pearson Education, Inc. All rights reserved.

53

5.5 do…while Repetition Statement

•do…while structure– Similar to while structure

– Tests loop-continuation after performing body of loop• i.e., loop body always executes at least once

Page 54: Review

2005 Pearson Education, Inc. All rights reserved.

54

Outline

•DoWhileTest.java

•Line 8

•Lines 10-14

•Program output

1 // Fig. 5.7: DoWhileTest.java

2 // do...while repetition statement.

3

4 public class DoWhileTest

5 {

6 public static void main( String args[] )

7 {

8 int counter = 1; // initialize counter

9

10 do

11 {

12 System.out.printf( "%d ", counter );

13 ++counter;

14 } while ( counter <= 10 ); // end do...while

15

16 System.out.println(); // outputs a newline

17 } // end main

18 } // end class DoWhileTest 1 2 3 4 5 6 7 8 9 10

Declares and initializes control variable counter

Variable counter’s value is displayed before testing counter’s final value

Page 55: Review

2005 Pearson Education, Inc. All rights reserved.

55

5.6 switch Multiple-Selection Statement

•switch statement– Used for multiple selections

Page 56: Review

2005 Pearson Education, Inc. All rights reserved.

56

Switch / case statement example69 public void incrementLetterGradeCounter( int numericGrade ) 70 { 71 // determine which grade was entered 72 switch ( grade / 10 ) 73 { 74 case 9: // grade was between 90 75 case 10: // and 100 76 ++aCount; // increment aCount 77 break; // necessary to exit switch 78 79 case 8: // grade was between 80 and 89 80 ++bCount; // increment bCount 81 break; // exit switch 82

83 case 7: // grade was between 70 and 79

84 ++cCount; // increment cCount

85 break; // exit switch

86

87 case 6: // grade was between 60 and 69

88 ++dCount; // increment dCount

89 break; // exit switch

90

91 default: // grade was less than 60

92 ++fCount; // increment fCount

93 break; // optional; will exit switch anyway

94 } // end switch

95 } // end method incrementLetterGradeCounter

107

Page 57: Review

2005 Pearson Education, Inc. All rights reserved.

57

5.6 switch Multiple-Selection Statement (Cont.)

• Expression in each case– Constant integral expression

• Combination of integer constants that evaluates to a constant integer value

– Character constant• E.g., ‘A’, ‘7’ or ‘$’

– Constant variable• Declared with keyword final

Page 58: Review

2005 Pearson Education, Inc. All rights reserved.

58

5.7 break and continue Statements

•break/continue– Alter flow of control

•break statement – Causes immediate exit from control structure

• Used in while, for, do…while or switch statements

•continue statement – Skips remaining statements in loop body

– Proceeds to next iteration• Used in while, for or do…while statements

Page 59: Review

2005 Pearson Education, Inc. All rights reserved.

59

Software Engineering Observation 5.3

• Some programmers feel that break and continue violate structured programming. Since the same effects are achievable with structured programming techniques, these programmers do not use break or continue.

• Try not to use break or continue in loops

Page 60: Review

2005 Pearson Education, Inc. All rights reserved.

60

5.8 Logical Operators

• Logical operators– Allows for forming more complex conditions

– Combines simple conditions

• Java logical operators– && (conditional AND)

– || (conditional OR)

– & (boolean logical AND)

– | (boolean logical inclusive OR)

– ^ (boolean logical exclusive OR)

– ! (logical NOT)

Page 61: Review

2005 Pearson Education, Inc. All rights reserved.

61

5.8 Logical Operators (Cont.)

• Conditional AND (&&) Operator– Consider the following if statement

if ( (gender == FEMALE) && (age >= 65) )

++seniorFemales;

– Combined condition is true • if and only if both simple conditions are true

– Combined condition is false • if either or both of the simple conditions are false

Page 62: Review

2005 Pearson Education, Inc. All rights reserved.

62

Fig. 5.14 | && (conditional AND) operator truth table.

expression1 expression2 expression1 && expression2 false false False false true False true false False true true True

Page 63: Review

2005 Pearson Education, Inc. All rights reserved.

63

5.8 Logical Operators (Cont.)

• Conditional OR (||) Operator– Consider the following if statement

if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 )

System.out.println( “Student grade is A” );

– Combined condition is true • if either or both of the simple condition are true

– Combined condition is false • if both of the simple conditions are false

Page 64: Review

2005 Pearson Education, Inc. All rights reserved.

64

Fig. 5.15 | || (conditional OR) operator truth table.

expression1 expression2 expression1 || expression2 false false false false true true true false true true true true

Page 65: Review

2005 Pearson Education, Inc. All rights reserved.

65

5.8 Logical Operators (Cont.)

• Boolean Logical AND (&) Operator– Works similar to &&

– Except & always evaluate both operands (no short circuit)

• Boolean Logical OR (|) Operator – Works similar to ||

– Except | always evaluate both operands (no short circuit)

• Can also use & and | for bit-wise manipulations (bit masking)

Page 66: Review

2005 Pearson Education, Inc. All rights reserved.

66

5.8 Logical Operators (Cont.)

• Boolean Logical Exclusive OR (^)– One of its operands is true and the other is false

• Evaluates to true

– Both operands are true or both are false• Evaluates to false

– (!A & B) + (A & !B)

• Logical Negation (!) Operator– Unary operator

Page 67: Review

2005 Pearson Education, Inc. All rights reserved.

67

DeMorgan’s Law

• Logical equivalence

• !(A && B) = !A || !B

• !(A || B) = !A && !B

Page 68: Review

2005 Pearson Education, Inc. All rights reserved.

68

Pop quiz – Control Structures- 1&2

AB\AreviewQuizControlStruct.doc

Page 69: Review

2005 Pearson Education, Inc. All rights reserved.

69

Review

Review

Methods (ch6)

Page 70: Review

2005 Pearson Education, Inc. All rights reserved.

70

6.3  static Methods, static Fields and Class Math

• Applies to the class as a whole instead of a specific object of the class• A method which is declared static can be accessed without first

creating an instance of the class which contains it. – Don’t have to instantiate the object!!!

• While an instance of a class normally gets its own set of instance variables when it is created, there exists only one instantiation of a static variable for all instances of the class.

– If one instance changes the value of a static variable, that change is seen by other instances of the class!!!

• Call a static method by using the method call:ClassName.methodName( arguments )

• Example: All methods of the Math class are static– example: Math.sqrt( 900.0 )

Page 71: Review

2005 Pearson Education, Inc. All rights reserved.

71

6.3  static Methods, static Fields and Class Math (Cont.)

• Constants– Keyword final

– Cannot be changed after initialization

•static fields– Are fields where one copy of the variable is shared among

all objects of the class

•Math.PI and Math.E are final static fields of the Math class

Page 72: Review

2005 Pearson Education, Inc. All rights reserved.

72

Fig. 6.2 | Math class methods. Method Description Example

abs( x ) absolute value of x abs( 23.7 ) is 23.7 abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7

ceil( x ) rounds x to the smallest integer not less than x

ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x in radians) cos( 0.0 ) is 1.0

exp( x ) exponential method ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906

floor( x ) rounds x to the largest integer not greater than x

Floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0 log( Math.E * Math.E ) is 2.0

max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3

min( x, y ) smaller value of x and y min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to the power y (i.e., xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0

sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0.0

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0

tan( x ) trigonometric tangent of x (x in radians) tan( 0.0 ) is 0.0

Page 73: Review

2005 Pearson Education, Inc. All rights reserved.

73

6.3  static Methods, static Fields and Class Math (Cont.)

• Method main– main is declared static so it can be invoked without

creating an object of the class containing main

– Any class can contain a main method• The JVM invokes the main method belonging to the class

specified by the first command-line argument to the java command

Page 74: Review

2005 Pearson Education, Inc. All rights reserved.

74

6.4  Declaring Methods with Multiple Parameters

• Multiple parameters can be declared by specifying a comma-separated list.

– Arguments passed in a method call must be consistent with the number, types and order of the parameters

• Sometimes called formal parameters

Page 75: Review

2005 Pearson Education, Inc. All rights reserved.

75

6.5  Notes on Declaring and Using Methods

• Three ways to call a method:– Use a method name by itself to call another method of the same

class

– Use a variable containing a reference to an object, followed by a dot (.) and the method name to call a method of the referenced object

– Use the class name and a dot (.) to call a static method of a class

•static methods cannot call non-static methods of the same class

Page 76: Review

2005 Pearson Education, Inc. All rights reserved.

76

6.5  Notes on Declaring and Using Methods (Cont.)

• Three ways to return control to the calling statement:

– If method does not return a result:• Program flow reaches the method-ending right brace or

• Program executes the statement return;

– If method does return a result:• Program executes the statement return expression;

– expression is first evaluated and then its value is returned to the caller

Page 77: Review

2005 Pearson Education, Inc. All rights reserved.

77

6.6  Method Call Stack and Activation Records

• Stacks– Last-in, first-out (LIFO) data structures

• Items are pushed (inserted) onto the top• Items are popped (removed) from the top

• Program execution stack– Also known as the method call stack– Return addresses of calling methods are pushed onto this

stack when they call other methods and popped off when control returns to them

– When the last variable referencing a certain object is popped off this stack, that object is no longer accessible by the program it is subject to “garbage collection”

Page 78: Review

2005 Pearson Education, Inc. All rights reserved.

78

6.9  Case Study: Random-Number Generation

• Random-number generation– static method random from class Math

• Returns doubles in the range 0.0 <= x < 1.0

– class Random from package java.util• Can produce pseudorandom boolean, byte, float, double, int, long and Gaussian values

• Is seeded with the current time of day to generate different sequences of numbers each time the program execute

Page 79: Review

2005 Pearson Education, Inc. All rights reserved.

79

6.9.1 Generalized Scaling and Shifting of Random Numbers

• To generate a random number in certain sequence or range

– Use the expressionshiftingValue + differenceBetweenValues * randomNumbers.nextInt( scalingFactor )where:

• shiftingValue is the first number in the desired range of values

• differenceBetweenValues represents the difference between consecutive numbers in the sequence

• scalingFactor specifies how many numbers are in the range

– How would we generate a random even integer between 2 and 10 inclusive?

Page 80: Review

2005 Pearson Education, Inc. All rights reserved.

80

6.9.2 Random-Number Repeatability for Testing and Debugging

• To get a Random object to generate the same sequence of random numbers every time the program executes, seed it with a certain value

– When creating the Random object:Random randomNumbers =

new Random( seedValue );

– Use the setSeed method:randomNumbers.setSeed( seedValue );

– seedValue should be an argument of type long

Page 81: Review

2005 Pearson Education, Inc. All rights reserved.

81

6.10  Case Study: A Game of Chance (Introducing Enumerations)

• Enumerations– Programmer-declared types consisting of sets of constants– enum keyword– A type name (e.g. Status)– Enumeration constants (e.g. WON, LOST and CONTINUE)– Use only uppercase letters in the names of constants. This

reminds the programmer that enumeration constants are not variables.

– Using enumeration constants (like Status.WON, Status.LOST and Status.CONTINUE) rather than literal integer values (such as 0, 1 and 2) make programs easier to read and maintain.

Page 82: Review

2005 Pearson Education, Inc. All rights reserved.

82

6.11  Scope of Declarations

• Basic scope rules– Scope of a parameter declaration is the body of the method

in which appears

– Scope of a local-variable declaration is from the point of declaration to the end of that block

– Scope of a local-variable declaration in the initialization section of a for header is the rest of the for header and the body of the for statement

– Scope of a method or field (instance variable) of a class is the entire body of the class

Page 83: Review

2005 Pearson Education, Inc. All rights reserved.

83

6.11  Scope of Declarations (Cont.)

• Shadowing– A field (instance variable) is shadowed (or hidden) if a local

variable or parameter has the same name as the field• This lasts until the local variable or parameter goes out of

scope

Page 84: Review

2005 Pearson Education, Inc. All rights reserved.

84

6.12  Method Overloading

• Method overloading– Multiple methods with the same name, but different types,

number or order of parameters in their parameter lists

– Compiler decides which method is being called by matching the method call’s argument list to one of the overloaded methods’ parameter lists

• A method’s name and number, type and order of its parameters form its signature

– Differences in return type are irrelevant in method overloading

• Overloaded methods can have different return types

• Methods with different return types but the same signature cause a compilation error

Page 85: Review

2005 Pearson Education, Inc. All rights reserved.

85

Common Programming Error 6.11

• Declaring overloaded methods with identical parameter lists is a compilation error regardless of whether the return types are different.

• What type of method has an identical parameter list?

Page 86: Review

2005 Pearson Education, Inc. All rights reserved.

86

Review

Review

Arrays and ArrayLists (ch7)

Page 87: Review

2005 Pearson Education, Inc. All rights reserved.

87

7.1 and 7.2 Introduction

• Arrays– Data structures

– Related data items of same type

– Remain same size once created

– Index / subscript• Position number in square brackets

• Must be positive integer or integer expression (not long, double, etc)

• First element has index zero

– “length” method accesses array’s length

Page 88: Review

2005 Pearson Education, Inc. All rights reserved.

88

Fig. 7.1 | A 12-element array.

Page 89: Review

2005 Pearson Education, Inc. All rights reserved.

89

7.3 Declaring and Creating Arrays

• Declaring and Creating arrays– Arrays are objects that occupy memory

– Created dynamically with keyword new int c[] = new int[ 12 ];

– Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array

• We can create arrays of objects too

String b[] = new String[ 100 ];

Page 90: Review

2005 Pearson Education, Inc. All rights reserved.

90

7.4 Examples Using Arrays (Cont.)

• Using an array initializer– Use initializer list

• Items enclosed in braces ({})

• Items in list separated by commas

int n[] = { 10, 20, 30, 40, 50 };

– Creates a five-element array

– Index values of 0, 1, 2, 3, 4

– Do not need keyword new

Page 91: Review

2005 Pearson Education, Inc. All rights reserved.

91

7.6 Enhanced for Statement

• Enhanced for statement– New feature of J2SE 5.0 (Part of the AP exam!!!)

– Allows iterates through elements of an array or a collection without using a counter

– Syntax

for ( parameter : arrayName )

Statement

– Next slides show equivalent for header usage

Page 92: Review

2005 Pearson Education, Inc. All rights reserved.

92

Outline

•EnhancedForTest.java

1 // Fig. 7.12: EnhancedForTest.java

2 // Using enhanced for statement to total integers in an array.

3

4 public class EnhancedForTest

5 {

6 public static void main( String args[] )

7 {

8 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };

9 int total = 0;

10

11 // add each element's value to total

12 for ( int number : array )

13 total += number;

14

15 System.out.printf( "Total of array elements: %d\n", total );

16 } // end main

17 } // end class EnhancedForTest Total of array elements: 849

For each iteration, assign the next element of array to int variable number, then add it to total

Page 93: Review

2005 Pearson Education, Inc. All rights reserved.

93

7.6 Enhanced for Statement (Cont.)

• Lines 12-13 are equivalent tofor ( int counter = 0; counter < array.length; counter++ )

total += array[ counter ];

• Usage– Can access array elements

– Cannot modify array elements

– Cannot access the counter indicating the index

Page 94: Review

2005 Pearson Education, Inc. All rights reserved.

94

7.7 Passing Arrays to Methods

• To pass array argument to a method– Specify array name without brackets

• Array hourlyTemperatures is declared as

int hourlyTemperatures = new int[ 24 ];

• The method call

modifyArray( hourlyTemperatures );

• Passes array hourlyTemperatures to method modifyArray

Page 95: Review

2005 Pearson Education, Inc. All rights reserved.

95

7.7 Passing Arrays to Methods (Cont.)

• Notes on passing arguments to methods– Two ways to pass arguments to methods

• Pass-by-value– Copy of argument’s value is passed to called method– In Java, every primitive is pass-by-value

• Pass-by-reference– Caller gives called method direct access to caller’s data– Called method can manipulate this data– Improved performance over pass-by-value– In Java, every object is pass-by-reference

• In Java, arrays are objects

• Therefore, arrays are passed to methods by reference

Page 96: Review

2005 Pearson Education, Inc. All rights reserved.

96

7.9 Multidimensional Arrays

• Multidimensional arrays– Tables with rows and columns

• Two-dimensional array

• m-by-n array

Page 97: Review

2005 Pearson Education, Inc. All rights reserved.

97

Fig. 7.16 | Two-dimensional array with three rows and four columns.

Page 98: Review

2005 Pearson Education, Inc. All rights reserved.

98

7.9 Multidimensional Arrays (Cont.)

• Arrays of one-dimensional array– Declaring two-dimensional array b[2][2]

int b[][] = { { 1, 2 }, { 3, 4 } };

– 1 and 2 initialize b[0][0] and b[0][1]

– 3 and 4 initialize b[1][0] and b[1][1]

int b[][] = { { 1, 2 }, { 3, 4, 5 } };

– row 0 contains elements 1 and 2

– row 1 contains elements 3, 4 and 5

Page 99: Review

2005 Pearson Education, Inc. All rights reserved.

99

7.9 Multidimensional Arrays (Cont.)

• Two-dimensional arrays with rows of different lengths

– Lengths of rows in array are not required to be the same• E.g., int b[][] = { { 1, 2 }, { 3, 4, 5 } };

Page 100: Review

2005 Pearson Education, Inc. All rights reserved.

100

7.9 Multidimensional Arrays (Cont.)

• Creating two-dimensional arrays with array-creation expressions

– Can be created dynamically• 3-by-4 array

int b[][]; b = new int[ 3 ][ 4 ];

• Rows can have different number of columns int b[][];

b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1

Page 101: Review

2005 Pearson Education, Inc. All rights reserved.

101

Outline

•InitArray.java

•(1 of 2)

•Line 9

•Line 10

1 // Fig. 7.17: InitArray.java

2 // Initializing two-dimensional arrays.

3

4 public class InitArray

5 {

6 // create and output two-dimensional arrays

7 public static void main( String args[] )

8 {

9 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; 10 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };

11

12 System.out.println( "Values in array1 by row are" );

13 outputArray( array1 ); // displays array1 by row

14

15 System.out.println( "\nValues in array2 by row are" );

16 outputArray( array2 ); // displays array2 by row

17 } // end main

18

Use nested array initializers to initialize array1

Use nested array initializers of different lengths to

initialize array2

Page 102: Review

2005 Pearson Education, Inc. All rights reserved.

102

Outline

•InitArray.java

•(2 of 2)

•Line 26

•Line 27

•Program output

19 // output rows and columns of a two-dimensional array

20 public static void outputArray( int array[][] )

21 {

22 // loop through array's rows

23 for ( int row = 0; row < array.length; row++ )

24 {

25 // loop through columns of current row

26 for ( int column = 0; column < array[ row ].length; column++ )

27 System.out.printf( "%d ", array[ row ][ column ] );

28

29 System.out.println(); // start new line of output

30 } // end outer for

31 } // end method outputArray

32 } // end class InitArray Values in array1 by row are 1 2 3 4 5 6 Values in array2 by row are 1 2 3 4 5 6

array[row].length returns number of columns associated with row subscript

Use double-bracket notation to access two-dimensional array values

Page 103: Review

2005 Pearson Education, Inc. All rights reserved.

103

7.9 Multidimensional Arrays (Cont.)

• Common multidimensional-array manipulations performed with for statements

– Many common array manipulations use for statements

E.g.,

for ( int column = 0; column < a[ 2 ].length; column++ ) a[ 2 ][ column ] = 0;

Page 104: Review

2005 Pearson Education, Inc. All rights reserved.

104

ArrayList

• Guaranteed to be on the AP exam!!• Similar to arrays but more powerful• ArrayLists can grow and shrink as needed• ArrayList class provides methods for common

tasks such as inserting and removing elements

• Stores Objects– Can’t store primitive data types directly– For example, if need to store integers use class Integer(7)

Page 105: Review

2005 Pearson Education, Inc. All rights reserved.

105

ArrayList (cont)• ArrayList<object> myArrayList = new ArrayList<object>();

• Some of the methods (there are more…)– add(int index, Object element)

          Inserts the specified element at the specified position in this list. – add(Object o)

          Appends the specified element to the end of this list. – get(int index)

          Returns the element at the specified position in this list. – set(int index, Object element)

          Replaces the element at the specified position in this list with the specified element.

– clear()           Removes all of the elements from this list.

– isEmpty()           Tests if this list has no elements.

– remove(int index)           Removes the element at the specified position in this list.

– size()           Returns the number of elements in this list.

Page 106: Review

2005 Pearson Education, Inc. All rights reserved.

106

ArrayList (cont) 1 public class BankAccount

2 {

3 private int accountNumber;

4 private double balance;

5

6 public BankAccount (int anAccountNumber)

7 {

8 accountNumber = anAccountNumber;

9 balance = 0;

10 }

11 public BankAccount (int anAccountNumber, double initialBalance)

12 {

13 accountNumber = anAccountNumber;

14 balance = initialBalance;

15 }

16 public int getAccountNumber()

17 {

18 return accountNumber;

19 }

20 public void deposit (double amount)

21 {

22 double newBalance = balance + amount;

23 balance = newBalance;

24 }

25 public void withdraw (double amount)

26 {

27 double newBalance = balance – amount;

28 balance = newBalance;

29 }

30 public double getBalance()

31 {

32 return balance;

33 }

34 }

Page 107: Review

2005 Pearson Education, Inc. All rights reserved.

107

ArrayList (cont) 1 import java.util.ArrayList;

2

3 public class ArrayListTester

4 {

5 public static void main(String[] args)

6 {

7 ArrayList<BankAccount> accounts

8 = new ArrayList<BankAccount>();

9 accounts.add(new BankAccount(1001));

10 accounts.add(new BankAccount(1015));

11 accounts.add(new BankAccount(1729));

12 accounts.add(1, new BankAccount(1008)); // places where??

13 accounts.remove(0);

14

15 System.out.println(“size=” + accounts.size());

16 BankAccount first = accounts.get(0);

17 System.out.println(“first account number= “

18 + first.getAccountNumber());

19 BankAccount last = accounts.get(accounts.size() – 1);

20 System.out.println(“last account number=”

21 + last.getAccountNumber());

22 } // end main

23 } // end class ArrayListTester

Page 108: Review

2005 Pearson Education, Inc. All rights reserved.

108

Pop quiz – Methods, Arrays and ArrayLists

AreviewQuizMethodArrayArraylist.doc

Page 109: Review

2005 Pearson Education, Inc. All rights reserved.

109

Review

Review

Strings and Characters (ch29)

Page 110: Review

2005 Pearson Education, Inc. All rights reserved.

110

29.1 Introduction

• String and character processing– Class java.lang.String

– Class java.lang.Character

– Class java.util.StringTokenizer

Page 111: Review

2005 Pearson Education, Inc. All rights reserved.

111

29.2 Fundamentals of Characters and Strings

• Characters– Every Java source programs consists of a sequence of characters

(building block of Java source programs)– Character literals: integer value of char in single quotes– Represented by Unicode character set (2 bytes) – ASCII is subset

of the Unicode set

• String– Series of characters treated as single unit– May include letters, digits, special characters.– Object of class String – stored in memory as objects – String literals: sequence of chars in double quotes– Many constructors (check out the api)

Page 112: Review

2005 Pearson Education, Inc. All rights reserved.

112

Software Engineering Obervation 29.1

•String objects are immutable—their character contents cannot be changed after they are created, because class String does not provide any methods that allow the contents of a String object to be modified.

Page 113: Review

2005 Pearson Education, Inc. All rights reserved.

113

29.3.2 String Methods length, charAt and getChars

• Method length– Determine the length of a String

• Like arrays, Strings always “know” their size

• Unlike arrays, Strings do not have length instance variable (have length() method. Works similar to arrays)

• Method charAt– Get character at specific location in String

• Method getChars– Get entire set of characters in String

Page 114: Review

2005 Pearson Education, Inc. All rights reserved.

114

29.3.3 Comparing Strings

• Comparing String objects– Method equals

• compares 2 Strings char by char• NOTE: CANNOT USE “==“ THIS WILL TEST IF POINTING TO THE SAME OBJECT!!!

– Method equalsIgnoreCase– Method compareTo

• If 0 then the 2 Strings are equal • If < or > 0 then represents offset in ASCII table

– Method regionMatches• Compares portions of 2 Strings

Page 115: Review

2005 Pearson Education, Inc. All rights reserved.

115

29.3.5 Extracting Substrings from Strings

• Create Strings from other Strings– Method substring

Page 116: Review

2005 Pearson Education, Inc. All rights reserved.

116

29.3.6 Concatenating Strings

• Method concat– Concatenate two String objects

– (note strings don’t change – create a new one)

– (+ sign is a shortcut for concat)

• Part of the AP exam!!

Page 117: Review

2005 Pearson Education, Inc. All rights reserved.

117

29.3.8 String Method valueOf

•String provides static class methods– Method valueOf

• Returns String representation of object, data, etc.

Page 118: Review

2005 Pearson Education, Inc. All rights reserved.

118

Pop quiz – Strings and CharactersAssume the following String arrays:

String word1[] = { “The ", “A ", “One ", “Some ", “Any " };

String word2[] = { "boy", "girl", "dog", "town", "car" };

String word3[] = { " drove", " jumped", " ran", " walked" };

String word4[] = {" away", " back", " home", " town", " car" };

Write a code segment which constructs and prints out the String:

“Some dog jumped back.” (Cap the S and put in a period)

String popQuizSentence = new String("");

char popQuizSentenceChars[];

popQuizSentence = popQuizSentence.concat(word1[3]).concat(word2[2]).concat(word[1]).concat(word4[1]);

popQuizSentenceChars = popQuizSentence.toCharArray();

for( char character: popQuizSentenceChars)

System.out.print(character);

System.out.printf(".\n");

Page 119: Review

2005 Pearson Education, Inc. All rights reserved.

119

Review

Review

Classes and Objects (ch8)

Page 120: Review

2005 Pearson Education, Inc. All rights reserved.

120

8.1 – 8.2 toString()

• Method in Class java.lang.Object

• Returns a string representation of the object – consisting of the name of the class, the @ character, and the

unsigned hexadecimal representation of the hash code of the object.

– getClass().getName() @ random looking numbers

(where getClass() and getName are also methods in Class java.lang.Object)

• It is recommended that all classes override this method to return useful debugging info

• Can use String.format() embedded in a print statement to format the Strings printed

Page 121: Review

2005 Pearson Education, Inc. All rights reserved.

121

8.4  Referring to the Current Object’s Members with the this Reference

• The this reference– Any object can access a reference to itself with keyword this

– Non-static methods implicitly use this when referring to the object’s instance variables and other methods

• A .java file can contain more than one class– Creates the number of .class files corresponding to the

number of classes

– But only one class in each .java file can be public

Page 122: Review

2005 Pearson Education, Inc. All rights reserved.

122

Outline

•ThisTest.java

•(1 of 2)

1 // Fig. 8.4: ThisTest.java

2 // this used implicitly and explicitly to refer to members of an object.

3

4 public class ThisTest

5 {

6 public static void main( String args[] )

7 {

8 SimpleTime time = new SimpleTime( 15, 30, 19 );

9 System.out.println( time.buildString() );

10 } // end main

11 } // end class ThisTest

12

13 // class SimpleTime demonstrates the "this" reference

14 class SimpleTime

15 {

16 private int myHour; // 0-23

17 private int myMinute; // 0-59

18 private int mySecond; // 0-59

19

20

21

22

23 public SimpleTime( int hour, int minute, int second )

24 {

25 this.myHour = hour; // set "this" object's hour

26 this.myMinute = minute; // set "this" object's minute

27 this.mySecond = second; // set "this" object's second

28 } // end SimpleTime constructor

29

Create new SimpleTime object

Declare instance variables

Using this to access the object’s instance variables

Use of this is actually implied for private variables but makes it more readable (we’ll use it for methods too)

Page 123: Review

2005 Pearson Education, Inc. All rights reserved.

123

8.5  Time Class Case Study: Overloaded Constructors

• Overloaded constructors– Provide multiple constructor definitions with different

signatures

• No-argument constructor– A constructor invoked without arguments

• The this reference can be used to invoke another constructor

– Allowed only as the first statement in a constructor’s body

Page 124: Review

2005 Pearson Education, Inc. All rights reserved.

124

• If this is used in a constructor’s body to call another constructor, it must be the first statement in the constructor.

• A method cannot invoke a constructor directly via this.

Common Programming Error 8.3

Page 125: Review

2005 Pearson Education, Inc. All rights reserved.

125

8.7  Set and Get Methods

• Set methods– Also known as mutator methods

– Assign values to instance variables

– Should validate new values for instance variables• Can return a value to indicate invalid data

• Get methods– Also known as accessor methods or query methods

– Obtain the values of instance variables

– Can control the format of the data it returns

Page 126: Review

2005 Pearson Education, Inc. All rights reserved.

126

8.8  Composition

• Composition– A class can have references to objects of other classes as

members– Sometimes referred to as a has-a relationship– Establishes the design hierarchy and is an importance

concept for inheritance

– Example, establish the composition hierarchy if have classes: door, car, wheel, person, motor

(has-a) (has-a)

Person → car → door

→ wheel

→ motor

Page 127: Review

2005 Pearson Education, Inc. All rights reserved.

127

8.16  Time Class Case Study: Creating Packages

• To declare a reusable class– Declare a public class

– Add a package declaration to the source-code file• must be the very first executable statement in the file• package name should consist of your Internet domain name

in reverse order followed by other names for the package

– example: com.deitel.jhtp6.ch08

– package name is part of the fully qualified class name

• Distinguishes between multiple classes with the same name belonging to different packages

• Prevents name conflict (also called name collision)

– Class name without package name is the simple name

Page 128: Review

2005 Pearson Education, Inc. All rights reserved.

128

Outline

•Time1.java

•(1 of 2)

1 // Fig. 8.18: Time1.java

2 // Time1 class declaration maintains the time in 24-hour format.

3 package com.deitel.jhtp6.ch08;

4

5 public class Time1

6 {

7 private int hour; // 0 - 23

8 private int minute; // 0 - 59

9 private int second; // 0 - 59

10

11 // set a new time value using universal time; perform

12 // validity checks on the data; set invalid values to zero

13 public void setTime( int h, int m, int s )

14 {

15 hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // validate hour

16 minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute

17 second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second

18 } // end method setTime

19

package declaration

Time1 is a public class so it can be used by importers of this package

Page 129: Review

2005 Pearson Education, Inc. All rights reserved.

129

8.16  Time Class Case Study: Creating Packages (Cont.)

– Compile the class so that it is placed in the appropriate package directory structure

• Example: our package should be in the directorycom

deiteljhtp6

ch08

Page 130: Review

2005 Pearson Education, Inc. All rights reserved.

130

8.16  Time Class Case Study: Creating Packages (Cont.)

– Import the reusable class into a program• Single-type-import declaration

– Imports a single class

– Example: import java.util.Random;

• Type-import-on-demand declaration

– Imports all classes in a package

– Example: import java.util.*;

Page 131: Review

2005 Pearson Education, Inc. All rights reserved.

131

Outline

•Time1PackageTest

•.java

• (1 of 2)

1 // Fig. 8.19: Time1PackageTest.java

2 // Time1 object used in an application.

3 import com.deitel.jhtp6.ch08.Time1; // import class Time1

4

5 public class Time1PackageTest

6 {

7 public static void main( String args[] )

8 {

9 // create and initialize a Time1 object

10 Time1 time = new Time1(); // calls Time1 constructor

11

12 // output string representations of the time

13 System.out.print( "The initial universal time is: " );

14 System.out.println( time.toUniversalString() );

15 System.out.print( "The initial standard time is: " );

16 System.out.println( time.toString() );

17 System.out.println(); // output a blank line

18

Single-type import declaration

Refer to the Time1 class by its simple name

Page 132: Review

2005 Pearson Education, Inc. All rights reserved.

132

Pop quiz – Methods and Objects

Text here

Page 133: Review

2005 Pearson Education, Inc. All rights reserved.

133

Review

Review

Inheritance (ch9)

Page 134: Review

2005 Pearson Education, Inc. All rights reserved.

134

9.1 Introduction• Inheritance

– Software reusability • Copying and pasting code from one class to another can spread

errors across multiple source code files. • Independent software vendors develop proprietary code for

sale/license– Available in object-code format– Users derive new classes without accessing ISV proprietary

source code

– Create new class from existing class• Absorb existing class’s data and behaviors• Enhance with new capabilities

– Subclass extends superclass• Subclass

– More specialized group of objects– Behaviors inherited from superclass

• Can customize and add specific behaviors

Page 135: Review

2005 Pearson Education, Inc. All rights reserved.

135

9.1 Introduction (Cont.)

• Class hierarchy definitions– Direct superclass

• Inherited explicitly (one level up hierarchy)

– Indirect superclass• Inherited two or more levels up hierarchy

– Single inheritance• Inherits from one superclass

– Multiple inheritance• Inherits from multiple superclasses

– Java does not support multiple inheritance

Page 136: Review

2005 Pearson Education, Inc. All rights reserved.

136

9.2 Superclasses and subclasses

• Superclasses and subclasses– Object of one class “is an” object of another class

• Example: Rectangle is quadrilateral.

– Class Rectangle inherits from class Quadrilateral

– Quadrilateral: superclass

– Rectangle: subclass

– SUBCLASSES MUST FOLLOW THE IS-A(n) RELATIONSHIP!!!

– Superclass typically represents larger set of objects than subclasses

Page 137: Review

2005 Pearson Education, Inc. All rights reserved.

137

9.2 Superclasses and subclasses (Cont.)• Inheritance hierarchy

– Inheritance relationships: tree-like hierarchy structure

– Each class becomes….• superclass

– Supply members to other classes

• subclass

– Inherit members from other classes

Page 138: Review

2005 Pearson Education, Inc. All rights reserved.

138

Inheritance notes• The common instance variables and methods of all the

classes in the hierarchy are declared in a superclass.

• Methods of a subclass cannot directly access private members of their superclass.

• A subclass can change the state of private superclass instance variables only through non-private methods provided in the superclass and inherited by the subclass (getters and setters).

• Methods of a subclass can override public methods of its superclass; example toString( )

• When a program creates a subclass object, the subclass constructor immediately calls the superclass constructor (explicitly, via super, or implicitly).

Page 139: Review

2005 Pearson Education, Inc. All rights reserved.

139

Protected Access modifier• Recall in public access, the variable or method can be

accessed anywhere in the same package, no package, orany other package.  Anything that is public has wide open access.

• Protected has less access than public.  A member with protected access can be accessed in any class in the same package.  

– You cannot access a protected member in a different package.– Protected is often referred to as package public.

• Protected access is most commonly used when you have instance variables in a super class that you wish to access directly in the sub class.  

– Members in the super class with private acccess could not be accessed directly in the sub class.

– HOWEVER, the prefered way to access instance variables is to use setters and getters.

Page 140: Review

2005 Pearson Education, Inc. All rights reserved.

140

Pop quiz – Inheritance

Text here

Page 141: Review

2005 Pearson Education, Inc. All rights reserved.

141

Review

Review

Polymorphism (ch10)

Page 142: Review

2005 Pearson Education, Inc. All rights reserved.

142

DefinitionsConcrete class

• Provide complete (100%) implementation its methods

Abstract class

• Provides partial (0 to 100%) implementation its methods

Interface

• Provides no (0%) implementation of methods

Page 143: Review

2005 Pearson Education, Inc. All rights reserved.

143

Abstract Classes and Methods• Why abstract classes and methods?

– Sometimes a class that you define represents an abstract concept and therefore should not be instantiated.

– Example: food should not be instantiated, food items such as carrots, apples, etc should be instantiated.

• Abstract classes are superclasses that implement a collection of methods which define common behaviors (much of the class is undefined and unimplemented)

• Many inheritance hierarchies have abstract superclasses occupying the top few levels

• An abstract class can only be subclassed; it cannot be instantiated. It would be extended by other classes which fill in the details with specialized subclasses.

Page 144: Review

2005 Pearson Education, Inc. All rights reserved.

144

Abstract Classes and Methods cont.• In practice, abstract classes usually provide a complete or

partial implementation of at least one method. – If an abstract class contains only abstract method declarations, it

should be implemented as an interface instead.

– Technically, an interface is a completely abstract implementation (more details later…)

• Any class that has an abstract method in it or that does not provide an implementation for any abstract methods declared in its superclasses must be declared as an abstract class

• A class that defines an abstract method, or that inherits an abstract method without overriding it, must be declared abstract

Page 145: Review

2005 Pearson Education, Inc. All rights reserved.

145

10.5.1 Creating Abstract Superclass

• Example

public abstract class Employee

{ …. }

•abstract superclass Employee– earnings is declared abstract

• No implementation can be given for earnings in the Employee abstract class

– An array of Employee variables will store references to subclass objects• earnings method calls from these variables will call the

appropriate version of the earnings method

Page 146: Review

2005 Pearson Education, Inc. All rights reserved.

146

Common Programming Error 10.2

• Failure to implement a superclass’s abstract methods in a subclass is a compilation error unless the subclass is also declared abstract.

Page 147: Review

2005 Pearson Education, Inc. All rights reserved.

147

Interfaces intro

• Interfaces define a protocol of behavior (collection of method definitions and constant values) that can be implemented by any class anywhere in the class hierarchy

• Interfaces never implement methods; instead, classes that implement the interface implement the methods defined by the interface.

• A class can implement many interfaces (as many as it needs to)

• Unrelated classes can implement the same interface.

• An interface is a totally abstract class

Page 148: Review

2005 Pearson Education, Inc. All rights reserved.

148

Interfaces intro cont.

In practice interfaces are useful for:– declaring methods that one or more classes are expected to

implement

– revealing an object's programming interface

• When a class implements an interface, it “agrees” to implement all the methods defined in the interface

• Access privileges: public then any class in any package, no specifier then only to classes identified in the same package (ie. protected)

• An interface may extend zero or more interfaces if it likes, but it cannot extend a class, because then it would inherit functionality, and interfaces cannot have functionality.

Page 149: Review

2005 Pearson Education, Inc. All rights reserved.

149

10.7  Case Study: Creating and Using Interfaces

• Keyword interface

• Classes can implement interfaces– The class must declare each method in the interface using

the same signature or the class must be declared abstract

• Normally declared in their own files with the same names as the interfaces and with the .java file-name extension

Page 150: Review

2005 Pearson Education, Inc. All rights reserved.

150

Common Programming Error 10.6

• Failing to implement any method of an interface in a concrete class that implements the interface results in a syntax error indicating that the class must be declared abstract.

Page 151: Review

2005 Pearson Education, Inc. All rights reserved.

151

Fig. 10.10 | Payable interface hierarchy UML

class diagram.

Page 152: Review

2005 Pearson Education, Inc. All rights reserved.

152

Class hierarchy

• Composition, has-a relationship– A class can have references to objects of other classes as

members

– Establishes the design hierarchy and is an importance concept for inheritance

• Is-a relationship– An object of a subclass can also be treated as an object of

its superclass

– Example: Dog is-a(n) animal, LoudDog is-a Dog, LoudDog is-a(n) animal

Page 153: Review

2005 Pearson Education, Inc. All rights reserved.

153

Polymorphism Defined

• Polymorphism: “having many forms”

• A set of distinct classes share a common interface because they are all derived from the same base class(es).

• Because the derived classes are distinct, their implementations may differ. However, because the derived classes share a common interface, instances of those classes are used in exactly the same way.

Page 154: Review

2005 Pearson Education, Inc. All rights reserved.

154

10.2  Polymorphism Examples

• When a program invokes a method through a superclass variable, the correct subclass version of the method is called, based on the type of the reference stored in the superclass variable

• The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked

• Facilitates adding new classes to a system with minimal modifications to the system’s code

Page 155: Review

2005 Pearson Education, Inc. All rights reserved.

155

10.5.6 Demonstrating Polymorphic Processing, Operator instanceof and Downcasting

• Assigning a superclass variable to a subclass variable (without an explicit cast) is a compilation error.

• Dynamic binding– Also known as late binding

– Calls to overridden methods are resolved at execution time, based on the type of object referenced

•instanceof operator– Determines whether an object is an instance of a certain type

– Useful but not tested in AP exam

Page 156: Review

2005 Pearson Education, Inc. All rights reserved.

156

10.5.7 Summary of the Allowed Assignments Between Superclass and Subclass Variables

• Assigning a superclass reference to a superclass variable is straightforward

• Assigning a subclass reference to a subclass variable is straightforward

• Assigning a subclass reference to a superclass variable is safe because of the is-a relationship

– Referring to subclass-only members through superclass variables is a compilation error

• Assigning a superclass reference to a subclass variable is a compilation error

– Downcasting can get around this error

Page 157: Review

2005 Pearson Education, Inc. All rights reserved.

157

Old MacDonald Class Hierarchy and Polymorphism Example

<<interface>>

Animal

Chick

NamedCow

Chick

Pig Pig

a[0]

a[1]

a[2]

Farm

Old MacDonald

NamedCow

Cow

getType()

getSound()

cow goes moogetType()

getSound()

+ getType()

+ getSound()

+ getType()

+ getSound()

+ getType()

+ getSound()

The cow is known as Elsie

chick goes cheep

pig goes oink

NamedCow

+ getType()

+ getSound()

+ getType()

+ getSound()

+ getType()

+ getSound()

Chick

Pig

+ getName()+ getName()

Note, need to downcast when calling getName since NamedCow is-a Cow

Page 158: Review

2005 Pearson Education, Inc. All rights reserved.

158

Example

public class Animal{

public int A(){ return A( ) + 3; }public int B( ){ return 7; }

}

public class Dog extends Animal{

public int A(){ return super.B( ) + 2; }public int B( ){ return super.A( ) + 5; }public int C( ){ return super.A( ); }

}

Because Dog extends Animal, it is legal to cast the super class to the subclass (is-a relationships allow this)

Example: Animal x = new Dog( );

What is printed as a result of the call System.out.print (x.B( ))?

7 + 2 + 3 + 5 = 17

Page 159: Review

2005 Pearson Education, Inc. All rights reserved.

159

Polymorphism examplespublic class Animal{ public int A() { return A() + 3; } public int B() { return 7; } public int C() { return 14; } public int D() { return 8; } public int E() { return C() + 8; }}//end class Animal

public class Dog extends Animal{ public int A() { return super.B( ) + 2; } public int B( ) { return super.A( ) + 5; } public int C( ) { return super.A( ); } public int D( ) { return super.A( ); }}//end class Dog

public class Puppy extends Dog{

public int A(){ return super.B( ) + 2; }public int B( ){ return super.E( ) + 5; }public int C( ){ return super.A( ); }public int D( ){ return E() + 4; }

}//end class Puppy

1. Draw the inheritance hierarchy diagram for Animal, Dog, Puppy2. What is printed as a result of the following declaration and print statements?a. Dog myPuppy4 = new Puppy(); System.out.println(myPuppy4.D());b. Animal myPuppy1 = new Puppy(); System.out.println(myPuppy1.B()); c. Animal myPuppy3 = new Puppy(); System.out.println(myPuppy3.C());

d. Animal myPuppy2 = new Puppy(); System.out.println(myPuppy2.D());

e. Animal myPuppy5 = new Animal(); System.out.println(myPuppy5.A());

Page 160: Review

2005 Pearson Education, Inc. All rights reserved.

160

Iterators• Used to traverse an ArrayList

• Useful if removing elements from the list

• Check out the Sun Java API for method details

public void removeElement(String word)

{

for ( int i = 0; i < list.size(); i++) {

String s = list.get(i);

if (s.equals(word))

{

list.remove(i);

i--;

}

}

}

public void removeElement(String word)

{

Iterator it = list.iterator();

while (it.hasNext()){

String s = it.next();

if (s.equals(word)){

it.remove();

}

}

}

Page 161: Review

2005 Pearson Education, Inc. All rights reserved.

161

Pop quiz – Polymorphism

Text here

Page 162: Review

2005 Pearson Education, Inc. All rights reserved.

162

Review

Review

Recursion (ch15)

Page 163: Review

2005 Pearson Education, Inc. All rights reserved.

163

15.1 Introduction

• Earlier programs structured as methods that call one another in a hierarchical manner

• Recursive methods– Call themselves

– Useful for some problems to define a method to call itself

– Can be called directly or indirectly through another method

Page 164: Review

2005 Pearson Education, Inc. All rights reserved.

164

15.2 Recursion Concepts• Recursive problem-solving elements

– Base case• Recursive method capable of solving only simplest case—the base

case

• If method is called with base case, method returns result

– If method is called with more complex problem, problem divided into two pieces—the base and the recursive step

– Recursive call/recursion step• Must resemble original problem but be slightly simpler or smaller

version

• Method calls fresh copy of itself to work on smaller problem

• Indirect recursion– Recursive method calls another method that eventually

makes call back to recursive method

Page 165: Review

2005 Pearson Education, Inc. All rights reserved.

165

15.3 Example Using Recursion: Factorials

• Factorial of n, or n! is the productn · (n – 1) · (n – 2) · … · 1

With 1! equal to 1 and 0! defined to be 1.

• Can be solved recursively or iteratively (nonrecursively)

• Recursive solution uses following relationship:n! = n · (n – 1)!

• Infinite recursion – recursive calls are continuously made until memory has been exhausted

– Caused by either omitting base case or writing recursion step that does not converge on base case

Page 166: Review

2005 Pearson Education, Inc. All rights reserved.

166

Fig. 15.2 | Recursive evaluation of 5!.

Page 167: Review

2005 Pearson Education, Inc. All rights reserved.

167

Outline

•Factorial

•Calculator.java

1 // Fig. 15.3: FactorialCalculator.java

2 // Recursive factorial method.

3

4 public class FactorialCalculator

5 {

6 // recursive method factorial

7 public long factorial( long number )

8 {

9 if ( number <= 1 ) // test for base case

10 return 1; // base cases: 0! = 1 and 1! = 1

11 else // recursion step

12 return number * factorial( number - 1 );

13 } // end method factorial

14

15 // output factorials for values 0-10

16 public void displayFactorials()

17 {

18 // calculate the factorials of 0 through 10

19 for ( int counter = 0; counter <= 10; counter++ )

20 System.out.printf( "%d! = %d\n", counter, factorial( counter ) );

21 } // end method displayFactorials

22 } // end class FactorialCalculator

Base case returns 1

Original call to recursive method

Page 168: Review

2005 Pearson Education, Inc. All rights reserved.

168

Common Programming Error 15.1

• Either omitting the base case or writing the recursion step incorrectly so that it does not converge on the base case can cause a logic error known as infinite recursion, where recursive calls are continuously made until memory has been exhausted. This error is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

Page 169: Review

2005 Pearson Education, Inc. All rights reserved.

169

15.6 Recursion vs. Iteration

• Any problem that can be solved recursively can be solved iteratively

• Both iteration and recursion use a control statement– Iteration uses a repetition statement– Recursion uses a selection statement

• Iteration and recursion both involve a termination test– Iteration terminates when the loop-continuation condition

fails– Recursion terminates when a base case is reached

• Recursion can be expensive in terms of processor time and memory space, but usually provides a more intuitive solution

• But….you need to know recursion for the AP exam!!!

Page 170: Review

2005 Pearson Education, Inc. All rights reserved.

170

Pop quiz – Recursion

Text here

Page 171: Review

2005 Pearson Education, Inc. All rights reserved.

171

Review

Review

Exception Handling (ch13)

Page 172: Review

2005 Pearson Education, Inc. All rights reserved.

172

13.1 Introduction

• Exception – an indication of a problem that occurs during a program’s execution (an exceptional condition)

• Exception handling – resolving exceptions that may occur so program can continue or terminate gracefully

• Exception handling enables programmers to create programs that are more robust and fault-tolerant

Page 173: Review

2005 Pearson Education, Inc. All rights reserved.

173

Exception Examples (on the AP exam)

• NullPointerException – when a null reference is used where an object is expected

• ArrayIndexOutOfBoundsException – try to access an element past the end of an array

• ClassCastException – try to cast an object that does not have an is-a relationship with the type specified in the cast operator

• ArithmeticException – arithmetic problems, eg. Divide by zero• InputMismatchException – incorrect parameter type, eg. Scanner method nextInt receives a “abc123”

• IllegalArgumentException – throw this when a method has been passed an illegal or inappropriate argument

• IllegalStateException – signals that a method has been invoked at an illegal or inappropriate time, eg file read error

• NoSuchElementException – Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration, eg. Trying to read past an eof indicator

Page 174: Review

2005 Pearson Education, Inc. All rights reserved.

174

13.3 Example: Divide By Zero Without Exception Handling (Some definitions)

• Thrown exception – an exception that has occurred

• Throw point – initial point at which the exception occurs, top row of call chain

• Stack trace– Name of the exception in a message that indicates the

problem

– See the complete method-call stack on the console

Page 175: Review

2005 Pearson Education, Inc. All rights reserved.

175

Using the throws Clause

•throws clause – specifies the exceptions a method may throw

– Appears after method’s parameter list and before the method’s body

– Contains a comma-separated list of exceptions

– Exceptions can be thrown by statements in method’s body or by methods called in method’s body

– When you throw an exception, the current method terminates immediately

Page 176: Review

2005 Pearson Education, Inc. All rights reserved.

176

try-catch statements

• When a exception occurs (the exception is thrown), the program has the option of catching it.

• To catch an exception, we must anticipate where the exception might occur and enclose that code in a try block.

• The try block, is followed by a catch block that catches the exception (if it occurs) and performs the desired action.

Page 177: Review

2005 Pearson Education, Inc. All rights reserved.

177

General form of try-catch statementtry

{

try-block

}

catch (exception-type identifier)

{

catch-block

}

Page 178: Review

2005 Pearson Education, Inc. All rights reserved.

178

Catching Exceptions

•catch block – catches (i.e., receives) and handles an exception, contains:

– Begins with keyword catch

– Exception parameter in parentheses – exception parameter identifies the exception type and enables catch block to interact with caught exception object

– Block of code in curly braces that executes when exception of proper type occurs

Page 179: Review

2005 Pearson Education, Inc. All rights reserved.

179

Termination Model of Exception Handling

• When an exception occurs:– try block terminates immediately

– Program control transfers to first matching catch block

• After exception is handled:– Program control does not return to the throw point because the try block has expired. Flow of control proceeds to the first statement after the last catch block

Page 180: Review

2005 Pearson Education, Inc. All rights reserved.

180

Common Programming Error 13.1

• It is a syntax error to place code between a try block and its corresponding catch blocks.

• Each catch block can have only a single parameter—specifying a comma-separated list of exception parameters is a syntax error.

• It is a compilation error to catch the same type in two different catch blocks in a single try statement.

Page 181: Review

2005 Pearson Education, Inc. All rights reserved.

181

Error-Prevention Tip 13.4

• Read the online API documentation for a method before using that method in a program.

• The documentation specifies the exceptions thrown by the method (if any) and indicates reasons why such exceptions may occur.

• Then provide for handling those exceptions in your program.

Page 182: Review

2005 Pearson Education, Inc. All rights reserved.

182

ClassCastException Example

public class ExceptionTest

{

public static void main(String args[])

{

Object x = new Integer(0);

System.out.println((String)x);

} // end main

}

• How do we add exception handling?

Page 183: Review

2005 Pearson Education, Inc. All rights reserved.

183

Fig. 13.3 | Portion of class Throwable’s inheritance hierarchy.

13.6 Java Exception Hierarchy

Page 184: Review

2005 Pearson Education, Inc. All rights reserved.

184

13.6 Java Exception Hierarchy

• Two categories of exceptions: checked and unchecked

• Checked exceptions– Exceptions that inherit from class Exception but not from

RuntimeException

– Compiler checks each method call and method declaration to determine

whether the method throws checked exceptions. If so, the compiler ensures that the checked exception is caught or is declared in a throws clause. If not caught or declared, compiler error occurs.

• Unchecked exceptions– Inherit from class RuntimeException or class Error

– Compiler does not check code to see if exception is caught or declared

– If an unchecked exception occurs and is not caught, the program terminates or runs with unexpected results

Page 185: Review

2005 Pearson Education, Inc. All rights reserved.

185

13.7 finally block

• finally block– Consists of finally keyword followed by a block of code enclosed in

curly braces– Optional in a try statement– If present, is placed after the last catch block– Executes whether or not an exception is thrown in the corresponding

try block or any of its corresponding catch blocks– Will not execute if the application exits early from a try block via

method System.exit– Typically contains resource-release code

• Programs that obtain certain resources must return them explicitly to avoid resource leaks

– Standard streams• System.out – standard output stream• System.err – standard error stream

– System.err can be used to separate error output from regular output

Page 186: Review

2005 Pearson Education, Inc. All rights reserved.

186

Try-catch-finally general form

try { statements }

catch ( AKindOfException exception1 ) { exception-handling statements } . . . catch ( AnotherKindOfException exception2 ) { exception-handling statements } finally { statements resource-release statements }

Page 187: Review

2005 Pearson Education, Inc. All rights reserved.

187

Throwing Exceptions Using the throw Statement

•throw statement – used to throw exceptions

• Programmers can thrown exceptions themselves from a method if something has gone wrong

•throw statement consists of keyword throw followed by the exception object

• Example– Exceptions can be thrown from constructors when an error is

detector – good practice to eliminate improperly formed objects.

– Exceptions can be thrown if input parameters to a method are illegal or inappropriate (eg. IllegalStateException, IllegalArgumentException)

Page 188: Review

2005 Pearson Education, Inc. All rights reserved.

188

Example: Throwing exceptions 1 // Example IllegalArgumentException

2

3 public class BankAccount

4 {

5 double balance;

6 public void withdraw (double amount )

7 {

8 if (amount > balance)

9 {

10 IllegalArgumentException exception

11 = new IllegalArgumentException(“Amount exceeds balance”);

12 throw exception;

13 }

14 balance -= amount;

15 } //end withdraw

…..

} //end BankAccount

Page 189: Review

2005 Pearson Education, Inc. All rights reserved.

189

13.11 Declaring New Exception Types

• You can declare your own exception classes that are specific to the problems that can occur when another program uses your reusable classes

• New exception class must extend an existing exception class

• Typically contains only two constructors– One takes no arguments, passes a default exception

messages to the superclass constructor

– One that receives a customized exception message as a string and passes it to the superclass constructor

Page 190: Review

2005 Pearson Education, Inc. All rights reserved.

190

Example: New exception types 1 // Example New exception type

2

3 public class BankAccount

4 {

5 double balance;

6 public void withdraw (double amount )

7 {

8 if (amount > balance)

9 {

10 throw new InsufficientFundsException (“withdrawl of “ + amount +

11 “exceeds balance of “ + balance);

12 }

13 balance -= amount;

14 } //end withdraw

…..

} //end BankAccount

1 public class InsufficientFundsException extends RuntimeException

2 {

3 public InsufficientFundsException ( ) { }

4 public InsufficientFundsException ( message )

5 {

6 super (message); //print the message using getMessage method

7 }

…..

} //end InsufficientFundsException

Page 191: Review

2005 Pearson Education, Inc. All rights reserved.

191

Pop quizText here

Page 192: Review

2005 Pearson Education, Inc. All rights reserved.

192

Review

Review

Search and Sort algorithms (Ch16)

Page 193: Review

2005 Pearson Education, Inc. All rights reserved.

193

16.1 Introduction

• Searching– Determining whether a search key (the value, string, etc.

we’re looking for) is present in data

• Sorting– Places data in order based on one or more sort keys

Page 194: Review

2005 Pearson Education, Inc. All rights reserved.

194

Efficiency of the Search algorithms• Big O Notation (see AB25 and worksheet)

– Indicates the worst-case run time for an algorithm (how hard an algorithm has to work)

– Constant run time• O(1)• Does not grow as the size of the array increases

– Linear run time• O(n)• Grows proportional to the size of the array

– Quadratic run time• O(n2)• Grows proportional to the square of the size of the array

– Logarithmic run time (log is base2)• O(log n)• Grows proportional to the log of the size of the array• Example: If the number of data was 1024, the number of steps equals

log21024, or 10 steps since 210 = 1024.

Page 195: Review

2005 Pearson Education, Inc. All rights reserved.

195

Fig. 16.13 | Number of comparisons for common Big O notations.

n = O(log n) O(n) O(n log n) O(n2)

1 0 1 0 1

2 1 2 2 4

3 1 3 3 9

4 1 4 4 16

5 1 5 5 25

10 1 10 10 100

100 2 100 200 10000

1,000 3 1000 3000 106

1,000,000 6 1000000 6000000 1012

1,000,000,000 9 1000000000 9000000000 1018

Page 196: Review

2005 Pearson Education, Inc. All rights reserved.

196

Example 1Determine the order of the following algorithm.

(how many times will the recursive algo be called – try working it with an integer for n)

public int answer(int n){if (n == 1){

return 2;

}else {

return 2 * answer (n - 1);

}

}

Page 197: Review

2005 Pearson Education, Inc. All rights reserved.

197

Example 1 cont.The recursive algorithm will be called n times. If n = 5,

then the algorithm will be called 5 times to solve the problem of 2 to the 5th power.

public int answer(int n){if (n == 1){

return 2;

}else {

return 2 * answer (n - 1);

}

}

Therefore the order is O(n) or linear

Page 198: Review

2005 Pearson Education, Inc. All rights reserved.

198

Example 2

Determine the order of the following algorithm.

public void reverse(ArrayList <Integer> numbers){

int temp;

for (int loop = 0; loop <= (numbers.size()-1)/2; loop++){

temp = numbers.get(loop);

numbers.set(loop, numbers.get(numbers.size()-loop-1));

numbers.set(numbers.size()-loop-1, temp);

}

}

Page 199: Review

2005 Pearson Education, Inc. All rights reserved.

199

Example 2 cont.The algorithm swaps values from the first half of the list with values in

the second half of the list. Even though the algorithm does not go all the way through the ArrayList, we still class this as a linear algorithm.

public void reverse(ArrayList <Integer> numbers){

int temp;

for (int loop = 0; loop <= (numbers.size()-1)/2; loop++){

temp = numbers.get(loop);

numbers.set(loop, numbers.get(numbers.size()-loop-1));

numbers.set(numbers.size()-loop-1, temp);

}

}

Therefore the order is O(n) or linear

Page 200: Review

2005 Pearson Education, Inc. All rights reserved.

200

Example 3

Determine the order of the following algorithm.

final int N = 100;

boolean[][] data = new boolean[N][N];

void invert(boolean[][] data){

for (int row = 0; row < N; row++){

for (int col = 0; col < N; col++){

data[row][col] = (!data[row][col]);

}

}

}

Page 201: Review

2005 Pearson Education, Inc. All rights reserved.

201

Example 3 cont.The nested loops will cause the innermost statement,

data [row][col] = (! data [row][col]); to be executed (row x col) number of times.

final int N = 100;boolean[][] data = new boolean[N][N];void invert(boolean[][] data){ for (int row = 0; row < N; row++){ for (int col = 0; col < N; col++){ data[row][col] = (!data[row][col]); } }}

Therefore the order is O(n2) or quadratic

Page 202: Review

2005 Pearson Education, Inc. All rights reserved.

202

16.2.1 Linear Search

• Linear (sequential) search– Searches each element sequentially

– If search key is not present• Tests each element

• When algorithm reaches end of array, informs user search key is not present

– If search key is present• Test each element until it finds a match

Page 203: Review

2005 Pearson Education, Inc. All rights reserved.

203

Outline

•LinearArray.java

•(1 of 2)

1 // Fig 16.2: LinearArray.java

2 // Class that contains an array of random integers and a method

3 // that will search that array sequentially

4 import java.util.Random;

5

6 public class LinearArray

7 {

8 private int[] data; // array of values

9 private static Random generator = new Random();

10

11 // create array of given size and fill with random numbers

12 public LinearArray( int size )

13 {

14 data = new int[ size ]; // create space for array

15

16 // fill array with random ints in range 10-99

17 for ( int i = 0; i < size; i++ )

18 data[ i ] = 10 + generator.nextInt( 90 );

19 } // end LinearArray constructor 20

Page 204: Review

2005 Pearson Education, Inc. All rights reserved.

204

Outline

•LinearArray.java

•(2 of 2)

21 // perform a linear search on the data

22 public int linearSearch( int searchKey )

23 {

24 // loop through array sequentially

25 for ( int index = 0; index < data.length; index++ )

26 if ( data[ index ] == searchKey )

27 return index; // return index of integer

28

29 return -1; // integer was not found

30 } // end method linearSearch

31

32 // method to output values in array

33 public String toString()

34 {

35 StringBuffer temporary = new StringBuffer();

36

37 // iterate through array

38 for ( int element : data )

39 temporary.append( element + " " );

40

41 temporary.append( "\n" ); // add endline character

42 return temporary.toString();

43 } // end method toString

44 } // end class LinearArray

Iterate through array

Test each element sequentially

Return index containing search key

Page 205: Review

2005 Pearson Education, Inc. All rights reserved.

205

Outline

•LinearSearchTest.java

•(1 of 2)

1 // Fig 16.3: LinearSearchTest.java

2 // Sequentially search an array for an item.

3 import java.util.Scanner;

4

5 public class LinearSearchTest

6 {

7 public static void main( String args[] )

8 {

9 // create Scanner object to input data

10 Scanner input = new Scanner( System.in );

11

12 int searchInt; // search key

13 int position; // location of search key in array

14

15 // create array and output it

16 LinearArray searchArray = new LinearArray( 10 );

17 System.out.println( searchArray ); // print array

18

19 // get input from user

20 System.out.print(

21 "Please enter an integer value (-1 to quit): " );

22 searchInt = input.nextInt(); // read first int from user

23

24 // repeatedly input an integer; -1 terminates the program

25 while ( searchInt != -1 )

26 {

27 // perform linear search

28 position = searchArray.linearSearch( searchInt ); 29

Page 206: Review

2005 Pearson Education, Inc. All rights reserved.

206

Outline

•LinearSearchTest.java

•(2 of 2)

30 if ( position == -1 ) // integer was not found

31 System.out.println( "The integer " + searchInt +

32 " was not found.\n" );

33 else // integer was found

34 System.out.println( "The integer " + searchInt +

35 " was found in position " + position + ".\n" );

36

37 // get input from user

38 System.out.print(

39 "Please enter an integer value (-1 to quit): " );

40 searchInt = input.nextInt(); // read next int from user

41 } // end while

42 } // end main

43 } // end class LinearSearchTest

16 35 68 10 48 36 81 60 84 21 Please enter an integer value (-1 to quit): 48 The integer 48 was found in position 4. Please enter an integer value (-1 to quit): 60 The integer 60 was found in position 7. Please enter an integer value (-1 to quit): 33 The integer 33 was not found. Please enter an integer value (-1 to quit): -1

Page 207: Review

2005 Pearson Education, Inc. All rights reserved.

207

Efficiency of Linear Search (?)

• Linear search algorithm– O(n)

– Worst case: algorithm checks every element before being able to determine if the search key is not present

– Grows proportional to the size of the array

Page 208: Review

2005 Pearson Education, Inc. All rights reserved.

208

16.2.2 Binary Search

• Binary search– More efficient than linear search

– Requires elements to be sorted• If array, can use java.util.Arrays sort methods

– Tests the middle element in an array• If it is the search key, algorithm returns

• Otherwise, if the search key is smaller, eliminates larger half of array

• If the search key is larger, eliminates smaller half of array

– Each iteration eliminates half of the remaining elements

Page 209: Review

2005 Pearson Education, Inc. All rights reserved.

209

Outline

•BinaryArray.java

•(1 of 3)

1 // Fig 16.4: BinaryArray.java

2 // Class that contains an array of random integers and a method

3 // that uses binary search to find an integer.

4 import java.util.Random;

5 import java.util.Arrays;

6

7 public class BinaryArray

8 {

9 private int[] data; // array of values

10 private static Random generator = new Random();

11

12 // create array of given size and fill with random integers

13 public BinaryArray( int size )

14 {

15 data = new int[ size ]; // create space for array

16

17 // fill array with random ints in range 10-99

18 for ( int i = 0; i < size; i++ )

19 data[ i ] = 10 + generator.nextInt( 90 );

20

21 Arrays.sort( data );

22 } // end BinaryArray constructor 23

Page 210: Review

2005 Pearson Education, Inc. All rights reserved.

210

Outline

•BinaryArray.java

•(2 of 3)

24 // perform a binary search on the data

25 public int binarySearch( int searchElement )

26 {

27 int low = 0; // low end of the search area

28 int high = data.length - 1; // high end of the search area

29 int middle = ( low + high + 1 ) / 2; // middle element

30 int location = -1; // return value; -1 if not found

31

32 do // loop to search for element

33 {

34 // print remaining elements of array

35 System.out.print( remainingElements( low, high ) );

36

37 // output spaces for alignment

38 for ( int i = 0; i < middle; i++ )

39 System.out.print( " " );

40 System.out.println( " * " ); // indicate current middle

41

42 // if the element is found at the middle

43 if ( searchElement == data[ middle ] )

44 location = middle; // location is the current middle

45

46 // middle element is too high

47 else if ( searchElement < data[ middle ] )

48 high = middle - 1; // eliminate the higher half

49 else // middle element is too low

50 low = middle + 1; // eliminate the lower half 51

Store high, low and middle of remaining array to search

Loop until key is found or no elements left to search

If search element is the middle element

Return middle element

If search element is less than middle element

Eliminate higher half

Else, eliminate lower half

Page 211: Review

2005 Pearson Education, Inc. All rights reserved.

211

Outline

•BinaryArray.java

•(3 of 3)

52 middle = ( low + high + 1 ) / 2; // recalculate the middle

53 } while ( ( low <= high ) && ( location == -1 ) );

54

55 return location; // return location of search key

56 } // end method binarySearch

57

58 // method to output certain values in array

59 public String remainingElements( int low, int high )

60 {

61 StringBuffer temporary = new StringBuffer();

62

63 // output spaces for alignment

64 for ( int i = 0; i < low; i++ )

65 temporary.append( " " );

66

67 // output elements left in array

68 for ( int i = low; i <= high; i++ )

69 temporary.append( data[ i ] + " " );

70

71 temporary.append( "\n" );

72 return temporary.toString();

73 } // end method remainingElements

74

75 // method to output values in array

76 public String toString()

77 {

78 return remainingElements( 0, data.length - 1 );

79 } // end method toString

80 } // end class BinaryArray

Update middle of array

Return location of element

Page 212: Review

2005 Pearson Education, Inc. All rights reserved.

212

Outline

•BinarySearchTest.java

•(1 of 3)

1 // Fig 16.5: BinarySearchTest.java

2 // Use binary search to locate an item in an array.

3 import java.util.Scanner;

4

5 public class BinarySearchTest

6 {

7 public static void main( String args[] )

8 {

9 // create Scanner object to input data

10 Scanner input = new Scanner( System.in );

11

12 int searchInt; // search key

13 int position; // location of search key in array

14

15 // create array and output it

16 BinaryArray searchArray = new BinaryArray( 15 );

17 System.out.println( searchArray );

18

Page 213: Review

2005 Pearson Education, Inc. All rights reserved.

213

Outline

•BinarySearchTest.java

•(2 of 3)

19 // get input from user

20 System.out.print(

21 "Please enter an integer value (-1 to quit): " );

22 searchInt = input.nextInt(); // read an int from user

23 System.out.println();

24

25 // repeatedly input an integer; -1 terminates the program

26 while ( searchInt != -1 )

27 {

28 // use binary search to try to find integer

29 position = searchArray.binarySearch( searchInt );

30

31 // return value of -1 indicates integer was not found

32 if ( position == -1 )

33 System.out.println( "The integer " + searchInt +

34 " was not found.\n" );

35 else

36 System.out.println( "The integer " + searchInt +

37 " was found in position " + position + ".\n" );

38

39 // get input from user

40 System.out.print(

41 "Please enter an integer value (-1 to quit): " );

42 searchInt = input.nextInt(); // read an int from user

43 System.out.println();

44 } // end while

45 } // end main

46 } // end class BinarySearchTest

Page 214: Review

2005 Pearson Education, Inc. All rights reserved.

214

Binary Search Example in JCreator 13 23 24 34 35 36 38 42 47 51 68 74 75 85 97 Please enter an integer value (-1 to quit): 23 13 23 24 34 35 36 38 42 47 51 68 74 75 85 97 * 13 23 24 34 35 36 38 * 13 23 24 * The integer 23 was found in position 1. Please enter an integer value (-1 to quit): 75 13 23 24 34 35 36 38 42 47 51 68 74 75 85 97 * 47 51 68 74 75 85 97 * 75 85 97 * 75 * The integer 75 was found in position 12. Please enter an integer value (-1 to quit): 52 13 23 24 34 35 36 38 42 47 51 68 74 75 85 97 * 47 51 68 74 75 85 97 * 47 51 68 * 68 * The integer 52 was not found. Please enter an integer value (-1 to quit): -1

Page 215: Review

2005 Pearson Education, Inc. All rights reserved.

215

Efficiency of Binary Search (?)

• Binary search– Each comparison halves the size of the remaining array

– Results in O(log n)

– Called logarithmic run time

– Try an example with 8 elements. How many iterations before the result is found (worst case).

Page 216: Review

2005 Pearson Education, Inc. All rights reserved.

216

16.3 Sorting Algorithms

• Sorting data– Placing data into some particular order

• A bank sorts checks by account number

• Telephone companies sort accounts by name

– End result is always the same – a sorted array

– Choice of algorithm affects how you achieve the result and, most importantly, how fast you achieve the result

Page 217: Review

2005 Pearson Education, Inc. All rights reserved.

217

16.3.1 Selection Sort• Use

– If want to sort the first n element of an array, example the 5 highest GPA’s for the class

• Selection sort details– Simple, but inefficient sorting algorithm– First iteration selects smallest element in array and swaps

it with the first element– Each iteration selects the smallest remaining unsorted

element and swaps it with the next element at the front of the array

– After i iterations, the smallest i elements will be sorted in the first i elements of the array

Page 218: Review

2005 Pearson Education, Inc. All rights reserved.

218

Selection Sort Example Unsorted array: 61 87 80 58 40 50 20 13 71 45 after pass 1: 13 87 80 58 40 50 20 61* 71 45 -- after pass 2: 13 20 80 58 40 50 87* 61 71 45 -- -- after pass 3: 13 20 40 58 80* 50 87 61 71 45 -- -- -- after pass 4: 13 20 40 45 80 50 87 61 71 58* -- -- -- -- after pass 5: 13 20 40 45 50 80* 87 61 71 58 -- -- -- -- -- after pass 6: 13 20 40 45 50 58 87 61 71 80* -- -- -- -- -- -- after pass 7: 13 20 40 45 50 58 61 87* 71 80 -- -- -- -- -- -- -- after pass 8: 13 20 40 45 50 58 61 71 87* 80 -- -- -- -- -- -- -- -- after pass 9: 13 20 40 45 50 58 61 71 80 87* -- -- -- -- -- -- -- -- -- Sorted array: 13 20 40 45 50 58 61 71 80 87

Page 219: Review

2005 Pearson Education, Inc. All rights reserved.

219

Outline

•SelectionSort.java

•(1 of 3)

1 // Fig 16.6: SelectionSort.java

2 // Class that creates an array filled with random integers.

3 // Provides a method to sort the array with selection sort.

4 import java.util.Random;

5

6 public class SelectionSort

7 {

8 private int[] data; // array of values

9 private static Random generator = new Random();

10

11 // create array of given size and fill with random integers

12 public SelectionSort( int size )

13 {

14 data = new int[ size ]; // create space for array

15

16 // fill array with random ints in range 10-99

17 for ( int i = 0; i < size; i++ )

18 data[ i ] = 10 + generator.nextInt( 90 );

19 } // end SelectionSort constructor

20

21 // sort array using selection sort

22 public void sort()

23 {

24 int smallest; // index of smallest element

25

26 // loop over data.length - 1 elements

27 for ( int i = 0; i < data.length - 1; i++ )

28 {

29 smallest = i; // first index of remaining array 30

Variable to store index of smallest element

Loop length – 1 times

Page 220: Review

2005 Pearson Education, Inc. All rights reserved.

220

Outline

•SelectionSort.java

•(2 of 3)

31 // loop to find index of smallest element

32 for ( int index = i + 1; index < data.length; index++ )

33 if ( data[ index ] < data[ smallest ] )

34 smallest = index;

35

36 swap( i, smallest ); // swap smallest element into position

37 printPass( i + 1, smallest ); // output pass of algorithm

38 } // end outer for

39 } // end method sort

40

41 // helper method to swap values in two elements

42 public void swap( int first, int second )

43 {

44 int temporary = data[ first ]; // store first in temporary

45 data[ first ] = data[ second ]; // replace first with second

46 data[ second ] = temporary; // put temporary in second

47 } // end method swap

48

49 // print a pass of the algorithm

50 public void printPass( int pass, int index )

51 {

52 System.out.print( String.format( "after pass %2d: ", pass ) );

53

54 // output elements till selected item

55 for ( int i = 0; i < index; i++ )

56 System.out.print( data[ i ] + " " );

57

58 System.out.print( data[ index ] + "* " ); // indicate swap 59

Loop over remaining elements

Locate smallest remaining element

Swap smallest element with first unsorted element

Page 221: Review

2005 Pearson Education, Inc. All rights reserved.

221

Outline

•SelectionSort.java

•(3 of 3)

60 // finish outputting array

61 for ( int i = index + 1; i < data.length; i++ )

62 System.out.print( data[ i ] + " " );

63

64 System.out.print( "\n " ); // for alignment

65

66 // indicate amount of array that is sorted

67 for ( int j = 0; j < pass; j++ )

68 System.out.print( "-- " );

69 System.out.println( "\n" ); // add endline

70 } // end method indicateSelection

71

72 // method to output values in array

73 public String toString()

74 {

75 StringBuffer temporary = new StringBuffer();

76

77 // iterate through array

78 for ( int element : data )

79 temporary.append( element + " " );

80

81 temporary.append( "\n" ); // add endline character

82 return temporary.toString();

83 } // end method toString

84 } // end class SelectionSort

Page 222: Review

2005 Pearson Education, Inc. All rights reserved.

222

Outline

•SelectionSortTest.java

•(1 of 2)

1 // Fig 16.7: SelectionSortTest.java

2 // Test the selection sort class.

3

4 public class SelectionSortTest

5 {

6 public static void main( String[] args )

7 {

8 // create object to perform selection sort

9 SelectionSort sortArray = new SelectionSort( 10 );

10

11 System.out.println( "Unsorted array:" );

12 System.out.println( sortArray ); // print unsorted array

13

14 sortArray.sort(); // sort array

15

16 System.out.println( "Sorted array:" );

17 System.out.println( sortArray ); // print sorted array

18 } // end main

19 } // end class SelectionSortTest

Page 223: Review

2005 Pearson Education, Inc. All rights reserved.

223

Selection Sort Example in JCreator Unsorted array: 61 87 80 58 40 50 20 13 71 45 after pass 1: 13 87 80 58 40 50 20 61* 71 45 -- after pass 2: 13 20 80 58 40 50 87* 61 71 45 -- -- after pass 3: 13 20 40 58 80* 50 87 61 71 45 -- -- -- after pass 4: 13 20 40 45 80 50 87 61 71 58* -- -- -- -- after pass 5: 13 20 40 45 50 80* 87 61 71 58 -- -- -- -- -- after pass 6: 13 20 40 45 50 58 87 61 71 80* -- -- -- -- -- -- after pass 7: 13 20 40 45 50 58 61 87* 71 80 -- -- -- -- -- -- -- after pass 8: 13 20 40 45 50 58 61 71 87* 80 -- -- -- -- -- -- -- -- after pass 9: 13 20 40 45 50 58 61 71 80 87* -- -- -- -- -- -- -- -- -- Sorted array: 13 20 40 45 50 58 61 71 80 87

Page 224: Review

2005 Pearson Education, Inc. All rights reserved.

224

Efficiency of Selection Sort?

• Selection sort– Outer for loop iterates over n – 1 elements

– Inner for loop iterates over remaining elements in the array:

n + (n-1) + (n-2) + (n-3) + .. + 1 = n(n+1)/2 = (n2 + n)/2

– Results in O(n2)

Page 225: Review

2005 Pearson Education, Inc. All rights reserved.

225

16.3.2 Insertion Sort

• Insertion sort– Another simple, but inefficient sorting algorithm

– First pass takes the second element and inserts it into the correct order with the first element

– Each iteration takes the next element in the array and inserts it into the sorted elements at the beginning of the array

– After i iterations, the first i elements of the array are in sorted order

Page 226: Review

2005 Pearson Education, Inc. All rights reserved.

226

Example 1

14 17 22 15 1. Initial Array to sort

2. temp = 15

3. Compare to 1st element on left. If left bigger then shift it right

4. Compare to next element on left. If left bigger then shift it right

5. Compare to next element on left. If left bigger then shift it right. Else insert temp

14 17 22

14 17 22

14 17 22

14 15 17 22

Page 227: Review

2005 Pearson Education, Inc. All rights reserved.

227

Example 28 6 7 10 1. Initial Array to sort

2. Sort the 1st two elements:temp=6, compare to element on left,

shift if needed and insert

3. Sort the next element:temp=7, compare to element on left,

shift if needed, continue comparing until insert

4. Sort the next element:temp=10, compare to element on left,

shift if needed, continue comparing until insert

8 7 10

6 8 7 10

6 8 10

6 7 8 10

6 7 8

6 7 8 10

Page 228: Review

2005 Pearson Education, Inc. All rights reserved.

228

Example 3 Unsorted array: 40 17 45 82 62 32 30 44 93 10 after pass 1: 17* 40 45 82 62 32 30 44 93 10 -- -- after pass 2: 17 40 45* 82 62 32 30 44 93 10 -- -- -- after pass 3: 17 40 45 82* 62 32 30 44 93 10 -- -- -- -- after pass 4: 17 40 45 62* 82 32 30 44 93 10 -- -- -- -- -- after pass 5: 17 32* 40 45 62 82 30 44 93 10 -- -- -- -- -- -- after pass 6: 17 30* 32 40 45 62 82 44 93 10 -- -- -- -- -- -- -- after pass 7: 17 30 32 40 44* 45 62 82 93 10 -- -- -- -- -- -- -- -- after pass 8: 17 30 32 40 44 45 62 82 93* 10 -- -- -- -- -- -- -- -- -- after pass 9: 10* 17 30 32 40 44 45 62 82 93 -- -- -- -- -- -- -- -- -- -- Sorted array: 10 17 30 32 40 44 45 62 82 93

Page 229: Review

2005 Pearson Education, Inc. All rights reserved.

229

Outline

•InsertionSort.java

•(1 of 4)

1 // Fig 16.8: InsertionSort.java

2 // Class that creates an array filled with random integers.

3 // Provides a method to sort the array with insertion sort.

4 import java.util.Random;

5

6 public class InsertionSort

7 {

8 private int[] data; // array of values

9 private static Random generator = new Random();

10

11 // create array of given size and fill with random integers

12 public InsertionSort( int size )

13 {

14 data = new int[ size ]; // create space for array

15

16 // fill array with random ints in range 10-99

17 for ( int i = 0; i < size; i++ )

18 data[ i ] = 10 + generator.nextInt( 90 );

19 } // end InsertionSort constructor

20

Page 230: Review

2005 Pearson Education, Inc. All rights reserved.

230

Outline

•InsertionSort.java

•(2 of 4)

21 // sort array using insertion sort

22 public void sort()

23 {

24 int insert; // temporary variable to hold element to insert

25

26 // loop over data.length - 1 elements

27 for ( int next = 1; next < data.length; next++ )

28 {

29 // store value in current element

30 insert = data[ next ];

31

32 // initialize location to place element

33 int moveItem = next;

34

35 // search for place to put current element

36 while ( moveItem > 0 && data[ moveItem - 1 ] > insert )

37 {

38 // shift element right one slot

39 data[ moveItem ] = data[ moveItem - 1 ];

40 moveItem--;

41 } // end while

42

43 data[ moveItem ] = insert; // place inserted element

44 printPass( next, moveItem ); // output pass of algorithm

45 } // end for

46 } // end method sort

47

Declare variable to store element to be inserted

Iterate over length – 1 elements

Store value to insert

Search for location to place inserted element

Move one element to the right

Decrement location to insert element

Insert element into sorted place

Page 231: Review

2005 Pearson Education, Inc. All rights reserved.

231

Outline

•InsertionSort.java

•(3 of 4)

48 // print a pass of the algorithm

49 public void printPass( int pass, int index )

50 {

51 System.out.print( String.format( "after pass %2d: ", pass ) );

52

53 // output elements till swapped item

54 for ( int i = 0; i < index; i++ )

55 System.out.print( data[ i ] + " " );

56

57 System.out.print( data[ index ] + "* " ); // indicate swap

58

59 // finish outputting array

60 for ( int i = index + 1; i < data.length; i++ )

61 System.out.print( data[ i ] + " " );

62

63 System.out.print( "\n " ); // for alignment

64

65 // indicate amount of array that is sorted

66 for( int i = 0; i <= pass; i++ )

67 System.out.print( "-- " );

68 System.out.println( "\n" ); // add endline

69 } // end method printPass

70

Page 232: Review

2005 Pearson Education, Inc. All rights reserved.

232

Outline

•InsertionSort.java

•(4 of 4)

71 // method to output values in array

72 public String toString()

73 {

74 StringBuffer temporary = new StringBuffer();

75

76 // iterate through array

77 for ( int element : data )

78 temporary.append( element + " " );

79

80 temporary.append( "\n" ); // add endline character

81 return temporary.toString();

82 } // end method toString

83 } // end class InsertionSort

Page 233: Review

2005 Pearson Education, Inc. All rights reserved.

233

Outline

•InsertionSortTest.java

•(1 of 2)

1 // Fig 16.9: InsertionSortTest.java

2 // Test the insertion sort class.

3

4 public class InsertionSortTest

5 {

6 public static void main( String[] args )

7 {

8 // create object to perform selection sort

9 InsertionSort sortArray = new InsertionSort( 10 );

10

11 System.out.println( "Unsorted array:" );

12 System.out.println( sortArray ); // print unsorted array

13

14 sortArray.sort(); // sort array

15

16 System.out.println( "Sorted array:" );

17 System.out.println( sortArray ); // print sorted array

18 } // end main

19 } // end class InsertionSortTest

Page 234: Review

2005 Pearson Education, Inc. All rights reserved.

234

Insertion Sort Example in JCreator Unsorted array: 40 17 45 82 62 32 30 44 93 10 after pass 1: 17* 40 45 82 62 32 30 44 93 10 -- -- after pass 2: 17 40 45* 82 62 32 30 44 93 10 -- -- -- after pass 3: 17 40 45 82* 62 32 30 44 93 10 -- -- -- -- after pass 4: 17 40 45 62* 82 32 30 44 93 10 -- -- -- -- -- after pass 5: 17 32* 40 45 62 82 30 44 93 10 -- -- -- -- -- -- after pass 6: 17 30* 32 40 45 62 82 44 93 10 -- -- -- -- -- -- -- after pass 7: 17 30 32 40 44* 45 62 82 93 10 -- -- -- -- -- -- -- -- after pass 8: 17 30 32 40 44 45 62 82 93* 10 -- -- -- -- -- -- -- -- -- after pass 9: 10* 17 30 32 40 44 45 62 82 93 -- -- -- -- -- -- -- -- -- -- Sorted array: 10 17 30 32 40 44 45 62 82 93

Page 235: Review

2005 Pearson Education, Inc. All rights reserved.

235

Efficiency of Insertion Sort?

• Insertion sort– Outer for loop iterates over n – 1 elements

– Inner while loop iterates over preceding elements of array

– Inner for loop iterates over preceding elements in the array:

n + (n-1) + (n-2) + (n-3) + .. + 1 = n(n+1)/2 = (n2 + n)/2

– Results in O(n2)

Page 236: Review

2005 Pearson Education, Inc. All rights reserved.

236

16.3.3 Merge Sort

• Merge sort– More efficient sorting algorithm, but also more complex

– Splits array into two approximately equal sized subarrays, sorts each subarray, then merges the subarrays

– The implementation is recursive!!• Base case is a one-element array which cannot be unsorted

• Recursion step splits an array into two pieces, sorts each piece, then merges the sorted pieces

– You are expected to know the basic structure of the algorithm (break the array in halves, recursively call the sortArray method for each half, merge the two back together). You don’t have to know the details of the merge method

Page 237: Review

2005 Pearson Education, Inc. All rights reserved.

237

Merge Sort Example

Unsorted: 75 56 85 90 49 26 12 48 40 47 split: 75 56 85 90 49 26 12 48 40 47 75 56 85 90 49 26 12 48 40 47 split: 75 56 85 90 49 75 56 85 90 49 split: 75 56 85 75 56 85 split: 75 56 75 56

merge: 75 56 56 75 merge: 56 75 85 56 75 85 split: 90 49 90 49 merge: 90 49 49 90 merge: 56 75 85 49 90 49 56 75 85 90 split: 26 12 48 40 47 26 12 48 40 47 split: 26 12 48 26 12 48 split: 26 12 26 12

merge: 26 12 12 26 merge: 12 26 48 12 26 48 split: 40 47 40 47 merge: 40 47 40 47 merge: 12 26 48 40 47 12 26 40 47 48 merge: 49 56 75 85 90 12 26 40 47 48 49 56 75 85 90 Sorted: 12 26 40 47 48 49 56 75 85 90

Page 238: Review

2005 Pearson Education, Inc. All rights reserved.

238

Outline

•MergeSort.java

•(1 of 5)

1 // Figure 16.10: MergeSort.java

2 // Class that creates an array filled with random integers.

3 // Provides a method to sort the array with merge sort.

4 import java.util.Random;

5

6 public class MergeSort

7 {

8 private int[] data; // array of values

9 private static Random generator = new Random();

10

11 // create array of given size and fill with random integers

12 public MergeSort( int size )

13 {

14 data = new int[ size ]; // create space for array

15

16 // fill array with random ints in range 10-99

17 for ( int i = 0; i < size; i++ )

18 data[ i ] = 10 + generator.nextInt( 90 );

19 } // end MergeSort constructor

20

21 // calls recursive split method to begin merge sorting

22 public void sort()

23 {

24 sortArray( 0, data.length - 1 ); // split entire array

25 } // end method sort 26

Call recursive helper method

Page 239: Review

2005 Pearson Education, Inc. All rights reserved.

239

Outline

•MergeSort.java

•(2 of 5)

27 // splits array, sorts subarrays and merges subarrays into sorted array

28 private void sortArray( int low, int high )

29 {

30 // test base case; size of array equals 1

31 if ( ( high - low ) >= 1 ) // if not base case

32 {

33 int middle1 = ( low + high ) / 2; // calculate middle of array

34 int middle2 = middle1 + 1; // calculate next element over

35

36 // output split step

37 System.out.println( "split: " + subarray( low, high ) );

38 System.out.println( " " + subarray( low, middle1 );

39 System.out.println( " " + subarray( middle2, high ) );

40 System.out.println();

41

42 // split array in half; sort each half (recursive calls)

43 sortArray( low, middle1 ); // first half of array

44 sortArray( middle2, high ); // second half of array

45

46 // merge two sorted arrays after split calls return

47 merge ( low, middle1, middle2, high );

48 } // end if

49 } // end method split 50

Test for base case

Compute middle of array

Compute element one spot to right of middle

Recursively sort first half of array

Recursively sort second half of array

Merge the two sorted subarrays

Page 240: Review

2005 Pearson Education, Inc. All rights reserved.

240

Outline

•MergeSort.java

•(3 of 5)

51 // merge two sorted subarrays into one sorted subarray

52 private void merge( int left, int middle1, int middle2, int right )

53 {

54 int leftIndex = left; // index into left subarray

55 int rightIndex = middle2; // index into right subarray

56 int combinedIndex = left; // index into temporary working array

57 int[] combined = new int[ data.length ]; // working array

58

59 // output two subarrays before merging

60 System.out.println( "merge: " + subarray( left, middle1 ) );

61 System.out.println( " " + subarray( middle2, right ) );

62

63 // merge arrays until reaching end of either

64 while ( leftIndex <= middle1 && rightIndex <= right )

65 {

66 // place smaller of two current elements into result

67 // and move to next space in arrays

68 if ( data[ leftIndex ] <= data[ rightIndex ] )

69 combined[ combinedIndex++ ] = data[ leftIndex++ ];

70 else

71 combined[ combinedIndex++ ] = data[ rightIndex++ ];

72 } // end while

73

Index of element in left array

Index of element in right array

Index to place element in combined array

Array to hold sorted elements

Loop until reach end of either array

Determine smaller of two elements

Place smaller element in combined array

Page 241: Review

2005 Pearson Education, Inc. All rights reserved.

241

Outline

•MergeSort.java

•(4 of 5)

74 // if left array is empty

75 if ( leftIndex == middle2 )

76 // copy in rest of right array

77 while ( rightIndex <= right )

78 combined[ combinedIndex++ ] = data[ rightIndex++ ];

79 else // right array is empty

80 // copy in rest of left array

81 while ( leftIndex <= middle1 )

82 combined[ combinedIndex++ ] = data[ leftIndex++ ];

83

84 // copy values back into original array

85 for ( int i = left; i <= right; i++ )

86 data[ i ] = combined[ i ];

87

88 // output merged array

89 System.out.println( " " + subarray( left, right ) );

90 System.out.println();

91 } // end method merge 92

If left array is empty

Fill with elements of right array

If right array is empty

Fill with elements of left array

Copy values back to original array

Page 242: Review

2005 Pearson Education, Inc. All rights reserved.

242

Outline

•MergeSort.java

•(5 of 5)

93 // method to output certain values in array

94 public String subarray( int low, int high )

95 {

96 StringBuffer temporary = new StringBuffer();

97

98 // output spaces for alignment

99 for ( int i = 0; i < low; i++ )

100 temporary.append( " " );

101

102 // output elements left in array

103 for ( int i = low; i <= high; i++ )

104 temporary.append( " " + data[ i ] );

105

106 return temporary.toString();

107 } // end method subarray

108

109 // method to output values in array

110 public String toString()

111 {

112 return subarray( 0, data.length - 1 );

113 } // end method toString

114 } // end class MergeSort

Page 243: Review

2005 Pearson Education, Inc. All rights reserved.

243

Outline

•MergeSortTest.java

•(1 of 4)

1 // Figure 16.11: MergeSortTest.java

2 // Test the merge sort class.

3

4 public class MergeSortTest

5 {

6 public static void main( String[] args )

7 {

8 // create object to perform merge sort

9 MergeSort sortArray = new MergeSort( 10 );

10

11 // print unsorted array

12 System.out.println( "Unsorted:" + sortArray + "\n" );

13

14 sortArray.sort(); // sort array

15

16 // print sorted array

17 System.out.println( "Sorted: " + sortArray );

18 } // end main

19 } // end class MergeSortTest

Page 244: Review

2005 Pearson Education, Inc. All rights reserved.

244

Merge Sort Example in JCreator

Unsorted: 75 56 85 90 49 26 12 48 40 47 split: 75 56 85 90 49 26 12 48 40 47 75 56 85 90 49 26 12 48 40 47 split: 75 56 85 90 49 75 56 85 90 49 split: 75 56 85 75 56 85 split: 75 56 75 56

merge: 75 56 56 75 merge: 56 75 85 56 75 85 split: 90 49 90 49 merge: 90 49 49 90 merge: 56 75 85 49 90 49 56 75 85 90 split: 26 12 48 40 47 26 12 48 40 47 split: 26 12 48 26 12 48 split: 26 12 26 12

merge: 26 12 12 26 merge: 12 26 48 12 26 48 split: 40 47 40 47 merge: 40 47 40 47 merge: 12 26 48 40 47 12 26 40 47 48 merge: 49 56 75 85 90 12 26 40 47 48 49 56 75 85 90 Sorted: 12 26 40 47 48 49 56 75 85 90

Page 245: Review

2005 Pearson Education, Inc. All rights reserved.

245

Efficiency of Merge Sort?

• Far more efficient that selection sort or insertion sort• Last merge requires n – 1 comparisons to merge entire

array• Each lower level has twice as many calls to method merge,

with each call operating on an array half the size which results in O(n) total comparisons

• There will be O(log n) levels• Results in O(n log n)• Downside is that it requires temporary array for the

merge so may impact the system memory (especially for large arrays)