data structures for java william h. ford william r. topp java primer bret ford © 2005, prentice...

99
Data Structures for Java Data Structures for Java William H. Ford William H. Ford William R. Topp William R. Topp Java Primer Java Primer Bret Ford © 2005, Prentice Hall

Upload: horatio-brown

Post on 23-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Data Structures for JavaData Structures for JavaWilliam H. FordWilliam H. FordWilliam R. ToppWilliam R. Topp

Java PrimerJava Primer

Bret Ford

© 2005, Prentice Hall

Page 2: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Structure of a Java ProgramStructure of a Java Program Sample Problem: A person has a heigh of Sample Problem: A person has a heigh of

74 inches. 74 inches. The program converts the height into feet The program converts the height into feet

and inches and into centimeters. and inches and into centimeters. The conversion factor "1 inch = 2.54 cm" is The conversion factor "1 inch = 2.54 cm" is

used for the metric measure. used for the metric measure. Output to the screen displays the Output to the screen displays the

conversion in the form " Height of <foot> conversion in the form " Height of <foot> foot <inch> in metric is <centimeter> cm" foot <inch> in metric is <centimeter> cm" where the bracketed symbol <value> is where the bracketed symbol <value> is the actual value of the corresponding unit. the actual value of the corresponding unit.

Page 3: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Structure of a Java Program Structure of a Java Program (continued)(continued)

The class name with the extension The class name with the extension ".java" becomes the file name. By ".java" becomes the file name. By convention, all class names in Java begin convention, all class names in Java begin with a capital letter. with a capital letter. For the class name DemoProgram the file For the class name DemoProgram the file

name is DemoProgram.java.name is DemoProgram.java. The body of the class is enclosed in a pair of The body of the class is enclosed in a pair of

braces and includes a special method called braces and includes a special method called main.main.

This method designates where the runtime This method designates where the runtime system will begin execution of the program.system will begin execution of the program.

Page 4: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Structure of a Java Program Structure of a Java Program (continued)(continued)

// main class for source code in file// "DemoProgram.java"public class DemoProgram{

public static void main(String[] args){

<code to implement main()>}

}

Page 5: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Program ListingProgram Listing

[1] // DemoProgram: Converts height in inches into[2] // units of feet and inches as well as metric[3] // units and then outputs the results[4] [5] // application class that contains the main method[6] public class DemoProgram[7] {[8] public static void main(String[] args)[9] {[10] // the constant conversion factor inches to[11] // centimeters[12] final double IN2CM = 2.54;[13] [14] // variables for height, feet, inches, and[15] // centimeters[16] int height = 74, foot, inch;[17] double centimeter;

Page 6: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Program ListingProgram Listing(concluded)(concluded)

[18] [19] // convert height to feet and inches[20] foot = height / 12;[21] inch = height % 12;[22] centimeter = height * IN2CM;[23] [24] // display the output[25] System.out.println("Height of " + foot +[26] " foot " + inch + " in metric is "[27] + centimeter + " cm");[28] }[29] }

Height of 6 foot 2 in metric is 187.96 cm

Page 7: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

CommentsComments

A A single-linesingle-line comment starts with comment starts with the character sequence "//" and the character sequence "//" and continues to the end of the line. continues to the end of the line.

A A multi-linemulti-line comment includes all of comment includes all of the text that is enclosed within the the text that is enclosed within the pair of delimiters "/*" and "*/". pair of delimiters "/*" and "*/".

A third form is a Javadoc comment A third form is a Javadoc comment that creates HTML documentation. that creates HTML documentation.

Page 8: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Keywords and IdentifiersKeywords and Identifiers

KeywordsKeywords are words that have special are words that have special predefined meaning in the Java predefined meaning in the Java language. They may not be used as language. They may not be used as user-defined names. Examples: user-defined names. Examples: classclass, , staticstatic

The name of a class, a method, or a The name of a class, a method, or a variable is called an variable is called an identifieridentifier.. An identifier is a series of characters An identifier is a series of characters

consisting of letters (a...z, A...Z), digits consisting of letters (a...z, A...Z), digits (0...9), underscores ( _), and dollar signs (0...9), underscores ( _), and dollar signs ($) An identifier may not begin with a digit. ($) An identifier may not begin with a digit.

Page 9: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Declaring and Using VariablesDeclaring and Using Variables

A A variablevariable is the program's name for a is the program's name for a memory location that holds data. memory location that holds data.

A variable must have an associated A variable must have an associated type that indicates whether the data is type that indicates whether the data is an integer, a real number, a character, an integer, a real number, a character, or other kind of value. or other kind of value.

int height = 74, foot, inch;double centimeter;

Page 10: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Declaring and Using Variables Declaring and Using Variables (concluded)(concluded)

Java has two kinds of types, primitive Java has two kinds of types, primitive and reference. and reference. A reference type is associated with an A reference type is associated with an

object. The type of an object is a user-object. The type of an object is a user-defined class. defined class.

Primitive types are predefined in the Primitive types are predefined in the Java language and designate variables Java language and designate variables the have simple integer or real number the have simple integer or real number values, character values, or logical values, character values, or logical values (true or false). values (true or false).

Page 11: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Console OutputConsole Output Java provides the predefined stream Java provides the predefined stream

System.out for console output. System.out for console output. Use the stream with methods print and println Use the stream with methods print and println

to display strings and other information in a to display strings and other information in a console window. console window.

The form of the output is provided by a string The form of the output is provided by a string that is built with elements separated by the '+' that is built with elements separated by the '+' character. character.

The elements may include quoted strings The elements may include quoted strings (string literals), variables, and constants. (string literals), variables, and constants.

System.out.println("Height of " + foot + " foot " + inch + " in metric is " + centimeter + " cm");

Page 12: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The Java Programming The Java Programming EnvironmentEnvironment

Programs are initially written as a Programs are initially written as a sequence of Java statements and then sequence of Java statements and then translated by a compiler into translated by a compiler into bytecodebytecode..

To execute the bytecode, Java To execute the bytecode, Java provides an interpreter, called a Java provides an interpreter, called a Java Virtual Machine (JVM) that simulates Virtual Machine (JVM) that simulates the bytecode on the local computer. the bytecode on the local computer.

Page 13: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The Java Programming The Java Programming Environment (continued)Environment (continued)

The most basic environment is a The most basic environment is a command command line environmentline environment that that uses a separate uses a separate application from the Java application from the Java Software Software Development Kit (SDK)Development Kit (SDK) for each task. for each task. To compile the program, use the command To compile the program, use the command

"javac" with a file name that includes the "javac" with a file name that includes the extension ".java". extension ".java".

The command converts the source code into The command converts the source code into intermediate bytecode instructions. intermediate bytecode instructions.

The resulting file has the extension ".class". The resulting file has the extension ".class".

Page 14: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The Java Programming The Java Programming Environment (continued)Environment (continued)

To execute the program, use the To execute the program, use the command "java" with the name of command "java" with the name of the ".class" file. The extension is not the ".class" file. The extension is not included. included.

>javac DemoProgram.javacompiled to "DemoProgram.classcompiled to "DemoProgram.class"

>java DemoProgram

Page 15: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The Java Programming The Java Programming Environment (continued)Environment (continued)

Page 16: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Integrated Development Integrated Development EnvironmentEnvironment

An Integrated Development Environment An Integrated Development Environment (IDE) provides tools to support the entire (IDE) provides tools to support the entire program development and execution program development and execution process.process. The tools include an editor for writing The tools include an editor for writing

programs, debuggers to locate errors, a programs, debuggers to locate errors, a window to display compiler messages, and a window to display compiler messages, and a runtime window to execute the program.runtime window to execute the program. Examples: JBuilder, CodeWarrior, and Examples: JBuilder, CodeWarrior, and

EZJava. EZJava.

Page 17: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Integrated Development Integrated Development Environment (concluded)Environment (concluded)

Page 18: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Primitive Number TypesPrimitive Number Types

Primitive Primitive TypesTypes

Size in BitsSize in Bits RangeRange

bytebyte 8-bit integer8-bit integer -128 to 127 -128 to 127

shortshort 16-bit integer16-bit integer -32768 to 32767 -32768 to 32767

intint 32-bit integer32-bit integer -2,147,483,648 to -2,147,483,648 to 2,147,483,647 2,147,483,647

longlong 64-bit integer64-bit integer (Approx) -9 x 10(Approx) -9 x 101818 to 9 x 10 to 9 x 101818

floatfloat 32-bit real 32-bit real numbernumber

(Approx) -3.4 x10(Approx) -3.4 x103838 to 3.4 to 3.4 x10x103838

doubledouble 64-bit real 64-bit real numbernumber

(Approx) -1.7 x10(Approx) -1.7 x10308308 to to 1.7x101.7x10308308

Page 19: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Declaration of primitiveDeclaration of primitivenumeric variablesnumeric variables

// uninitialized variable of type bytebyte b;// declaration of two int variables; // n is initializedint m, n = 15500;// compiler error; range is -128 to 127byte badByte = 1000;// uninitialized variabledouble slope;// use fixed-point notationdouble x = 14.89;// use floating-point notationdouble y = 2.3e-5;// the literal is a 32-bit floatfloat t = 0.0775f;

Page 20: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java char TypeJava char Type

Character data includes uppercase Character data includes uppercase and lowercase letters, digits, and lowercase letters, digits, punctuation marks, and special punctuation marks, and special symbols.symbols. The Java primitive type The Java primitive type charchar specifies a specifies a

single character. A character literal is a single character. A character literal is a character enclose in single quotation character enclose in single quotation marks.marks.// declare the variables ch and letter// assign letter the character 'A'char ch, letter = 'A'

Page 21: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java char Type (continued)Java char Type (continued)

Java defines a set of Java defines a set of escape sequence escape sequence to represent special characters.to represent special characters.

CharacterCharacter Escape CodeEscape Code

backslashbackslash \\\\

carriage returncarriage return \r\r

double quotedouble quote \"\"

newlinenewline \n\n

tabtab \t\t

Page 22: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java char Type (concluded)Java char Type (concluded)

System.out.println("Source file is \"DemoProgram.java\"");System.out.println("Input c:\\dataIn.dat\n" +

"Output c:\\dataOut.dat");

Output: Source file is "DemoProgram.java"Input c:\dataIn.datOutput c:\dataOut.dat

Page 23: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Declaring NamedDeclaring NamedConstantsConstants

final int LIMIT = 50;final double PI = 3.14159265;final char DELIMITER = ':';

A program often uses a number or string A program often uses a number or string to define a value that should not be to define a value that should not be changed. For instance, circle changed. For instance, circle calculations use the value 3.14159265 calculations use the value 3.14159265 for for .. Create a named constant using the keyword Create a named constant using the keyword

finalfinal followed the declaration format for an followed the declaration format for an initialized primitive variable. initialized primitive variable.

Page 24: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arithmetic OperatorsArithmetic Operators An arithmetic expression combines numeric An arithmetic expression combines numeric

values and operators. values and operators. The familiar binary operators addition (+), The familiar binary operators addition (+),

subtraction (‑), and multiplication (*) apply subtraction (‑), and multiplication (*) apply to both integer and real numbers. to both integer and real numbers.

The unary operator negation (-) changes The unary operator negation (-) changes the sign of the operand.the sign of the operand. With integers, division is in fact long division With integers, division is in fact long division

that evaluates to a quotient and a remainder. that evaluates to a quotient and a remainder. The operator / returns the quotient. The % The operator / returns the quotient. The % operator gives the remainder (25/3=8, operator gives the remainder (25/3=8, 25%3=1).25%3=1).

Page 25: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Assignment OperatorAssignment Operator

Java uses the Java uses the assignment operatorassignment operator = to = to copy the value of an expression on the copy the value of an expression on the right-hand side (rhs) into a variable on right-hand side (rhs) into a variable on the left-hand side (lhs). the left-hand side (lhs).

An assignment statement is terminated An assignment statement is terminated by a semicolon.by a semicolon.

int m, n;m = 8; // rhs is the integer literal 8n = m * 2; // rhs is an expression which evaluates to 16// assigns 25 as value of m and then the value of m to nn = m = 25;

Page 26: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Compound Assignment Compound Assignment Operators Operators

Compound assignment: lhs <op>= rhsSimple assignment: lhs = lhs <op> rhs

Example: Assume m = 14 and n = 3.

m += 5; // m = m + 5; m is 19

n += m - 2; // n = n + (m - 2); n is 15

n *= 2; // n = n * 2; n is 6m /= 5; // m = m / 5; m is 2m %= 5; // m = m % 5; m is

4

Page 27: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Increment and Decrement Increment and Decrement OperatorsOperators

Java provides unary operators ++ and Java provides unary operators ++ and -- for the increment and decrement -- for the increment and decrement operations respectively.operations respectively.

count++;count++; // increment // increment operatoroperator

If the value of count is initially 8 before If the value of count is initially 8 before the statement is executed, the the statement is executed, the resulting value is 9. From initial value 8, resulting value is 9. From initial value 8, the result would be 7;the result would be 7;

count--;count--; // decrement operator// decrement operator

Page 28: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Operator Precedence and Operator Precedence and AssociativityAssociativity

In Java, each operator has a precedence In Java, each operator has a precedence level and the compiler generates code to level and the compiler generates code to execute operators in the order of their execute operators in the order of their precedence.precedence.

int m = 40, n;n = -m + 14 % 4;

First execute negation: n = -40 + 14 % 4 Second execute remainder: = -40 + 2 // 14 % 4 = 2Third execute addition: = -38 // -40 + 2 = -38

Page 29: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Operator PrecedenceOperator Precedenceand Associativity and Associativity

(concluded)(concluded)Level Operator Operation Associativity0 = Assignment R to L1 + Addition L to R - Subtraction L to R2 * Multiplication L to R / Division L to R % Remainder L to R3 + Unary plus R to L - Unary minus R to L

int m = 9, n = 5, p, q;p = q = 4 * m / n;

First execute multiplication: p=q=36/n // 4 * m = 4 * 9 = 36 Second execute division: p=q=7 // 36 / n = 36 / 5 = 7 Third execute assignment (R to L): q = 7 // assign 7 to qFourth execute assignment (R to L): p = q // assign q = 7 to p

Page 30: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Type ConversionsType Conversions Conversions between one primitive type Conversions between one primitive type

and another are classified as and another are classified as widening widening conversionsconversions or or narrowing conversions.narrowing conversions. Widening conversions go from one data type Widening conversions go from one data type

to another that uses the same or more to another that uses the same or more memory space to store the values. memory space to store the values.

Narrowing conversions go from one type to Narrowing conversions go from one type to another that uses a smaller space to store another that uses a smaller space to store values. values.

The result is often a loss of both the The result is often a loss of both the magnitude and precision of the value. magnitude and precision of the value.

The ordering of the widening conversions for The ordering of the widening conversions for numeric types isnumeric types is

byte -> short -> int -> long -> float -> doublebyte -> short -> int -> long -> float -> double

Page 31: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arithmetic promotion occurs automatically.Arithmetic promotion occurs automatically.

A cast is an explicit directive to the compiler A cast is an explicit directive to the compiler indicating that a conversion should occur. indicating that a conversion should occur.

The format for a cast places the desired The format for a cast places the desired type in parentheses in front of the operand type in parentheses in front of the operand which may be variable, literal, or complex which may be variable, literal, or complex expression. expression.

(type)operand

Arithmetic Promotion and Arithmetic Promotion and CastingCasting

4 + 6.5 is evaluated as 4.0 + 6.5 = 10.5

int total = 5;// avg1 = 1, avg2 = 1.25double avg1 = total/4, avg2 = (double)total/4;

Page 32: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Assignment ConversionAssignment Conversion

int m = 15, n = 65;double x;char ch;

x = m; // with widening conversion, x is 15.0ch = (char)n; // explicit casting, ch is 'A'

Assignment conversion occurs when the Assignment conversion occurs when the expression on the right side of an expression on the right side of an assignment statement has a different assignment statement has a different type than the left hand side. type than the left hand side.

Assignment accomplishes only widening Assignment accomplishes only widening conversion from the right-hand side to conversion from the right-hand side to the left-hand side. Otherwise, the right-the left-hand side. Otherwise, the right-hand side must be explicitly cast. hand side must be explicitly cast.

Page 33: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java Comparison OperatorsJava Comparison Operators

Java comparison operators withequivalent math notation

Mathematics Notation: = Java Notation: == Meaning: Equal to Java Example: n % 2 == 0Mathematics Notation: ≠ Java Notation: != Meaning: Not equal to Java Example: response != 'Y'Mathematics Notation: < Java Notation: < Meaning: Less than Java Example: 4 < 6

Page 34: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java ComparisonJava ComparisonOperators (concluded)Operators (concluded)

Mathematics Notation: ≤ Java Notation: <= Meaning: Less than or equal to Java Example: age <= 21Mathematics Notation: > Java Notation: > Meaning: Greater than Java Example: balance > 0Mathematics Notation: ≥ Java Notation: >= Meaning: Greater than or equal to Java Example: ch >= 'A'

Page 35: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Boolean OperatorsBoolean OperatorsLogical Operator Java OperatorAND &&OR ||NOT !

P && Q is true provided both P and Q are true; it is false in all other cases. Example: 'a' <= ch && ch <= 'z' // true if ch is a lowercase letter

P || Q is true if P is true or if Q is true; it is false only when both P and Q are false

Example: n % 2 == 0 || n == 5 // true if n is even or n is 5

!P is the logical opposite of P. It is true when P is false and false when P is true Example: !(n % 5 == 0) // true if n is not divisible by 5

Page 36: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Boolean Operators Boolean Operators (concluded)(concluded)

With With short-circuit evaluation, the , the computer evaluates the operands from computer evaluates the operands from left to right and stops as soon as the left to right and stops as soon as the logical value of the entire expression is logical value of the entire expression is known.known.

In the following expression, the division is not done if x is 0.0.In the following expression, the division is not done if x is 0.0.

x != 0.0 && 20/x < 1

Page 37: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The if-StatementThe if-Statement

A A code block code block is a group of one or more is a group of one or more statements that are combined to carry statements that are combined to carry out a single task. out a single task.

Instructions within the block are set off by Instructions within the block are set off by braces and may contain declarations. braces and may contain declarations.

In the case of a single statement, the In the case of a single statement, the braces may be omitted. braces may be omitted.

A variable declared in a block can only be A variable declared in a block can only be used in the block. We say that the block used in the block. We say that the block defines the defines the scopescope of the variable. of the variable.

Page 38: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The if-Statement The if-Statement (continued)(continued)

The simplest form of an if-statement uses The simplest form of an if-statement uses a logical expression as a condition and a logical expression as a condition and executes code block codeexecutes code block codeTT if the if the expression evaluates to true.expression evaluates to true.

Block Syntax:{

Declarations // declaration of variables Statement1 // sequence of statements

...Statementn

}

Syntax:if (condition)

CodeT

Page 39: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The if-Statement The if-Statement (continued)(continued)

if (m < n){ int temp; // the exchange needs temporary

//storage

temp = m; // hold m in temporary storage m = n; // copy n to m n = temp; // copy original value of m to n}

Page 40: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The if-Statement The if-Statement (continued)(continued) The most common form of an The most common form of an if-statement if-statement has has

the program choose from among two options. the program choose from among two options. The form of the if-statement uses the reserved The form of the if-statement uses the reserved

word word elseelse to designate the second option. to designate the second option. The statement, called an if-else statement, The statement, called an if-else statement,

tests the condition and executes Codetests the condition and executes CodeTT if the if the condition is true and Codecondition is true and CodeFF if it is false. if it is false.

Syntax:Syntax:if (condition)

CodeT // if true, execute this code else

CodeF // if false, execute this code

Page 41: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The if-Statement The if-Statement (continued)(continued)

if (avgScore >= 70) grade = 'P';else grade = 'F';

A course grade is 'P' or 'F' indicating pass A course grade is 'P' or 'F' indicating pass or failure. The instructor passes a student or failure. The instructor passes a student when the average score is 70 or above.when the average score is 70 or above.

Page 42: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Nested if-StatementsNested if-Statements

An if-else statement can contain any sort An if-else statement can contain any sort of statements within its code blocks. of statements within its code blocks.

In particular, it can constitute a nested if-In particular, it can constitute a nested if-statement by placing if-else statements statement by placing if-else statements within the blocks. within the blocks.

Page 43: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Nested if-Statements Nested if-Statements (continued)(continued)

Plywood price (per sheet)Plywood price (per sheet)

UtilitUtilityy

FinisheFinishedd

Quantity 1-Quantity 1-99

12.5012.50 18.7518.75

Quantity Quantity 10+10+

11.2511.25 17.2517.25

• A lumber company prices sheets of plywood A lumber company prices sheets of plywood based on their grade F (finished) or U (utility). based on their grade F (finished) or U (utility). •In addition, the company offers customers a In addition, the company offers customers a reduced price on a sheet if they buy in quantity. reduced price on a sheet if they buy in quantity. •The following table lists the price of a sheet of The following table lists the price of a sheet of plywood based on grade and quantityplywood based on grade and quantity

Page 44: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Nested if-Statements Nested if-Statements (continued)(continued)// first test for the grade; nested if-else

// statements for each grade test the quantityif (grade == 'U') if (quantity < 10) // option: U grade, quantity 1-9 totalCost = n * 12.50; else // option: U grade, quantity 10+ totalCost = n * 11.25;else if (quantity < 10) // option: F grade, quantity 1-9 totalCost = n * 18.75; else // option: F grade, quantity 10+ totalCost = n * 17.25;

Page 45: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Multiway if/else StatementsMultiway if/else Statements

In many applications, we want a In many applications, we want a selection statement to specify branches selection statement to specify branches into a number of different options. into a number of different options.

This can be done with nested if-This can be done with nested if-statements but without indenting to list statements but without indenting to list the choices. the choices.

The format creates a multiway if-else The format creates a multiway if-else statement that better describes how we statement that better describes how we view the options. view the options.

Page 46: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Multiway if/elseMultiway if/elseStatementsStatements

if (avgScore >= 90) grade = 'A';else if (avgScore >= 80) grade = 'B';else if (avgScore >= 70) grade = 'C';else if (avgScore >= 60) grade = 'D';// could be a simple else statementelse if (avgScore < 60) grade = 'F';

Page 47: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Conditional ExpressionConditional ExpressionOperatorOperator

Java provides an alternative to the "if-else" Java provides an alternative to the "if-else" statement using the statement using the conditional expression conditional expression operatoroperator (?:). (?:).

The syntax for the operator requires three The syntax for the operator requires three operands. The first is a boolean expression operands. The first is a boolean expression and the other two are expressions that are and the other two are expressions that are set off with separators "?" and ":" set off with separators "?" and ":" respectively.respectively.

SyntaxSyntax:: condition ? expressioncondition ? expressionTT : expression : expressionFF

Page 48: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Conditional ExpressionConditional ExpressionOperator (concluded)Operator (concluded)

if (x >= y)max = x;

elsemax = y;

max = (x >= y) ? x : y;

equivalent to

Page 49: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The switch-StatementThe switch-Statement

The The switch-statementswitch-statement is a special form is a special formof multiway selection that transfers control of multiway selection that transfers control to one of several statements depending on to one of several statements depending on the value of an integer or character the value of an integer or character expression.expression. If no match occurs, then control passes to the If no match occurs, then control passes to the

defaultdefault label if it exists or to the first statement label if it exists or to the first statement following the switch block. following the switch block.

When a statement sequence concludes, control When a statement sequence concludes, control continues with the next statement sequence. continues with the next statement sequence.

Java provides a Java provides a breakbreak statement, which forces a statement, which forces a branch out of the switch statement. branch out of the switch statement.

Page 50: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The switch-Statement The switch-Statement (continued)(continued)

Syntax:switch (selector expression){

case constant1: Statement for constant1

break;. . . . . .

case constantn: Statement for constantn

break;

default: Statement if no case matches selector break;

}

Page 51: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The switch-Statement The switch-Statement (continued)(continued)

If a break statement is not placed at the end of a case-If a break statement is not placed at the end of a case-option, the runtime system will execute instructions in option, the runtime system will execute instructions in the next case-option.the next case-option.

For instance, assume the example includes no break For instance, assume the example includes no break statements and coinValue is 25.statements and coinValue is 25.

A run would produce output that includes the case 50 A run would produce output that includes the case 50 option and the default option.option and the default option.

Output: Output: 25 cents is a standard coin25 cents is a special coinNo coin for 25 cents

Page 52: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Switch-Statement ExampleSwitch-Statement Exampleswitch(coinValue){ case 1: // Note: two or more case options included with case 5: // a single statement case 10: case 25: System.out.println(coinValue + " cents " + "is a standard coin"); break; case 50: System.out.println(coinValue + " cents " + "is a special coin"); break; default: System.out.println("No coin for " + coin + " cents"); break;}

For coinValue = 25, the output is "25 cents is a standard coin"For coinValue = 50, the output is "50 cents is a special coin"For coinValue = 15, the output is "No coin for 15 cents"

Page 53: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The boolean TypeThe boolean Type

The boolean type is a primitive type like int, The boolean type is a primitive type like int, double, and char. double, and char.

The type has values The type has values truetrue and and falsefalse which can which can be used in program statements. be used in program statements.

Like the other primitive types, you can have Like the other primitive types, you can have constants and variables of boolean type. constants and variables of boolean type.

A variable is typically used as a flag to A variable is typically used as a flag to indicate the status of a condition in an indicate the status of a condition in an algorithm or as a name for a boolean algorithm or as a name for a boolean expression. expression.

Page 54: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The boolean Type The boolean Type (continued)(continued)

final boolean VALID_ID = true;

// isEnrolled is a flag that indicates the// registration status of a student in a course;// The flag is set to false if the student drops// the courseboolean isEnrolled = true;

// variables are names for a boolean expression;// the value of the variable is the value of the// boolean expressionboolean isLowercase = 'a' <= ch && ch <= 'z';boolean onProbation = gpa < 2.0;

boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

Page 55: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The boolean Type The boolean Type (concluded)(concluded)

boolean haveInsufficientFunds = balance < checkAmt;

boolean isSenior = age >= 60;

if (haveInsufficientFunds) fee = 20.00;else if (isSenior) fee = 0.50; else fee = 1.00;

Page 56: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The while LoopThe while Loop

The while statement repeats its action until the The while statement repeats its action until the controlling condition (loop test) becomes false.controlling condition (loop test) becomes false.

Syntax:while (logical expression)body

Sum successive even integers 2 + 4 + 6 + . . . until the total is Sum successive even integers 2 + 4 + 6 + . . . until the total is greater than 250.greater than 250. int i, sum = 0;i = 2; // initial even integer for the sumwhile (sum <= 250) // loop test; check current value of sum {

sum += i; // add integer to sumi += 2; // update i to next even integer

}

Page 57: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The do/while LoopThe do/while Loop The The do/whiledo/while loop is similar to a while loop is similar to a while

loop except that it places the loop test at loop except that it places the loop test at the end of the loop body. the end of the loop body.

A do/while loop executes at least one A do/while loop executes at least one iteration and then continues execution so iteration and then continues execution so long as the test condition remains true. long as the test condition remains true.

Syntax: do {

body } while (logical expression);

Page 58: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The do/while loop The do/while loop (concluded)(concluded)

int count = 10;do{ System.out.print(count + " "); count--; // decrement count}while (count > 0); // repeat until count is 0

System.out.println("Blast Off!!!");

Output: 10 9 8 7 6 5 4 3 2 1 Blast Off!!!

Page 59: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The for LoopThe for Loop

The The for-statementfor-statement is an alternative loop is an alternative loop structure for a counter-controlled while structure for a counter-controlled while statement. statement.

The format of the for-loop has three The format of the for-loop has three separate fields, separated by semicolons. separate fields, separated by semicolons.

The fields enable a programmer to The fields enable a programmer to initialize variables, specify a loop test, initialize variables, specify a loop test, and update values for control variables.and update values for control variables.

Syntax: for (init statement; test condition; update statement)body

Page 60: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The for loop (concluded)The for loop (concluded)

int i, sum = 0;

while LOOP for LOOP ========== ========init: i = 1; for (i = 1; i <= 10; i++)test: while (i <= 10) sum += i; { sum += i;update: i++; }

Page 61: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

The Break StatementThe Break Statement

while (true){ <read data from the file> if (eof) break; <process data from this input>}

Within a loop body, a Within a loop body, a breakbreak statement statement causes immediate exit from the loop to causes immediate exit from the loop to the first statement after the loop body. the first statement after the loop body.

The break allows for an exit at any The break allows for an exit at any intermediate statement in the loop. intermediate statement in the loop.

Syntax: break;

Page 62: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

ArraysArrays An An arrayarray is a fixed-size collection of is a fixed-size collection of

elements of the same data type that occupy elements of the same data type that occupy a block of contiguous memory locations. a block of contiguous memory locations.

Like any other variable, an array declaration Like any other variable, an array declaration includes the name of the array and the data includes the name of the array and the data type for the elements in the sequence. type for the elements in the sequence.

To specify that the variable is an array, add To specify that the variable is an array, add a pair of square brackets immediately after a pair of square brackets immediately after the data type.the data type.

int[] intArr;Time24[] tarr;

Page 63: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued) An array is a different kind of entityAn array is a different kind of entity

called a called a reference variablereference variable. . It contains a value which is a reference It contains a value which is a reference

(address) to the first location in the (address) to the first location in the associated block of memory.associated block of memory. A simple declaration of an array assigns it A simple declaration of an array assigns it

the value the value nullnull. The array does not point to . The array does not point to any actual memory locations.any actual memory locations.

To allocate a block of memory for the array To allocate a block of memory for the array and assign the address of the block to the and assign the address of the block to the array variable, use the array variable, use the new new operator.operator.

Page 64: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued)

The syntax for the new operator includes The syntax for the new operator includes the data type and the number of elements the data type and the number of elements in the array enclosed in square brackets. in the array enclosed in square brackets.

For instance, the following statement For instance, the following statement allocates four integer elements. allocates four integer elements.

intArr = new int[4];

Page 65: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued)

Assume n is the size of the array. Assume n is the size of the array. Access to an individual element in the Access to an individual element in the

array is provided by an index in the range array is provided by an index in the range 0 to n-1. 0 to n-1.

The index denotes the position of the The index denotes the position of the element in the sequence. The element at element in the sequence. The element at index i is denoted by arr[i]. index i is denoted by arr[i].

The sequence of elements in the array isThe sequence of elements in the array isarr[0], arr[1], arr[2],..., arr[n-2], arr[n-1] arr[0], arr[1], arr[2],..., arr[n-2], arr[n-1]

int[] intArr = new int[4]; // array of 4 integerschar[] charArr = new char[80]; // array of 80 charactersdouble[] rainfall = new double[12]; // array of 12 real numbers

Page 66: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued)

For instance, let intArr be an array of For instance, let intArr be an array of four integers 21, 7, 30, and 15. four integers 21, 7, 30, and 15.

The figure displays the sequence as a The figure displays the sequence as a contiguous block of memory with an contiguous block of memory with an index listed below each cell. index listed below each cell.

Page 67: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued) The range of valid indices is 0 to n-1 where n The range of valid indices is 0 to n-1 where n

is the size of the array. is the size of the array. An attempt to access an element outside of An attempt to access an element outside of

the valid index range results in a runtime the valid index range results in a runtime error. error.

Once an array is created, a program may Once an array is created, a program may access its size using the expression access its size using the expression arr.lengtharr.length. .

Java defines length as a variable associated Java defines length as a variable associated with the array. with the array.

Hence, with any array, the valid index range Hence, with any array, the valid index range is 0 to arr.length -1. is 0 to arr.length -1.

Page 68: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued) A loop provides efficient sequential access to A loop provides efficient sequential access to

the elements in an array. the elements in an array. Let the loop control variable serve as an Let the loop control variable serve as an

index. index. For instance, the following statements For instance, the following statements

declare an array arr of 100 integer elements declare an array arr of 100 integer elements and use a for-loop to initialize the array with and use a for-loop to initialize the array with values 1, 2, ..., 100.values 1, 2, ..., 100.

int[] arr = new int[100]; // declare array and allocate space

for (i=0; i < arr.length; i++)arr[i] = i+1;

Page 69: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued) An array can be initialized when it is An array can be initialized when it is

declared. declared. After the array name, use "=" followed by an After the array name, use "=" followed by an

array initializer listarray initializer list which is a comma- which is a comma-separated sequence of values enclosed in separated sequence of values enclosed in braces. braces.

There is no need to use the operator new There is no need to use the operator new since the compiler uses the size of the since the compiler uses the size of the initializer list to allocate memory.initializer list to allocate memory.

int[] intArr = {21, 7, 30, 15};String[] day = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

Page 70: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays (continued)Arrays (continued) Java provides an "enhanced for" Java provides an "enhanced for"

statement that allows for a read-only statement that allows for a read-only scan of an array without using indices. scan of an array without using indices.

The syntax includes a declaration of a The syntax includes a declaration of a variable of the array type and the array variable of the array type and the array name separated by a colon(:).name separated by a colon(:).Syntax: for (Type varName : arrayName)

. . .

int [] intArr = {6, 1, 8, 4, 9}; int sum;

for (int eltValue : intArr)sum += eltValue;

Page 71: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Two-Dimensional ArraysTwo-Dimensional Arrays A two-dimensional array is a table with A two-dimensional array is a table with

access specified by row and column indices. access specified by row and column indices. Rather than using one pair of square brackets Rather than using one pair of square brackets

to denote an array, the two-dimensional to denote an array, the two-dimensional array uses two pairs of brackets. array uses two pairs of brackets.

We often refer to a two-dimensional array of We often refer to a two-dimensional array of numbers as a matrix.numbers as a matrix.

int[][] mat; // declare two-dim reference variable// allocate 8 integer locations in 2 rows, 4 columnsmat = new int[2][4];

Elements of mat are accessed using double-bracket notation

mat[i][j] where 0 <= i < 2, 0 <= j < 4

Page 72: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Two-Dimensional Arrays Two-Dimensional Arrays (continued)(continued)

The following table displays the elements in The following table displays the elements in mat. mat.

Nested for-loops scan the elements and Nested for-loops scan the elements and compute the sum of the elements. compute the sum of the elements.

int row, col, sum = 0;

for (row = 0; row < 2; row++)for (col = 0; col < 4; col++)

sum += mat[row][col];

Page 73: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Two-Dimensional Arrays Two-Dimensional Arrays (continued)(continued)

A program may access an entire row of A program may access an entire row of the matrix using a row index in brackets. the matrix using a row index in brackets.

The resulting structure is a 1-dimensional The resulting structure is a 1-dimensional array.array.// mat[0] is the first row in the matrix.// as a one-dimensional array,// it has an associated length variablecolumnSize = mat[0].length; // value 4

Page 74: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Two-Dimensional Arrays Two-Dimensional Arrays (concluded)(concluded)

Like a one-dimensional array, you can Like a one-dimensional array, you can use an initializer list to allocate a use an initializer list to allocate a matrix with initial values.matrix with initial values.

int[][] mat = { {20, 5, 30, 0}, {-40, 15, 100, 80} };

Page 75: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java MethodsJava Methods

A A methodmethod is a collection of statements is a collection of statements that perform a task. that perform a task.

A method can accept data values, A method can accept data values, carry out calculations, and return a carry out calculations, and return a value. value.

The data values serve as input for the The data values serve as input for the method and the return value is its method and the return value is its output.output.

Page 76: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java Methods (continued)Java Methods (continued) The declaration of a method beginsThe declaration of a method begins

with its signature, which consists of with its signature, which consists of modifiers, a return type, a method modifiers, a return type, a method name, and a parameter list that name, and a parameter list that specifies the formal parameters.specifies the formal parameters.

The code that implements the method is The code that implements the method is a block called the a block called the method body.method body.

modifiers returnType methodName (Type1 var1, Type2 var2, . . .){

// method body}

Page 77: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Java Methods (continued)Java Methods (continued) We are already familiar with the method We are already familiar with the method

main(). main(). The method name is The method name is mainmain and the return and the return

type is void since it does not return a value. type is void since it does not return a value. The parameter list is a single variable The parameter list is a single variable

specifying an array of strings. specifying an array of strings. The method has the modifier "public static" The method has the modifier "public static"

which indicates that it is associated with the which indicates that it is associated with the main application class.main application class.

public static void main(String[] args){

// body is the main program }

Page 78: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Predefined MethodsPredefined Methods

Java provides a collection of methods Java provides a collection of methods that implement familiar that implement familiar mathematical functions for scientific, mathematical functions for scientific, engineering or statistical engineering or statistical calculations. calculations.

The methods are defined in the Math The methods are defined in the Math class.class.

Page 79: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Predefined MethodsPredefined Methods(continued)(continued)

Power Function: // x^y

public static double pow(double x, double y);

Square Root Function:

public static double sqrt(double x);

Trigonometric Functions:

public static double cos(double x);public static double sin(double x);public static double tan(double x);

Page 80: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Predefined MethodsPredefined Methods(continued)(continued)

To access a Java method defined in the To access a Java method defined in the Math class, a calling statement must Math class, a calling statement must access the method using the syntax access the method using the syntax

Math.method(arguments).Math.method(arguments). If not void, the return value may be used If not void, the return value may be used

in an assignment statement or as part of in an assignment statement or as part of an expression. an expression.

Page 81: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Predefined MethodsPredefined Methods(continued)(continued)

// variables for one argument and the return valuedouble a = 4.0, powValue;// call pow() from Math class; integer 3 is promoted to a double.// assign powValue the return value 64.0powValue = Math.pow(a,3);

Page 82: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Predefined MethodsPredefined Methods(concluded)(concluded)

The Math class defines the constant The Math class defines the constant as as the named constant Math.PI. the named constant Math.PI.

A trigonometric function takes an angle in A trigonometric function takes an angle in radians. radians.

The expression (angle * (The expression (angle * (/180)) converts /180)) converts from degrees to radians.from degrees to radians.

double theta = 0.0, angle = 30; System.out.println("cosine of 0 radians is " + Math.cos(theta));System.out.println("sine of 30 degrees is " +

Math.sin(angle*(Math.PI/180));

cosine of 0 radians is 1.0sine of 30 degrees is 0.5

Page 83: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

User Defined MethodsUser Defined Methods

In a method, we provide the return In a method, we provide the return value with a statement that uses the value with a statement that uses the reserved word reserved word returnreturn and the value. and the value.

The data type of the return value The data type of the return value must be compatible with the return must be compatible with the return type in the method header. type in the method header.

The general form of the statement isThe general form of the statement isreturn expression;return expression;

Page 84: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

User Defined Methods User Defined Methods (continued)(continued)

public static double annuity(double principal,double rate, int nyears){ return principal * Math.pow(1+rate,nyears);}

The method annuity() returns the The method annuity() returns the value of an annuity.value of an annuity.

Page 85: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

User Defined Methods User Defined Methods (continued)(continued) A return statement can be used anywhere A return statement can be used anywhere

in the body of the method and causes an in the body of the method and causes an exit from the method with the return value exit from the method with the return value passed back to the calling statement.passed back to the calling statement. When a method has a returnType other than When a method has a returnType other than

void, use a return statement with a return void, use a return statement with a return value.value.

When the method has a void returnType, the When the method has a void returnType, the method will return after the last statement. method will return after the last statement.

You may force a return using the syntax You may force a return using the syntax return;return;

Page 86: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

User Defined Methods User Defined Methods (continued)(continued)

public static void printLabel(String label, String month, int year){ System.out.println(label + " " month + ", " + year);

// a return statement provides explicit exit // from the method; typically we use an implicit // return that occurs after executing the last // statement in the method body return;}

The method printLabel() takes a string The method printLabel() takes a string argument for a label along with string argument for a label along with string and integer arguments for the month and and integer arguments for the month and year and outputs the label and the month year and outputs the label and the month and year separated by a comma (','). and year separated by a comma (',').

Page 87: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

User Defined Methods User Defined Methods (continued)(continued)

// month and year for purchaseString month = "December";int year = 1991;

// principal invested and interest earned per yeardouble principal = 10000.0, interestRate = 0.08, annuityValue;

// number of years for the annuityint nyears = 30;

// call the method and store the return valueannuityValue = annuity(principal, interestRate, nyears);

// output label and a summary description of the annuityprintLabel("Annuity purchased:", month, year);System.out.println("After " + nyears + " years, $" + principal + " at " + interestRate*100 + "% grows to $" + annuityValue);

Page 88: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

User Defined Methods User Defined Methods (continued)(continued)

Annuity purchased: December, 1991After 30 years, $10000.0 at 8.0% grows to $100626.57

Page 89: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method ParametersParameters

A method can include an array among A method can include an array among its formal parameters. its formal parameters.

The format includes the type of the The format includes the type of the elements followed by the symbol "[]" elements followed by the symbol "[]" and the array name.and the array name.

returnType methodName (Type[] arr, ...)

Page 90: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (continued)Parameters (continued)

The method max() returns the largest The method max() returns the largest element in an array of real numbers. element in an array of real numbers.

The method signature includes an The method signature includes an array of type double as a parameter array of type double as a parameter and a return type double.and a return type double.

Page 91: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (continued)Parameters (continued)

public static double max(double[] arr){ // assume arr[0] is largest double maxValue = arr[0];

// scan rest of array and update // maxValue if necessary for (int i = 1; i < arr.length; i++) if (arr[i] > maxValue) maxValue = arr[i];

// return largest value which is maxValue return maxValue;}

Page 92: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (continued)Parameters (continued)

In a declaration of an array, the name is a In a declaration of an array, the name is a reference that designates the address of reference that designates the address of the block of memory that holds the array the block of memory that holds the array elements. When a method has an array elements. When a method has an array parameter, call the method by passing the parameter, call the method by passing the name of an existing array argument. name of an existing array argument.

This has the effect of passing a reference This has the effect of passing a reference to the method identifying the sequence of to the method identifying the sequence of elements.elements.

Page 93: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (continued)Parameters (continued)

int[] arrList = new int[5];

maxValue = max(arrList);

Page 94: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (continued)Parameters (continued)

The algorithm for max() performs a The algorithm for max() performs a read-only scan of the elements. read-only scan of the elements.

It is possible to update the array It is possible to update the array passed to a method. passed to a method.

Since the array parameter is pointing Since the array parameter is pointing at the array allocated in the calling at the array allocated in the calling program, an update modifies this array program, an update modifies this array and the change remains in effect after and the change remains in effect after returning from the method.returning from the method.

Page 95: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (continued)Parameters (continued)

The method maxFirst() finds the largest The method maxFirst() finds the largest element in the tail of an array beginning element in the tail of an array beginning at index start and exchanges it with the at index start and exchanges it with the element at the index start. element at the index start.

The method has no return value.The method has no return value.

Page 96: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (continued)Parameters (continued)

public static void maxFirst(int[] arr, int start){ // maxValue and maxIndex are the value and // location of the largest element that is // identified during a scan of the array int maxValue = arr[start], maxIndex = start, temp;

// scan the tail of the list beginning at index // start+1 and update both maxValue and maxIndex // so that we know the value and location of the // largest element for (int i = start+1; i < arr.length; i++) if (arr[i] > maxValue) { maxValue = arr[i]; maxIndex = i; }

Page 97: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Arrays as Method Arrays as Method Parameters (concluded)Parameters (concluded)

// exchange arr[start] and arr[maxIndex] temp = arr[start]; arr[start] = arr[maxIndex]; arr[maxIndex] = temp;}

Page 98: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Program A.1Program A.1

// main application classpublic class ProgramA_1{ public static void main(String[] args) { int[] intArr = {35, 20, 50, 5, 40, 20, 15, 45}; int i;

// scan first n-1 positions in the array where // n = intArr.length; call maxFirst() to place // largest element from the unsorted tail of // the list into position i for (i = 0; i < intArr.length-1; i++) maxFirst(intArr, i);

Page 99: Data Structures for Java William H. Ford William R. Topp Java Primer Bret Ford © 2005, Prentice Hall

Program A.1 (concluded)Program A.1 (concluded)

// display the sorted array for (i = 0; i < intArr.length; i++) System.out.print(intArr[i] + " "); System.out.println(); }

<include code for maxFirst()>}

Run:50 45 40 35 20 20 15 5