FIT9131
Week 6
1
Programming Foundations FIT9131
Documentation, identity, equality, more collections
Week 6
FIT9131
Week 6
Lecture outline
• class documentation • javadoc
• object identity vs. object equality • Java Strings
• Iterators
• Fixed-size Arrays
• conditional operator
2
FIT9131
Week 6
Review : Class documentation
• The Java standard library documentation shows details about all classes in the library.
• This is called the Java API (Application Programming Interface) documentation.
• The documentation is readable in a Web browser.
• Provides an interface description for all library
classes
3
FIT9131
Week 6
Interface vs. Implementation
The documentation includes:
• the name of the class;
• a general description of the class;
• a list of constructors and methods;
• return value types and parameters for constructors and methods;
• a description of the purpose of each constructor and method.
describes the interface of the class
4
FIT9131
Week 6
Interface vs. Implementation
The documentation does not include :
• private fields (fields are typically private) • private methods
• the bodies (source code) for each method
does not describe the implementation of the class
5
FIT9131
Week 6
Writing class documentation
• It is important to document your code.
• Your own classes should be documented in the
same way as the Java library classes.
• Important : other people should be able to use your class without reading/knowing the implementation.
• Make your class to be just like a ‘library class’! The aim is to make your class as re-usable as possible – and not just for use in the current program you are writing.
6
FIT9131
Week 6
Elements of documentation
Documentation for a class should include at least:
• theclassname
• acommentdescribingtheoverallpurposeand characteristics of the class
• aversionnumber
• theauthors’names
• documentationforeachconstructorandeach method
7
FIT9131
Week 6
Elements of documentation
The documentation for each method (and also each constructor) should include:
• the name of the method
• thereturntype
• theparameternamesandtypes
• a description of the purpose and function of the method
• a description of each parameter
• a description of the value returned
8
FIT9131
Week 6
Start of comment
section. Eg :
Javadoc
Javadoc is a tool (a document generator) to automate
the generation of Java documentation.
Documentation comments are enclosed by /** … */ These consist of a main description followed by a “tag”
Example of a Class comment
/**
* The Responder class represents a response
* generator object. It is used to generate an
* automatic response.
*
* @author
* @version
*/
Michael Kölling and David J. Barnes 1.0 (30.Mar.2006)
End of comment
Tags
Tags’ values
9
FIT9131
Week 6
Javadoc
Method comment:
/**
(contd.)
Main description
Tags
* Read a line of text from standard input (the text
* terminal), and return it as a set of words. *
* @param prompt A prompt to print to screen.
* @return An ArrayList set of Strings, where each
Example of a Method comment
10
*
*/
public ArrayList
… }
String is one of the words typed by the user
FIT9131 Week 6
Overall project details (
BlueJ
)
ReadMe file
11
FIT9131 Week 6
Using
BlueJ
to generate documentation
12
FIT9131 Week 6
Sample
Javadoc
output from BlueJ
13
FIT9131
Week 6
Toggling between
Document/
SourceCode
view
In the BlueJ code editor, you can easily toggle between the Document view and the Source Code view
14
Source Code view
Document view
FIT9131 Week 6
Object : Identity vs. Equality
:Person :Person
15
“Fred”
person1 person2
person1 == person2 ?
“Jill”
FIT9131 Week 6
Object : Identity vs. Equality
:Person :Person
16
“Fred”
person1 person2
person1 == person2 ?
“Fred”
FIT9131
Week 6
Object : Identity vs. Equality
:Person :Person
“Fred”
“Fred”
person1
This is really NOT the correct way to compare 2 strings!!!
person1.getName() == person2.getName() ? (assuming Person class has a getName() accessor method)
person2
17
FIT9131
Week 6
Object : Identity vs. Equality
:Person :Person
18
“Fred”
person1 person2
person1 == person2 ? person1 == person3 ?
person3
“Fred”
FIT9131 Week 6
Comparing two
String
s
A java String is an object. Comparing two Strings for equality using the == operator compares the reference variables, i.e. the memory locations, for equality. The only way they will be equal is if they are the same location in memory, i.e. the same object.
If you want to compare the content of two Strings to see if they are the same, you should use the equals method of the String class.
The same rule applies to any two objects. If you write a class, and you want to compare the state (eg. the name attribute of a Person class) of the two objects of that class, you need to write an equals method for the class.
19
FIT9131
Week 6
20
String equality
if(input == “bye”) {
… }
if(input.equals(“bye”))
{
… }
tests equality
✓
tests identity
Strings should always be compared using the equals method. The String class also has an equalsIgnoreCase method.
FIT9131
Week 6
Identity vs. equality (Strings)
String input = reader.getInput(); if (input == “bye”)
{
…
}
This example is from the InputReader class in the tech-support project from the textbook (Chapter05)
== tests identity
:String == input
:String ?
“bye”
“bye”
21
FIT9131
Week 6
Identity vs. equality (Strings)
String input = reader.getInput();
if (input.equals(“bye”))
{
22
… }
✓
equals
input
:String
:String
?
equals tests equality
“bye”
“bye”
FIT9131
Week 6
Eg :
public void changingString()
{
String greeting = “Hello there”; System.out.println(greeting.toUpperCase()); System.out.println(greeting);
Strings are immutable
JavaStringsareimmutable. AStringnever changes its value. A method that appears to change a String (e.g. toUpperCase) actually creates a new temporary String that looks like the original in upper case, but the original is unchanged.
}
What will be displayed on the screen?
23
FIT9131
Week 6
Example: Building a string using a loop
// this works, but is rather inefficient
public void showLine(int numberOfStars)
{
String line = “”;
for (int counter = 0; counter < numberOfStars;
counter++)
line = line + "*";
System.out.println(line);
}
24
How many temporary Strings are created here?
FIT9131
Week 6
Example : Changing a string (more efficient way)
public String changingString(String aString) {
StringBuffer buffer = new StringBuffer(aString); // modify the StringBuffer object here...
...
return buffer.toString(); }
Strings can be converted to StringBuffers and vice versa. It is often more efficient to use a StringBuffer, especially when you are going to append things to it.
25
FIT9131 Week 6
Example: Building a string (more efficient way) again
public void showLineWithStringBuffer(int numberOfStars) {
String line = "";
StringBuffer buffer = new StringBuffer(line);
for (int counter = 0; counter < numberOfStars;
counter++)
buffer.append("*"); System.out.println(buffer);
}
26
This is more efficient than the previous example. Why?
FIT9131
Week 6
Removing spaces from a string
This is from the InputReader class in the tech-support project from the textbook (Chapter05)
The leading and trailing spaces can be easily removed from a string:
String input = console.getInput(); input = input.trim();
These can be merged into a single line of code :
String input = console.getInput().trim();
27
FIT9131
Week 6
Test : Changing the case of characters in a string
Write a line of code that will get a line of input from the user, removes the leading and trailing spaces and also changes it to lower case. Hint : use the line of code on the previous slide as a starting point.
String input =
28
FIT9131
Week 6
Examples : Validating a
• If a String is supposed to be numeric (e.g. a phone number or a postcode), you need to check that each character is a numeric character (i.e. between '0' and '9').
• If a String is not supposed to be blank (where a blank String is either empty or full of space characters), you could check each character to see if they are all spaces.
• Unfortunately the String class does not provide methods to do these checks.
String
29
FIT9131 Week 6
Example:
stringNumeric
method
public boolean stringNumeric(String aString) {
if (aString.length() == 0)
return false;
int position = 0;
while (position < aString.length()) {
char thisCharacter = aString.charAt(position);
if (thisCharacter < '0' || thisCharacter > ‘9’)
return false; position++;
}
return true; }
30
FIT9131
Week 6
Revision : loops and collections
Loop statements allow a block of statements to be repeated.
• The while loop allows the repetition to be controlled by a boolean expression.
• The for loop offers an alternative to while loops when the number of repetitions is known.
• The for-each loop allows iteration over a whole collection.
• All collection classes provide a special object known as an Iterator, that provides sequential access to the whole collection.
31
FIT9131
Week 6
and
32
iterator
• Collections (eg. ArrayLists) have an iterator()
method.
• Calling this method returns an Iterator object.
• An Iterator
•E next()
•void remove()
Iterator
()
FIT9131
Week 6
Iterating using an
An iterator object can be used to perform looping over a Collection. Eg :
• The iterator method of ArrayList, like all collections, returns an iterator object.
• A while loop performs the iteration. • The iterator object keeps track of the
position in the list.
To use the iterator object we need to import the Iterator class:
import java.util.Iterator;
iterator
object
33
FIT9131
Week 6
Using an
Iterator
object
java.util.Iterator returns an Iterator object
Iterator
while (it.hasNext()) {
call it.next() to get the next object
do something with that object
}
General Syntax
public void listAllFiles() {
Iterator
FIT9131
Week 6
Other Collections
(non
• Apart from the ArrayList we discussed before, Java also provides other collections. Two of the more commonly used ones are :
• HashMaps : collections that contain pairs of objects. Pairs consist of a key and a value.
• HashSets : collections that store each individual element at most once (ie. no duplicates).
• These specialised collections are often used to implement specific types of data, Eg. A Map can be used to implement a Telephone Book, where each “pair” consists of a name and a corresponding tel#.
35
–
examinable topics)
FIT9131 Week 6
Collection comparisons
Collection
Strengths
Limitations
Example usages
ArrayList
A sequence of elements in order of insertion
Slow to search, slow to add/remove arbitrary elements.
List of accounts; waiting line; the lines of a file.
HashSet
A set of unique elements that is fast to search
Does not have indexes; cannot retrieve arbitrary elements from it.
Unique words in a book; lottery ticket numbers
HashMap
A group of associations between pairs of “key” and “value” objects.
Not a general- purpose collection; cannot easily map backward from a value to its key.
Word counting; phone book.
36
From: “Building Java Programs”, by Regges & Stepp
FIT9131
Week 6
Conditional operator
public String toString() {
conditional operator
return name + ” ” + age + ” ”
+ (isStudent ? “Student” : “Not a student”);
}
condition consequent alternative
? : is called the conditional operator. All three parts (condition, consequent, alternative) must be present.
Its returned value can be used like any other returned value. How does this compare to the if statement?
37
FIT9131
Week 6
An equivalent IF example
public String toString() {
condition
consequent
}
return name + ” ” + age + ” Not a student”);
alternative
if (isStudent)
return name + ” ” + age + ” Student”;
else
This does the same thing as the version using the conditional operator, but the code is longer.
38
FIT9131
Week 6
Common Scanner input error
Problems may occur when using nextLine() in conjunction with nextInt() from the Scanner class.
For example, when the following code was executed:
int age = console.nextInt();
String name = console.nextLine(); System.out.println(age + “, ” + name);
with the following input from the keyboard:
77
the following output will be produced:
77,
39
What happened to the name?
FIT9131
Week 6
What was the problem?
7
7
\n
H
e
l
e
…
To Java, the input is a long buffer of characters:
nextInt removes the characters corresponding to a number, and that is all. The newline character (‘\n’) is not removed from the buffer.
nextLine looks for the next newline character (‘\n’), and returns everything before the first one it finds, in this example it will return an empty string.
age = 77
\n
H
e
l
e
n
\n
…
H
e
l
e
n
\n
…
…
40
name = “”
FIT9131
Week 6
41
Some possible solutions
• use nextLine() to get all input (this will remove the newline character properly)
• for this approach, the inputs may need to be converted back to the correct format, eg. to int’s if arithmetic operations are needed.
• so the previous example would become :
String
nextLine()
int age = console.nextInt();
String name = console.nextLine();
System.out.println(age + “, ” + name);
// obviously, this only works if we do not intend // to perform any calculations on the age
FIT9131
Week 6
Some possible solutions
• use a dummy nextLine() to explicitly remove the newline character, before the next real input statement. In other words, use an extra nextLine() statement, but don’t store the input for it.
• so the previous example would become :
int age = console.nextInt(); console.nextLine();
String name = console.nextLine(); System.out.println(age + “, ” + name);
a dummy getLine() (note that the result is not assigned to anything)
42
FIT9131
Week 6
The
The auction project (Chapter04 from textbook) provides further illustration of collections and iteration … and some other concepts.
A field that has not explicitly been initialised will contain the special value null by default.
We can test if an object variable holds the null variable. If it does, it is not a valid object, and must not be used!!
43
auction
project
FIT9131
Week 6
Special value :
• Used with object types.
• Used to indicate : ”no object”.
• We can test if an object variable holds the null value, Eg :
if (highestBid == null) …
• if successful, this test indicates ‘there is no bid yet’, since the highestBid object does not exist.
null
44
FIT9131
Week 6
“Anonymous” objects
• Objects are often created and handed on elsewhere immediately:
Lot furtherLot = new Lot(…); lots.add(furtherLot);
• If we don’t really need the object furtherLot after this, we could have achieved the same effect using an anonymous object:
lots.add(new Lot(…)); anonymous object (an object with no name)
45
FIT9131
Week 6
Fixed
Sometimes the maximum collection size is known in advance.
Modern programming languages often offer a special fixed-size collection type: an array.
The elements in an array are held in a fixed number of contiguous memory locations.
Arrays behave in a similar way to ArrayLists, but use a different syntax.
46
–
size collections
FIT9131
Week 6
Arrays vs. ArrayLists
Access to items in arrays is often more efficient than access to items in comparable flexible-size collections.
Arrays can store objects OR primitive type values, whereas ArrayLists can store only objects.
47
Arrays have a special syntax (using [ ]) which is different from the usual Java expressions (including the ArrayList).
FIT9131
Week 6
Syntax : Creating an array object
Supposing we want to create an attribute, of type array, to hold up to 5 integers :
public class ArrayDemo
{
private int[] numbers; …;
public ArrayDemo()
{
numbers = new int[5]; …
} …
Array object declaration Array object creation
Which of these 2 statements do you think allocates the actual memory space for the array?
48
}
FIT9131
Week 6
The
(name of the array variable) numbers
array (logical view)
numbers
English explanation of the above:
0 1
(contents of the array variable) 2 3 4 (indices of the array elements)
numbers is an array of integers, which can store a maximum of 5 elements. Each individual element can be accessed using an index, which ranges from 0 to 4. The indices must be integers.
49
FIT9131
Week 6
Syntax for using an array
A special “square-bracket” notation is used to access an array element. This applies for both assigning values to the array and retrieving values from the array.
Eg : numbers[2] means: “the third element in the array whose name is numbers”
(NB. the index starts from 0)
50
FIT9131
Week 6
Assigning values to an array
Array elements are accessed just like ordinary variables. Eg :
• to assign a value to each of the elements : numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 99;
note the use of the square
brackets to indicate the note the use of the indices use of an array to refer to the elements
numbers
10
20
30
40
99
51
01234
FIT9131
Week 6
Retrieving values from an array
Eg :
• to access the individual array elements:
numbers[3] = numbers[1] + 5;
numbers[4] = -5;
result = numbers[2];
results
numbers
30
10
20
30
25
-5
52
01234
FIT9131
Week 6
Arrays and Loops
Loops are often used to manipulate arrays.
For instance, to initialize an array :
this is a special value which represents the size of an array
for (int index = 0; index < numbers.length; index++) numbers[index] = 0; // sets all elements to 0
numbers
0
0
0
0
0
53
01234
FIT9131
Week 6
More Array Example : The
project
A Web server records details of each access.
We can analyse this data to determine information such as:
• Most popular pages.
• Busiest periods.
• How much data is being delivered. • Broken references.
The weblog-analyzer project (textbook Chapter04) counts accesses made in each one-hour period over 24 hours during the duration covered by the log.
weblog
54
analyzer
-