Download presentation
Presentation is loading. Please wait.
Published byLesley Dawson Modified over 9 years ago
1
Lecture 6: More Java Advanced Programming Techniques Summer 2003
2
API Best reference is online: http://java.sun.com/j2se/1.4/docs/api/
3
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())
4
Java procedures are mainly call by reference This means that procedures can easily alter objects passed to them as parameters.
5
Building your own exceptions. Class ArgumentNegativeException extends Exception{};
6
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; }; ….
7
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)
8
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.
9
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.
10
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
11
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; }
12
Object equals(Object e) finalize() hashCode() toString()
13
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
14
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"};
15
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
16
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(); }
17
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
18
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)
19
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
20
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)
21
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
22
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)
23
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
24
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);
25
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
26
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(...);
27
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(); // New string! toLowerCase(Locale locale); toUpperCase(); toUpperCase(Locale locale); trim();
28
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();
29
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()
30
Useful System Constants final, static, portable? WindowsUnix 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;
31
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 }
32
Keyword finally try { } catch() { { finally { code here runs whether or not catch runs }
33
Optimization -O option used to direct compiler to optimize code
34
JIT Just-In-Time compiler If present, can speed things up How does this work?
35
What features of Java would you like to talk about?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.