Notes
Slide Show
Outline
1
CS110 Lecture 22
Tuesday, April 20, 2004
  • Announcements
    • hw10 due Thursday, April 22
    • exam next Tuesday, April 27
  • Agenda
    • Questions
    • Error handling (finally)
    • What’s on the exam?
2
RumpelStiltskin
  • Exception examples in a short standalone program
  • The fairy tale: guess my name
  • examples/RumpelStiltskin.java
  • > Java RumpelStiltskin
  • > Java RumpelStiltskin foo
  • > Java RumpelStiltskin foo bar
  • > Java RumpelStiltskin RumpelStiltskin
3
Java RumpelStiltskin
  • Design (pseudocode)
    • If there is no command line argument
    • print usage message
    • end the program


  • Two possible implementation strategies
    • test for args[0], proceed based on test result
    • assume args[0] is there, catch Exception if not
4
Test first strategy
  • if (args.length == 0 ) {
  •    System.out.println(
    •   "usage: java RumpelStiltskin guess");
    • System.exit(0); // leave program gracefully
  • }
    • // continue normal processing
5
Exception strategy
  • try {
  •  System.out.println(”Are you " + args[0] +'?');
  •  rumpelstiltskin.guessName(args[0]);
  •  System.out.println("Yes! How did you guess?");
  •  System.exit(0); // leave program gracefully
  • }
  • // come here right away if there is no args[0]
  • catch (IndexOutOfBoundsException e) {
  •    System.out.println(
    •   "usage: java RumpelStiltskin guess");
    • System.exit(0); // leave program gracefully
  • }
6
java RumpelStiltskin foo
  • sorry - foo is not my name


  • Intentionally generate a NullPointerException,
  • see what the Exception's toString method returns
  • java.lang.NullPointerException


  • Experiment with the printStackTrace() method:
  • BadGuessException
  •         at java.lang.Throwable.<init>(Compiled Code)
  •         at java.lang.Exception.<init>(Compiled Code)
  •         at BadGuessException.<init>(Compiled Code)
  •         at Wizard.guessName(Compiled Code)
  •         at Wizard.makeMischief(Compiled Code)
  •         at RumpelStiltskin.main(Compiled Code)


  • Look for a second command line argument,
  • see what happens if it's not there:
  • java.lang.ArrayIndexOutOfBoundsException: 1
  •         at RumpelStiltskin.main(Compiled Code)


7
Equality
  • In Java, “==” means “two variables have same value”
  • Box and arrow pictures help:
    • same value for primitive types is just what you expect
    • same value for reference types: arrow points to the same Object
  • In Object
    • public boolean equals(Object o) {
    •    return this == o;
    • }
  • Override equals when you have a better idea about what equality should mean
8
Equals in AbstractList.java
  • public boolean equals(Object o) {
  • if (o == this)
  •     return true;
  • if (!(o instanceof List))
  •     return false;


  • ListIterator e1 = listIterator();
  • ListIterator e2 = ((List) o).listIterator();
  • while(e1.hasNext() && e2.hasNext()) {
  •     Object o1 = e1.next();
  •     Object o2 = e2.next();
  •     if (!(o1==null ? o2==null : o1.equals(o2)))
  •   return false;
  • }
  • return !(e1.hasNext() || e2.hasNext());
  • }
9
How ArrayLists work
  • private Object elementData[];


  • private int size;


  • public ArrayList() {
  • this(10);
  • }
  • public boolean add(Object o) {
  • ensureCapacity(size + 1);
  •   elementData[size++] = o;
  • return true;
  • }


10
How ArrayLists grow
  •  public void ensureCapacity(int minCapacity) {
  • int oldCapacity = elementData.length;
  • if (minCapacity > oldCapacity) {
  •     Object oldData[] = elementData;
  •     int newCapacity = (oldCapacity * 3)/2 + 1;
  •     if (newCapacity < minCapacity)
  •     newCapacity = minCapacity;
  •     elementData = new Object[newCapacity];
  •     System.arraycopy(oldData, 0, elementData,    0, size);
  • }
  • }


11
hw10
  • Test scripts
  • Error handling for all shell commands
  • Error handling to register and login
  • Count fraction of Juno that’s there for error handling (class Profile)
12
Characters
  • Type char is primitive in Java
  • A char is really an int
  • In the old days characters were just small integers
  • The ASCII character set contains 128 characters numbered 0-127
  • one byte, 8 bits: 00000000 to 11111111 in binary     (0-255 decimal)
  • ascii codes are the bytes with the high bit 0
  •  Googling for ASCII code will find lots of information


13
Characters (continued)
  • Printable characters are 32-126 (decimal) – other bytes are
    • visible in emacs (look at a class file)
    • used for emacs commands, like ^S
  • To represent them in Java use escape character: \
  • ‘\ddd’  // ddd is base 8 number < 256
  • System.out.println(‘\007’); //ring bell
  • ‘\n’, ‘\b’, ‘\t’, ‘\”’, ‘\\’
  • See Escape.java in joi/examples/



14
Unicode
  • Unicode extends character set to 16 bits (0 to 216-1)               for kanji, Arabic, Hebrew, mathematics, …
  • Type char in Java really is a 16 bit int
  • We usually write these values as hexadecimal strings:  16 bits is four hex digits
  • ‘\uXXXX’ (X = 0, 1, …, 9, A, … , F)
  • Internationalization (I18N)
    • locale
    • collation sequence
    • time, date, number format
15
class Character
  • Wrapper class for primitive type char
  • Static methods to process char values
  • Use Character to save  char in a Collection
  • Character(char ch) // constructor
  • public char charValue()
  • static int getNumericValue(char ch) // unicode value
  • static boolean isDigit(char ch)
  • static char toUpperCase(char ch)
  • … see API for more
16
Strings ...
  • The String API - lots there to use when needed
    • constructors
    • equality
    • comparisons
    • substrings
    • character contents
    • changing String contents (not)
  • Read (some of) String.java
17
String constructors
  • String s;
  • s = “hello”; //common and convenient
  • s = new String(“hello”);
  • char[ ] charArray = {‘O’, ‘K’} ;                        s = new String( charArray );
  • String t = new String(s);
18
String matches and searches
  • boolean equals(String anotherString);
  • boolean equalsIgnoreCase(String anotherString);


  • int compareTo(String anotherString); // +,-,0


  • boolean startsWith(String prefix);
  • boolean endsWith(String suffix);


  • int indexOf(int ch);
  • int indexOf(String str);
  • int indexOf(..., int fromIndex);
  • int lastIndexOf(...);