CompSci 100E5.1Java String Classÿ String is a class Do not need new to create StringString msg = ”hello”;ÿ Can join strings (concatenate) with + String mail = ”John says ” + msg;ÿ Most common String methods: int length(); // get number of chars in it String substring(int start, int stop);// substring gets part of string int indexOf(String key); // finds loc of key char charAt(int index); // get a single charCompSci 100E5.2String Methodsÿ More on useful String methods Examples. What are the values?String demo = ”How are things?”;demo.substring(8, 12)demo.indexOf(”wa”)demo.indexOf(”w a”)demo.charAt(7); Other common String methodsboolean equals(String s) // equality of contentsint compareTo(String s) // -1, 0, +1 : <, ==, >String substring(int start) // end of string Examples. What are the values?demo.comparetTo(”how are things?”)demo.equals (”how are things?”)demo.substring(10)CompSci 100E5.3Why Inheritance?ÿ Add new shapes easily without changing much code Shape s1 = new Circle(); Shape s2 = new Square();ÿ Interface/abstract base class: interface or abstraction Function called at runtimeÿ concrete subclass All abstract functions implemented Later we'll overrideÿ “is-a” view of inheritance Substitutable for, usable in all cases as-ashapemammalScoreEntryFullHouse, LargeStraightUser’s eye view: think andprogram withabstractions,realizedifferent, but conformingimplementations,don’t commit to somethingconcrete until as late as possibleCompSci 100E5.4Example of Inheritanceÿ What is behavior of a shape?void doShape(Shape s) {System.out.println(s.area());System.out.println(s.perimeter());s.expand(2.0);System.out.println(s.area());System.out.println(s.perimeter());}Shape s1 = new Circle(2);Shape s2 = new Square(4);Shape s3 = new Rectangle(2,5);doShape(s1); doShape(s2); doShape(s3);CompSci 100E5.5Inheritance (language independent)ÿ First view: exploit common interfaces in programming Iterators in Java or C++ Implementation varies while interface stays the sameÿ Second view: share code, factor code into parent class Code in parent class shared by subclasses Subclasses can override inherited methodo Subclasses can override and callÿ Polymorphism/late(runtime) binding (compare: static) Function actually called determined when program runs, notwhen program is compiledCompSci 100E5.6What can an Object do (to itself)?ÿ http://java.sun.com/j2se/1.5.0/docs/api/ Look at java.lang.Objectÿ toString() Used to print (System.out.println) an object, overriding toString() can result in 'useful' information being printed, also used in String concatenation: String s = x + y; Default is basically a pointer-valueÿ equals() Determines if guts of two objects are the same, must override, e.g., for using a.indexOf(o) in ArrayList a Default is ==, pointer equalityÿ hashCode() Hashes object (guts) to value for efficient lookupCompSci 100E5.7Objects and Valuesÿ Primitive variables are boxes think memory location with valueÿ Object variables are labels that are put on boxesString s = new String("genome");String t = new String("genome");if (s == t) {they label the same box}if (s.equals(t)) {contents of boxes thesame}stWhat's in the boxes? "genome" is in the boxesCompSci 100E5.8Objects, Values, Classesÿ For primitive types: int, char, double, boolean Variables have names and are themselves boxes (metaphorically) Two int variables assigned 17 are equal with ==ÿ For object types: String, Sequence, others Variables have names and are labels for boxes If no box assigned, created, then label applied to null Can assign label to existing box (via another label) Can create new box using newÿ Object types are references or pointers or labels to storageCompSci 100E5.9Java Arraysÿ Fixed size, once created Can hold primitive types Can hold objects (references)ÿ Example: Creating an array of doublesdouble[] times;times = new double[30]; // or could combine w prevÿExample: Creating an array of DLicensesDLicense[] dls;dls = new DLicense[50]; // create array (or combine)for (int k; k < dls.length; k++) {dls[k] = new DLicense(); // create objects in dls}CompSci 100E5.10Java Arraysÿ Can also create arrays by specifying initial values Avoids need for new Avoids need to count the number of valuesÿ Example: Creating an array of intsint[] counts = { 3, 12, 0, 8, 10}; Use counts.length to get size of arrayÿ Example: Creating an array of StringsString[] aHotel = {”Hilton”, ”Swans”, ”Astoria”};String[] bHotel = {”Kwik8”, ”SleepyT”, ”TuckUIn”};String[] cHotel = {”DiveX”, ”RRXing”, ”Swampys”};ÿExample: Creating an array of arrays (matrix)String[][] hotelChoice = {aHotel, bHotel, cHotel};CompSci 100E5.11Java ArrayList Classÿ Flexible Arrays Grows in size as needed! Many different methods to improved array processingÿ Create with:ArrayList list = new ArrayList();ÿ Uses: (assume dl, sl, are DLicense objects)list.add(dl); // add to “end” (append)list.add(k, dl); // insert at position k (shifts!)list.set(k, dl); // replace at position k//retrievefrompositionm–notecasttoDLicensesl = (DLicense) list.get(m);CompSci 100E5.12Java ArrayList Classÿ Print out with:(dl is a DLicense object and list an ArrayList of DLicense)for (int k = 0; k < list.size(); k++) {DLicense licns = (Dlicense) list.get(k);System.out.println(licns.getName()+ ””+ licns.getNum());}ÿ Note that brackets []don’t work ! ! ! Also see: o remove(), indexOf(), toArray(), o contains(), size(), ... Look them up in API!CompSci 100E5.13For-Each Loop (new with Java 5)ÿ For Arrays (and Collections) May Use Special Loop Syntaxfor (Type name:expression){body of loop}Typeis the type of object returned for use in loopnameis of variable that take on value for use in loopexpresssionis an array or collectionÿ Example: (list is an ArrayList of Dlicense objects)for (DLicense dl : list) {System.out.println(dl.getName() + ””+ dl.getNum());} But cannot change entries! (effectively dealing with copy)CompSci 100E5.14Java ArrayList Class (Java 5)ÿ Generic forms Previous example stored items as Objects On retrieving, needed to cast back to original classÿ Create with:ArrayList<DLicense> vect = new ArrayList<DLicense>();ÿUse: (assume sl, is a DLicense objects)sl = list.get(m); // get at position m: no cast neededfor (DLicense
View Full Document