Upload
lesley-dawson
View
222
Download
0
Embed Size (px)
Citation preview
Lecture 6: More Java
Advanced Programming TechniquesSummer 2003
API
Best reference is online:http://java.sun.com/j2se/1.4/docs/api/
Garbage Collection
All memory allocated on the heap that is no longer referenced is freed up by the Garbage CollectorThere is no telling when that will happenThere is a way to force garbage collection if needed (System.gc())
Java procedures are mainly call by reference
This means that procedures can easily alter objects passed to them as parameters.
Building your own exceptions.
Class ArgumentNegativeException extends Exception{};
Programming with exceptions.
class Factorial{Public static int compute(int k) throws
ArgumentNegativeException, other exceptions {if (k<0) throw new ArgumentNegativeException();else return 1;
}
(and later in a program)….try { System.out.println (“answer is: “ + Factorial.compute(n));
} catch(ArgumentNegativeException e) {System.err.println(e + “oops”);continue;
};….
super
used to call the parent class's constructor, with arguments if desired, using the syntax super(arg0, arg1, ...). must be the very first line in every constructor unless omitted, in which case it will be automatically inserted without argumentssuper.xxx( ) to call methods of the parentonly goes one level up (no super.super)
Java lacks some C++ features
No templates. But superclass is Object. Could program a stack class with Objects, and then cast into an object of another class.Exception: primitive data types such as int, float are not subclasses of Object. However, there are wrapper classes Integer, Double, etc.No overloading of operators (although function overloading is okay).No i/o operators <<, >>.No general multiple inheritance.
No environment variables in Java
No such thing as environment variables as there are with C/C++ and Unix because this is not OS independent. There’s a system property setting mechanism that accesses properties declared in the command line invocation called System.getProperty()… read about it in the Java documentation.
instanceOf
can upcast and downcast, but wrong cast can cause exceptions during runtimeTo check whether a certain object is of a particular class use instanceOf
keyword thisTo invoke one method from another in the same class an object must send a message to itselfthis.methodName( ) does the jobTo refer to a field, use this.fieldNameWhen no ambiguity is possible, this is optionalprivate String text;public Greeting(String text) { this.text = text;}
Object
equals(Object e)finalize()hashCode()toString()
Java Arrays
Objects, but not built with new ArrayC like syntaxSize must be known at instantiationHomogeneous (all elements of same type)Can contain primitive types
Array Syntax, Idioms// declare & initialize (allocate from heap)
int[] a = new int[3]; // stylish Java
int b[] = new int[6]; // like C, less good
// note scope of i in for loop (like C++)
for (int i = 0; i < a.length; i++)System.out.println(“a[” + i + “] =” + a[i]);
b = a; // a, b reference same array
// old b can be garbage collected
String[] colors={"red","blue","green"};
Command line arguments
class CommandLineArgsDemo.javapublic static void main( String[] args ){
for (int i = 0; i < args.length; i++) System.out.println('|' + args[i] + '|');
} }% java CommandLineArgsDemo foo bar "b q"
|foo| |bar| |b q|
args[0] isn’t program name
Java 2D Arrays
char[][] board = new char[8][8];
for(int y=0; y < board.length; y++) {
for(int x=0; x < board[y].length; x++)
System.out.print(board[x][y]);
System.out.println();
}
Collections in JavaManipulate grouped data as a single object Java provides List, Set, Map add, contains, remove, size, loop over, sort, …Insulate programmer from implementation array, linked list, hash table, balanced binary treeLike C++ Standard Template Library (STL)Can grow as necessaryContain only Objects (reference types)HeterogeneousCan be made thread safe (simultaneous access)Can be made unmodifiable
ListLike an array elements have positions indexed 0…size( )-1 duplicate entries possible
Unlike an array can grow as needed can contain only Objects (heterogeneous) easy to add/delete at any position API independent of implementation
(ArrayList, LinkedList)
SetLike a List can grow as needed can contain only Objects (heterogeneous) easy to add/delete API independent of implementation
(HashSet, TreeSet)
Unlike a List elements have no positions duplicate entries not allowed
Collection API methods (some)int size();boolean add( Object obj );returns true if Collection changes as a
result of the add (it always will for List, may not for Set)
boolean contains( Object obj );to see the rest, study the API (warning: look at List, not List (a GUI class)
Iterator Interface// suppose Collection of Programmer objects
Iterator iter = engineers.iterator();
while (iter.hasNext()) {
Programmer p = (Programmer)iter.next();
p.feed("pizza");
}
Note cast (Programmer) since Collection and Iterator manage anonymous objectsWhen collection has a natural ordering, Iterator will respect itSupports safe remove() of most recent next
StringTokenizer
Like an Iterator for a StringElements are (white space delimited) words
StringTokenizer st =
new StringTokenizer(“now is the time …”);
while (st.hasMoreTokens()) {
String word = st.nextToken();
...
}
Should implement Iterator interface (hasNext, next)
MapTable lookup abstraction void put( Object key, Object value) Object get( Object key) can grow as needed any Objects for key and value
(keys tested for equality with .equals, of course)
API syntax independent of implementation (HashMap, TreeMap)
Iterators for keys, values, (key, value) pairs
Conversions String < > Object
String s = “I am ” + obj;
invokes obj.toString()s = String.valueOf(Object obj);
ditto, and overloaded for primitive typeschar[], boolean, char, int, long, float, double
int Integer.valueOf(String s);
// Integer is wrapper class for int
Integer Integer.parseInt(String s);
Equality (reminder) for objects, == tests pointer, not contentsObject class implements
public boolean equals(Object obj) {
return this == obj; }
public int hashCode(); // probable unique id
String class overrides if (g.equals(“goodbye”)) ... // not ==
if “goodbye”.equals(g)) ... // ok too
Strings hash as they shouldfor deep copy, overrideObject clone() // field by field copy
String matches and searches
boolean equalsIgnoreCase(String anotherString);int compareTo(String anotherString); // +,-,0
boolean startsWith(String prefix);
boolean endsWith(String suffix);
boolean regionMatches(int toffset, String other,
int ooffset, int len);
int indexOf(int ch); int indexOf(String str);int indexOf(..., int fromIndex);int lastIndexOf(...);
Methods Returning/Constructing New Stringsconcat(String str); // Can also use +
replace(char old, char new); // Not in place!
substring(int beginIndex); // New string!substring(int beginIndex, int endIndex);
toLowerCase(); // New string!toLowerCase(Locale locale); toUpperCase();toUpperCase(Locale locale);
trim();
Class StringBuffer
mutable size and content
StringBuffer str = new StringBuffer("World");
str.insert(0, "Jello, ");
str.append("!");
str.setCharAt(0,'H'); // now "Hello, World!"
str.reverse(); // now "!dlroW ,olleH"
String s = str.toString();
public class FileInformation about files, not their contentsConstructors
File(String path) or (String path, String name) or(File dir, String name)
Methodsboolean exists(), isFile(), isDirectory(),
canRead(), canWrite();
long length(), lastModified();
boolean delete(), mkdir(), mkdirs(), renameTo(File dest);
String getName(), getParent(), getPath(), getAbsolutePath()
Useful System Constantsfinal, static , portable?
Windows Unix
File.pathSeparator; ";" ":"
File.separator; "\" "/”
System.getProperty
("line.separator")"\n\r" "\n"
// System.getProperty gets other properties too
public static final FileDescriptor in;
public static final FileDescriptor out;
public static final FileDescriptor err;
Keyword final
final class can’t be extendedfinal field can’t be modifiedfinal method can’t be overrridden
public final class Integer {
public static final int MAX_VALUE; //2147483647
}
Keyword finally
try { } catch() { { finally { code here runs whether or not catch runs }
Optimization
-O option used to direct compiler to optimize code
JIT
Just-In-Time compilerIf present, can speed things upHow does this work?
What features of Java would you like to talk about?