15-100 Sections S-V / Fall 2008
Quiz 9 / 5 Questions / 25 Minutes
Quiz Date:  Tue 25-Nov-2008

1.       A “nybble” is 4-bits (half a byte).  If Java had a signed primitive type “nybble” (which it doesn’t, but that does not matter here), the following code would demonstrates overflow.  What, exactly, would it print?
SHOW YOUR WORK!
    nybble n1 = 6;
    nybble n2 = 5;
    nybble n3 = (nybble) (n1 + n2); // overflows!  answer is negative!
    System.out.println(n3);

2.       Very briefly, and according to Horstmann’s style guide….

a.       You should not use switch statements.  Why, precisely (and briefly), does Horstmann say this?

b.       Which should be avoided, instance variables or static variables?

c.       Which is preferable (when applicable), “for” or “foreach” loops?

d.       You should not use “magic numbers”.  What are these?

e.       When is it ok to have a variable named “i"?

3.       Write a method, sortByAbsValue, that uses Arrays.sort to sort an array of Integers by their absolute value (for numbers with the same absolute value, negative values should occur before positive values).  To do this, you must also write a well-chosen class that implements Comparator<Integer>.

4.       List the non-optional methods (including their parameter lists and return types!) of the Iterable<String> and Iterator<String> interfaces, and describe in just a few words what each should do:
(Note:  do not write any code here – just explain!)

a.       Iterable<String> methods:

b.       Iterator<String> methods:

5.       Implement a class named Point with a constructor that takes two doubles, x and y, representing the point (x,y) on the plane.  Implement just enough of this class so the constructor works and so the “natural ordering” of a collection of Points is determined by their distance to the origin (0,0), with closer points coming first, and with ties determined arbitrarily.  Hint:  The distance formula from (x1, y1) to (x2, y2) is given by:
          

class Point implements Comparable {

}

6.       BONUS:  What will the following code print?
    Scanner s = new Scanner("123 456 3251 3521");
    s.useDelimiter("[" + ' ' + ( 2 + 3 ) + "]");
    while (s.hasNext())
      if (s.next().length() == 1)
        System.out.println(s.next());


carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem