Lecture 1: Introduction, Basic UNIX

Download Report

Transcript Lecture 1: Introduction, Basic UNIX

Lecture 6: More Java
Advanced Programming
Techniques
Summer 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 Collector
There is no telling when that will
happen
There 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
arguments
super.xxx( ) to call methods of the parent
only 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
runtime
To check whether a certain object is of
a particular class use instanceOf
keyword this
To invoke one method from another in the
same class an object must send a message
to itself
this.methodName( ) does the job
To refer to a field, use this.fieldName
When no ambiguity is possible, this is
optional
private String text;
public Greeting(String text) {
this.text = text;
}
Object
equals(Object e)
finalize()
hashCode()
toString()
Java Arrays
Objects, but not built with new Array
C like syntax
Size must be known at instantiation
Homogeneous (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.java
public 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 Java
Manipulate 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 tree
Like C++ Standard Template Library (STL)
Can grow as necessary
Contain only Objects (reference types)
Heterogeneous
Can be made thread safe (simultaneous
access)
Can be made unmodifiable
List
Like 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)
Set
Like 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 objects
When collection has a natural ordering, Iterator
will respect it
Supports safe remove() of most recent next
StringTokenizer
Like an Iterator for a String
Elements 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)
Map
Table 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 types
char[], 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 contents
Object 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 should
for deep copy, override
Object 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
int
int
int
indexOf(int ch);
indexOf(String str);
indexOf(..., int fromIndex);
lastIndexOf(...);
Methods Returning/Constructing New
Strings
concat(String str);
// Can also use +
replace(char old, char new); // Not in place!
substring(int beginIndex);
// New string!
substring(int beginIndex, int endIndex);
toLowerCase();
toLowerCase(Locale locale);
toUpperCase();
toUpperCase(Locale locale);
trim();
// New string!
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 File
Information about files, not their contents
Constructors
File(String path) or (String path, String name) or
(File dir, String name)
Methods
boolean exists(), isFile(), isDirectory(),
canRead(), canWrite();
long
length(), lastModified();
boolean delete(), mkdir(), mkdirs(),
renameTo(File dest);
String getName(), getParent(), getPath(),
getAbsolutePath()
Useful System Constants
final, static , portable?
File.pathSeparator;
File.separator;
Windows
";"
"\"
Unix
":"
"/”
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 extended
final field can’t be modified
final 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 compiler
If present, can speed things up
How does this work?
What features of Java would you like to
talk about?