35
Lecture 6: More Java Advanced Programming Techniques Summer 2003

Lecture 6: More Java Advanced Programming Techniques Summer 2003

Embed Size (px)

Citation preview

Page 1: Lecture 6: More Java Advanced Programming Techniques Summer 2003

Lecture 6: More Java

Advanced Programming TechniquesSummer 2003

Page 2: Lecture 6: More Java Advanced Programming Techniques Summer 2003

API

Best reference is online:http://java.sun.com/j2se/1.4/docs/api/

Page 3: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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())

Page 4: Lecture 6: More Java Advanced Programming Techniques Summer 2003

Java procedures are mainly call by reference

This means that procedures can easily alter objects passed to them as parameters.

Page 5: Lecture 6: More Java Advanced Programming Techniques Summer 2003

Building your own exceptions.

Class ArgumentNegativeException extends Exception{};

Page 6: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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;

};….

Page 7: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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)

Page 8: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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.

Page 9: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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.

Page 10: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 11: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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;}

Page 12: Lecture 6: More Java Advanced Programming Techniques Summer 2003

Object

equals(Object e)finalize()hashCode()toString()

Page 13: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 14: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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"};

Page 15: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 16: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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();

}

Page 17: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 18: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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)

Page 19: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 20: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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)

Page 21: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 22: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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)

Page 23: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 24: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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);

Page 25: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

Page 26: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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(...);

Page 27: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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();

Page 28: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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();

Page 29: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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()

Page 30: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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;

Page 31: Lecture 6: More Java Advanced Programming Techniques Summer 2003

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

}

Page 32: Lecture 6: More Java Advanced Programming Techniques Summer 2003

Keyword finally

try { } catch() { { finally { code here runs whether or not catch runs }

Page 33: Lecture 6: More Java Advanced Programming Techniques Summer 2003

Optimization

-O option used to direct compiler to optimize code

Page 34: Lecture 6: More Java Advanced Programming Techniques Summer 2003

JIT

Just-In-Time compilerIf present, can speed things upHow does this work?

Page 35: Lecture 6: More Java Advanced Programming Techniques Summer 2003

What features of Java would you like to talk about?