DOC PREVIEW
DREXEL CS 265 - 2

This preview shows page 1-2-17-18-19-35-36 out of 36 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 36 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Lecture 6: More JavaAPIGarbage CollectionJava procedures are mainly call by referenceBuilding your own exceptions.Programming with exceptions. superJava lacks some C++ featuresNo environment variables in JavaSlide 10instanceOfkeyword thisObjectJava ArraysArray Syntax, IdiomsCommand line argumentsJava 2D ArraysCollections in JavaListSetCollection API methods (some)Iterator InterfaceStringTokenizerMapConversions String < > ObjectEquality (reminder) String matches and searchesMethods Returning/Constructing New StringsClass StringBuffer public class FileUseful System Constants final, static , portable?Keyword finalKeyword finallyOptimizationJITSlide 36Lecture 6: More JavaAdvanced Programming TechniquesAPIBest reference is online:http://docs.oracle.com/javase/7/docs/api/index.html➢Generated by JavadocGarbage CollectionAll 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 referenceThis 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;};….superused 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++ featuresNo overloading of operators (although function overloading is okay).No i/o operators <<, >>.No general multiple inheritance.Jave does have something cooler, though: the InterfaceMultiple inheritance is messyNo environment variables in JavaNo 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.Generics (templates)New with Java 5Mechanism is a little different than the templateAllows containers to hold Objects, and first-class typesinstanceOf can upcast and downcast, but wrong cast can cause exceptions during runtimeTo check whether a certain object is of a particular class use instanceOfkeyword 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;}Objectequals(Object e)finalize()hashCode()toString()Java ArraysObjects, but not built with new ArrayC like syntaxSize must be known at instantiationHomogeneous (all elements of same type)Can contain primitive typesArray Syntax, Idioms// declare & initialize (allocate from heap)int[] a = new int[3]; // stylish Javaint 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 collectedString[] colors={"red","blue","green"};Command line argumentsclass 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 nameJava 2D Arrayschar[][] 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 unmodifiableListLike an array elements have positions indexed 0…size( )-1duplicate entries possibleUnlike 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 allowedCollection 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 nextStringTokenizerLike an Iterator for a StringElements are (white space delimited) wordsStringTokenizer 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) pairsConversions String < > ObjectString s = “I am ” + obj; invokes obj.toString()s = String.valueOf(Object obj); ditto, and overloaded for primitive


View Full Document

DREXEL CS 265 - 2

Download 2
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view 2 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view 2 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?