Presentation is loading. Please wait.

Presentation is loading. Please wait.

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists.

Similar presentations


Presentation on theme: "Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists."— Presentation transcript:

1 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists

2 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data = new double[10]; When array is created, all values are initialized depending on array type: Numbers: 0 Boolean : false Object References: null Arrays

3 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Arrays

4 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Arrays

5 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Using the value stored: System.out.println("The value of this data item is " + data[4]); Get array length as data.length (Not a method!) Index values range from 0 to length - 1 Accessing a nonexistent element results in a bounds error double[] data = new double[10]; data[10] = 29.95; // ERROR Limitation: Arrays have fixed length Arrays

6 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. new typeName[length] Example: new double[10] Purpose: To construct an array with a given number of elements. Syntax 7.1 Array Construction

7 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. arrayReference[index] Example: data[2] Purpose: To access an element in an array. Syntax 7.2 Array Element Access

8 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What elements does the data array contain after the following statements? double[] data = new double[10]; for (int i = 0; i < data.length; i++) data[i] = i * i; Answer: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, but not 100 Self Check 7.1

9 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What do the following program segments print? Or, if there is an error, describe the error and specify whether it is detected at compile-time or at run-time. a)double[] a = new double[10]; System.out.println(a[0]); b)double[] b = new double[10]; System.out.println(b[10]); c)double[] c; System.out.println(c[0]); Answer: a) 0 b) a run-time error: array index out of bounds c) a compile-time error: c is not initialized Self Check 7.2

10 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. The ArrayList class manages a sequence of objects Can grow and shrink as needed ArrayList class supplies methods for many common tasks, such as inserting and removing elements The ArrayList class is a generic class: ArrayList collects objects of type T : ArrayList accounts = new ArrayList (); accounts.add(new BankAccount(1001)); accounts.add(new BankAccount(1015)); accounts.add(new BankAccount(1022)); size method yields number of elements Array Lists

11 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Use get method Index starts at 0 BankAccount anAccount = accounts.get(2); // gets the third element of the array list Bounds error if index is out of range Most common bounds error: int i = accounts.size(); anAccount = accounts.get(i); // Error //legal index values are 0...i-1 Retrieving Array List Elements

12 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. set overwrites an existing value BankAccount anAccount = new BankAccount(1729); accounts.set(2, anAccount); add adds a new value before the index accounts.add(i, a) Adding Elements Continued

13 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Adding Elements (cont.)

14 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. remove removes an element at an index accounts.remove(i) Removing Elements

15 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: import java.util.ArrayList; 02: 03: /** 04: This program tests the ArrayList class. 05: */ 06: public class ArrayListTester 07: { 08: public static void main(String[] args) 09: { 10: ArrayList accounts 11: = new ArrayList (); 12: accounts.add(new BankAccount(1001)); 13: accounts.add(new BankAccount(1015)); 14: accounts.add(new BankAccount(1729)); 15: accounts.add(1, new BankAccount(1008)); 16: accounts.remove(0); 17: 18: System.out.println("Size: " + accounts.size()); 19: System.out.println("Expected: 3"); 20: BankAccount first = accounts.get(0); ch07/arraylist/ArrayListTester.java Continued

16 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 21: System.out.println("First account number: " 22: + first.getAccountNumber()); 23: System.out.println("Expected: 1015"); 24: BankAccount last = accounts.get(accounts.size() - 1); 25: System.out.println("Last account number: " 26: + last.getAccountNumber()); 27: System.out.println("Expected: 1729"); 28: } 29: } ch07/arraylist/ArrayListTester.java (cont.)

17 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. How do you construct an array of 10 strings? An array list of strings? Answer: new String[10]; new ArrayList (); Self Check 7.3

18 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What is the content of names after the following statements? ArrayList names = new ArrayList (); names.add("A"); names.add(0, "B"); names.add("C"); names.remove(1); Answer: names contains the strings "B" and "C" at positions 0 and 1 Self Check 7.4

19 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. You cannot insert primitive types directly into array lists To treat primitive type values as objects, you must use wrapper classes: ArrayList data = new ArrayList (); data.add(29.95); double x = data.get(0); Wrappers

20 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. There are wrapper classes for all eight primitive types: Wrappers

21 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Auto-boxing: Starting with Java 5.0, conversion between primitive types and the corresponding wrapper classes is automatic. Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95); double x = d; // auto-unboxing; same as double x = d.doubleValue(); Auto-boxing even works inside arithmetic expressions Double e = d + 1; Means: auto-unbox d into a double add 1 auto-box the result into a new Double store a reference to the newly created wrapper object in e Auto-boxing

22 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What is the difference between the types double and Double ? Answer: double is one of the eight primitive types. Double is a class type. Self Check 7.5

23 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Traverses all elements of a collection: double[] data =...; double sum = 0; for (double e : data) // You should read this loop as "for each e in data" { sum = sum + e; } Traditional alternative: double[] data =...; double sum = 0; for (int i = 0; i < data.length; i++) { double e = data[i]; sum = sum + e; } The Generalized for Loop

24 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Works for ArrayLists too: ArrayList accounts =... ; double sum = 0; for (BankAccount a : accounts) { sum = sum + a.getBalance(); } Equivalent to the following ordinary for loop: double sum = 0; for (int i = 0; i < accounts.size(); i++) { BankAccount a = accounts.get(i); sum = sum + a.getBalance(); } The Generalized for Loop

25 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. for (Type variable : collection) statement Example: for (double e : data) sum = sum + e; Purpose: To execute a loop for each element in the collection. In each iteration, the variable is assigned the next element of the collection. Then the statement is executed. Syntax 7.3 The "for each" Loop

26 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Write a "for each" loop that prints all elements in the array data. Answer: for (double x : data) System.out.println(x); Self Check 7.7

27 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why is the "for each" loop not an appropriate shortcut for the following ordinary for loop? for (int i = 0; i < data.length; i++) data[i] = i * i; Answer: The loop writes a value into data[i]. The "for each" loop does not have the index variable i. Self Check 7.8

28 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Check all elements and count the matches until you reach the end of the array list. public class Bank { public int count(double atLeast) { int matches = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) matches++; // Found a match } return matches; }... private ArrayList accounts; } Simple Array Algorithms: Counting Matches

29 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Check all elements until you have found a match. public class Bank { public BankAccount find(int accountNumber) { for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) // Found a match return a; } return null; // No match in the entire array list }... } Simple Array Algorithms: Finding a Value

30 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What does the find method do if there are two bank accounts with a matching account number? Answer: It returns the first match that it finds. Self Check 7.9

31 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. When constructing a two-dimensional array, you specify how many rows and columns you need: final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String[ROWS][COLUMNS]; You access elements with an index pair a[i][j] board[i][j] = "x"; Two-Dimensional Arrays

32 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A Tic-Tac-Toe Board

33 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " "; Traversing Two-Dimensional Arrays

34 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: /** 02: A 3 x 3 tic-tac-toe board. 03: */ 04: public class TicTacToe 05: { 06: /** 07: Constructs an empty board. 08: */ 09: public TicTacToe() 10: { 11: board = new String[ROWS][COLUMNS]; 12: // Fill with spaces 13: for (int i = 0; i < ROWS; i++) 14: for (int j = 0; j < COLUMNS; j++) 15: board[i][j] = " "; 16: } 17: 18: /** 19: Sets a field in the board. The field must be unoccupied. 20: @param i the row index 21: @param j the column index 22: @param player the player ("x" or "o") 23: */ ch07/twodim/TicTacToe.java Continued

35 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 24: public void set(int i, int j, String player) 25: { 26: if (board[i][j].equals(" ")) 27: board[i][j] = player; 28: } 29: 30: /** 31: Creates a string representation of the board, such as 32: |x o| 33: | x | 34: | o| 35: @return the string representation 36: */ 37: public String toString() 38: { 39: String r = ""; 40: for (int i = 0; i < ROWS; i++) 41: { 42: r = r + "|"; 43: for (int j = 0; j < COLUMNS; j++) 44: r = r + board[i][j]; 45: r = r + "|\n"; ch07/twodim/TicTacToe.java (cont.) Continued

36 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 46: } 47: return r; 48: } 49: 50: private String[][] board; 51: private static final int ROWS = 3; 52: private static final int COLUMNS = 3; 53: } ch07/twodim/TicTacToe.java (cont.)

37 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: import java.util.Scanner; 02: 03: /** 04: This program runs a TicTacToe game. It prompts the 05: user to set positions on the board and prints out the 06: result. 07: */ 08: public class TicTacToeRunner 09: { 10: public static void main(String[] args) 11: { 12: Scanner in = new Scanner(System.in); 13: String player = "x"; 14: TicTacToe game = new TicTacToe(); 15: boolean done = false; 16: while (!done) 17: { 18: System.out.print(game.toString()); 19: System.out.print( 20: "Row for " + player + " (-1 to exit): "); 21: int row = in.nextInt(); 22: if (row < 0) done = true; 23: else 24: { ch07/twodim/TicTacToeRunner.java Continued

38 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 25: System.out.print("Column for " + player + ": "); 26: int column = in.nextInt(); 27: game.set(row, column, player); 28: if (player.equals("x")) 29: player = "o"; 30: else 31: player = "x"; 32: } 33: } 34: } 35: } ch07/twodim/TicTacToeRunner.java (cont.)

39 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Output: | Row for x (-1 to exit): 1 Column for x: 2 | | x | | Row for o (-1 to exit): 0 Column for o: 0 |o | | x| | Row for x (-1 to exit): -1 ch07/twodim/TicTacToeRunner.java (cont.)

40 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. How do you declare and initialize a 4-by-4 array of integers? Answer: int[][] array = new int[4][4]; Self Check 7.11

41 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. How do you count the number of spaces in the tic-tac-toe board? Answer: int count = 0; for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) if (board[i][j] == ' ') count++; Self Check 7.12

42 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Copying an array variable yields a second reference to the same array Double[ ] data = new double[10]; // fill array... Double[ ] prices = data; Copying Arrays: Copying Array References

43 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Use clone to make true copy Double[ ] prices = (double[ ]) data.clone(); Copying Arrays: Cloning Arrays

44 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. System.arraycopy(from, fromStart, to, toStart, count); Copying Arrays: Copying Array Elements

45 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x; Adding an Element to an Array

46 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. System.arraycopy(data, i + 1, data, i, data.length - i - 1); Removing an Element from an Array

47 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. If the array is full and you need more space, you can grow the array: Create a new, larger array: double[] newData = new double[2 * data.length]; Copy all elements into the new array: System.arraycopy(data, 0, newData, 0, data.length); Store the reference to the new array in the array variable: data = newData; Growing an Array

48 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Double[ ] newData = new double[2 * data.length] System.arraycopy(data, 0, newData, 0, data.length) Continued Growing an Array

49 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. How do you add or remove elements in the middle of an array list? Answer: Use the insert and remove methods. Self Check 7.13

50 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why do we double the length of the array when it has run out of space rather than increasing it by one element? Answer: Allocating a new array and copying the elements is time-consuming. You wouldn't want to go through the process every time you add an element. Self Check 7.14

51 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. // Don't do this int[] accountNumbers; double[] balances; Make Parallel Arrays into Arrays of Objects

52 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Partially Filled Arrays (cont.)

53 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Save test cases Use saved test cases in subsequent versions A test suite is a set of tests for repeated testing Cycling = bug that is fixed but reappears in later versions Regression testing: repeating previous tests to ensure that known failures of prior versions do not appear in new versions Regression Testing

54 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Suppose you modified the code for a method. Why do you want to repeat tests that already passed with the previous version of the code? Answer: It is possible to introduce errors when modifying code. Self Check 7.15

55 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Suppose a customer of your program finds an error. What action should you take beyond fixing the error? Answer: Add a test case to the test suite that verifies that the error is fixed. Self Check 7.16

56 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why doesn't the BankTester program contain prompts for the inputs? Answer: There is no human user who would see the prompts because input is provided from a file. Self Check 7.17

57 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain Name for a class should be a noun that describes concept Concepts from mathematics: Point Rectangle Ellipse Concepts from real life: BankAccount CashRegister Choosing Classes

58 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Actors (end in -er, -or) – objects do some kinds of work for you Scanner Random // better name: RandomNumberGenerator Utility classes – no objects, only static methods and constants Math Program starters: only have a main method Don't turn actions into classes: Paycheck is a better name than ComputePaycheck Choosing Classes

59 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What is the rule of thumb for finding classes? Answer: Look for nouns in the problem description. Self Check 8.1

60 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Your job is to write a program that plays chess. Might ChessBoard be an appropriate class? How about MovePiece ? Answer: Yes ( ChessBoard ) and no ( MovePiece ). Self Check 8.2

61 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A class should represent a single concept The public interface of a class is cohesive if all of its features are related to the concept that the class represents This class lacks cohesion: public class CashRegister { public void enterPayment(int dollars, int quarters, int dimes, int nickels, int pennies)... public static final double NICKEL_VALUE = 0.05; public static final double DIME_VALUE = 0.1; public static final double QUARTER_VALUE = 0.25;... } Cohesion

62 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. CashRegister, as described above, involves two concepts: cash register and coin Solution: Make two classes: public class Coin { public Coin(double aValue, String aName) {... } public double getValue() {... }... } public class CashRegister { public void enterPayment(int coinCount, Coin coinType) {... }... } Cohesion

63 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A class depends on another if it uses objects of that class CashRegister depends on Coin to determine the value of the payment Coin does not depend on CashRegister High Coupling = many class dependencies Minimize coupling to minimize the impact of interface changes To visualize relationships draw class diagrams UML: Unified Modeling Language. Notation for object-oriented analysis and design Coupling

64 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Coupling

65 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. High and Low Coupling Between Classes

66 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why does the Coin class not depend on the CashRegister class? Answer: None of the coin operations require the CashRegister class. Self Check 8.4

67 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why should coupling be minimized between classes? Answer: If a class doesn't depend on another, it is not affected by interface changes in the other class. Self Check 8.5

68 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Accessor: does not change the state of the implicit parameter double balance = account.getBalance(); Mutator: modifies the object on which it is invoked account.deposit(1000); Immutable class: has no mutator methods (e.g., String ) String name = "John Q. Public"; String uppercased = name.toUpperCase(); // name is not changed It is safe to give out references to objects of immutable classes; no code can modify the object at an unexpected time Accessors, Mutators and Immutable Classes

69 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Is the substring method of the String class an accessor or a mutator? Answer: It is an accessor – calling substring doesn't modify the string on which the method is invoked. In fact, all methods of the String class are accessors. Self Check 8.6

70 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Another example of a side effect is output public void printBalance() // Not recommended { System.out.println("The balance is now $" + balance); } Bad idea: message is in English, and relies on System.out It is best to decouple input/output from the actual work of your classes You should minimize side effects that go beyond modification of the implicit parameter Side Effects

71 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. If a refers to a bank account, then the call a.deposit(100) modifies the bank account object. Is that a side effect? Answer: No – a side effect of a method is any change outside the implicit parameter. Self Check 8.8

72 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Precondition: Requirement that the caller of a method must meet Publish preconditions so the caller won't call methods with bad parameters /** Deposits money into this account. @param amount the amount of money to deposit (Precondition: amount >= 0) */ Typical use: To restrict the parameters of a method To require that a method is only called when the object is in an appropriate state Preconditions Continued

73 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. If precondition is violated, method is not responsible for computing the correct result. It is free to do anything Preconditions (cont.)

74 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Method may throw exception if precondition violated – more in Chapter 11 if (amount < 0) throw new IllegalArgumentException(); balance = balance + amount; Method doesn't have to test for precondition. (Test may be costly) // if this makes the balance negative, it's the caller's fault balance = balance + amount; Preconditions

75 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Method can do an assertion check assert amount >= 0; balance = balance + amount; To enable assertion checking: java -enableassertions MyProg You can turn assertions off after you have tested your program, so that it runs at maximum speed Many beginning programmers silently return to the caller if (amount < 0) return; // Not recommended; hard to debug balance = balance + amount; Preconditions

76 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. assert condition; Example: assert amount >= 0; Purpose: To assert that a condition is fulfilled. If assertion checking is enabled and the condition is false, an assertion error is thrown. Syntax 8.1 Assertion

77 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Condition that is true after a method has completed If method call is in accordance with preconditions, it must ensure that postconditions are valid There are two kinds of postconditions: The return value is computed correctly The object is in a certain state after the method call is completed /** Deposits money into this account. (Postcondition: getBalance() >= 0) @param amount the amount of money to deposit (Precondition: amount >= 0) */ Don't document trivial postconditions that repeat the @return clause Postconditions Continued

78 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. amount <= getBalance() // this is the way to state a postcondition amount <= balance // wrong postcondition formulation Contract: If caller fulfills precondition, method must fulfill postcondition Postconditions (cont.)

79 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why might you want to add a precondition to a method that you provide for other programmers? Answer: Then you don't have to worry about checking for invalid values – it becomes the caller's responsibility. Self Check 8.10

80 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. When you implement a method with a precondition and you notice that the caller did not fulfill the precondition, do you have to notify the caller? Answer: No – you can take any action that is convenient for you. Self Check 8.11

81 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Every method must be in a class A static method is not invoked on an object Why write a method that does not operate on an object? Common reason: encapsulate some computation that involves only numbers. Numbers aren't objects, you can't invoke methods on them. E.g., x.sqrt() can never be legal in Java public class Financial { public static double percentOf(double p, double a) { return (p / 100) * a; } // More financial methods can be added here. } Static Methods Continued

82 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Call with class name instead of object: double tax = Financial.percentOf(taxRate, total); main is static – there aren't any objects yet Static Methods (cont.)

83 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Harry turns in his homework assignment, a program that plays tic- tac-toe. His solution consists of a single class with many static methods. Why is this not an object-oriented solution? Answer: In an object-oriented solution, the main method would construct objects of classes Game, Player, and the like. Most methods would be instance methods that depend on the state of these objects. Self Check 8.13

84 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A static field belongs to the class, not to any object of the class. Also called class field public class BankAccount {... private double balance; private int accountNumber; private static int lastAssignedNumber = 1000; } If lastAssignedNumber was not static, each instance of BankAccount would have its own value of lastAssignedNumber Static Fields Continued

85 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. public BankAccount() { // Generates next account number to be assigned lastAssignedNumber++; // Updates the static field // Assigns field to account number of this bank account accountNumber = lastAssignedNumber; // Sets the instance field } Minimize the use of static fields (static final fields are ok) Static Fields (cont.)

86 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Three ways to initialize: 1.Do nothing. Field is initialized with 0 (for numbers), false (for boolean values), or null (for objects) 2.Use an explicit initializer, such as public class BankAccount {... private static int lastAssignedNumber = 1000; // Executed once, // when class is loaded } 3.Use a static initialization block Static fields should always be declared as private Static Fields Continued

87 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Exception: Static constants, which may be either private or public public class BankAccount {... public static final double OVERDRAFT_FEE = 5; // Refer to it as // BankAccount.OVERDRAFT_FEE } Static Fields (cont.)

88 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A Static Field and Instance Fields

89 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Name two static fields of the System class. Answer: System.in and System.out. Self Check 8.14

90 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Scope of variable: Region of program in which the variable can be accessed Scope of a local variable extends from its declaration to end of the block that encloses it Scope of Local Variables Continued

91 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sometimes the same variable name is used in two methods: public class RectangleTester { public static double area(Rectangle rect) { double r = rect.getWidth() * rect.getHeight(); return r; } public static void main(String[] args) { Rectangle r = new Rectangle(5, 10, 20, 30); double a = area(r); System.out.println(r); } } These variables are independent from each other; their scopes are disjoint Scope of Local Variables (cont.)

92 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Scope of a local variable cannot contain the definition of another variable with the same name Rectangle r = new Rectangle(5, 10, 20, 30); if (x >= 0) { double r = Math.sqrt(x); // Error - can't declare another variable called r here... } Scope of Local Variables Continued

93 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. However, can have local variables with identical names if scopes do not overlap if (x >= 0) { double r = Math.sqrt(x);... } // Scope of r ends here else { Rectangle r = new Rectangle(5, 10, 20, 30); // OK - it is legal to declare another r here... } Scope of Local Variables (cont.)

94 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Private members have class scope: You can access all members in any method of the class Must qualify public members outside scope Math.sqrt harrysChecking.getBalance Inside a method, no need to qualify fields or methods that belong to the same class Scope of Class Members Continued

95 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. An unqualified instance field or method name refers to the this parameter public class BankAccount { public void transfer(double amount, BankAccount other) { withdraw(amount); // i.e., this.withdraw(amount); other.deposit(amount); }... } Scope of Class Members (cont.)

96 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A local variable can shadow a field with the same name Local scope wins over class scope public class Coin {... public double getExchangeValue(double exchangeRate) { double value; // Local variable... return value; } private String name; private double value; // Field with the same name } Overlapping Scope Continued

97 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Access shadowed fields by qualifying them with the this reference value = this.value * exchangeRate; Overlapping Scope (cont.)

98 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Package: Set of related classes To put classes in a package, you must place a line package packageName ; as the first instruction in the source file containing the classes Package name consists of one or more identifiers separated by periods Organizing Related Classes into Packages Continued

99 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. For example, to put the Financial class introduced into a package named com.horstmann.bigjava, the Financial.java file must start as follows: package com.horstmann.bigjava; public class Financial {... } Default package has no name, no package statement Organizing Related Classes into Packages (cont.)

100 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. PackagePurposeSample Class java.lang Language support Math java.util Utilities Random java.io Input and output PrintStream java.awt Abstract Windowing Toolkit Color java.applet Applets Applet java.net Networking Socket java.sql Database Access ResultSet javax.swing Swing user interface JButton org.omg.CORBA Common Object Request Broker Architecture IntHolder Important Packages in the Java Library

101 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. package packageName; Example: package com.horstmann.bigjava; Purpose: To declare that all classes in this file belong to a particular package. Syntax 8.2 Package Specification

102 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Can always use class without importing java.util.Scanner in = new java.util.Scanner(System.in); Tedious to use fully qualified name Import lets you use shorter class name import java.util.Scanner;... Scanner in = new Scanner(System.in) Can import all classes in a package import java.util.*; Never need to import java.lang You don't need to import other classes in the same package Importing Packages

103 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Use packages to avoid name clashes java.util.Timer vs. javax.swing.Timer Package names should be unambiguous Recommendation: start with reversed domain name com.horstmann.bigjava edu.sjsu.cs.walters : for Bertha Walters' classes (walters@cs.sjsu.edu) Path name should match package name com/horstmann/bigjava/Financial.java Package Names and Locating Classes Continued

104 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Path name starts with class path export CLASSPATH =/ home/walters/lib :. set CLASSPATH=c :\ home\walters\lib ;. Class path contains the base directories that may contain package directories Package Names and Locating Classes (cont.)

105 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Which of the following are packages? a.java b.java.lang c.java.util d.java.lang.Math Answer: a.No b.Yes c.Yes d.No Self Check 8.18

106 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Is a Java program without import statements limited to using the default and java.lang packages? Answer: No – you simply use fully qualified names for all other classes, such as java.util.Random and java.awt.Rectangle. Self Check 8.19


Download ppt "Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Seven: Arrays and Array Lists."

Similar presentations


Ads by Google