600.107 Intro to Programming in Java Tests 2 & 3 The test is worth 200 points total. READ through all questions carefully. Please PRINT answers on the test LEGIBLY. Show all work for partial credit. ------------------------------------------------------------------------------ For the first few questions, assume the following declaration has been made at the beginning of the main class declaration (outside any methods). static Random rand = new Random(); Assuming that ch1 and ch2 are initialized character variables, with ch1 <= ch2 and both upper case, write a statement to put a random character between ch1 and ch2 (inclusive) into a third character variable ch3. [6] ch3 = (char) rand.nextInt(ch2 - ch1 + 1) + ch1; Write the header for a method that could appear in a main driver program which has two character parameters and returns a random upper case letter between those values (inclusive). [3] public static char randUpper(char ch1, char ch2) Write a recursive statement that could be added to the definition of the above method in order to handle the case where the first actual parameter comes later in the alphabet than the second one. You can still assume they are both upper case. [3] return randUpper(ch2, ch1); Write javadoc comments for the method above. [5] /** Generates a random upper case letter in an inclusive range @param ch1 the range lower bound @param ch2 the range upper bound @return the letter generated */ ------------------------------------------------------------------------------- What is the output of the following program? [4] public class finalA { public static void main(String[] args) { int x = 3; int y = 9; method1(x, y); System.out.println("after method1: " + x + " " + y); x = 3; y = 9; x = method2(x, y); System.out.println("after method2: " + x + " " + y); } public static void method1(int x, int y) { x = x + 2; y = x * 10; } public static int method2(int x, int y) { y = y * 2; x = y - 5; return y; } } after method1: 3 9 after method2: 18 9 ------------------------------------------------------------------------------- public static String change(String s) { if (s.length() == 0) return ""; if (s.length() % 2 == 0) return Character.toUpperCase(s.charAt(0)) + change(s.substring(1)); else return Character.toLowerCase(s.charAt(0)) + change(s.substring(1)); } Given the above method definition, what is the output of [2] System.out.println(change("ab")); (C) a) AB b) ab c) Ab d) aB Given the above method definition, what is the output of [3] System.out.println(change("XYZ")); (D) a) XYZ b) xya c) XyZ d) xYz ------------------------------------------------------------------------------- Write a RECURSIVE method called digitSum that calculates the sum of the digits of a long integer. For example, the statement long num = digitSum(1324364757687); would put 1+3+2+4+3+6+4+7+5+7+6+8+7 == 63 into variable num. Hint: the sum does not have to calculated in the order in which it is written here. Your method should work for positive and negative parameters (ignoring the negation). [13] public static long digitSum(long num) { if (num < 0) return digitSum(-num); if (num == 0) return 0; return num % 10 + digitSum(num / 10); } ------------------------------------------------------------------------------- Draw the array puzzle as it appears in memory at the end of this program segment. [8] char [][] puzzle = new char[3][5]; char letter = 'a'; for (i=0; i < 3; i++) for (j=0; j < 5; j++) { puzzle[i][j] = letter; letter = (char) (letter + 1); } a b c d e f g h i j k l m n o ------------------------------------------------------------------------------- Suppose that an array named table looks like this in memory: 1 4 8 16 3 9 15 21 What is the output of this code segment? [4] for (j=3; j >= 0; j -= 2) { for (i=0; i < 2; i++) System.out.print(table[i][j] + " "); System.out.println(); } 16 21 4 9 ------------------------------------------------------------------------------- public class finalRA { public static void main(String[] args) { final int ASIZE = 3; int [] small = {30, 20, 10}; int [] large = new int[ASIZE * 2]; int i, j; for (i=0; i < ASIZE; i++) { large[i] = small[i] / 2; large[i+ASIZE] = i * 2; } for (i=0; i < ASIZE*2; i++) System.out.print(large[i] + " "); System.out.println(); } } What is the output of the above program finalRA? [6] 15 10 5 0 2 4 ------------------------------------------------------------------------------- Complete the missing methods of this class definition, in accordance with the javadoc comment specifications. public class PhoneEntry { private String name; private long cell; private static int entries = 0; // how many entries have been made /** Create a entry by passing data for all the instance members. @param n the name @param c the cell phone (10 digits) */ // [7] public PhoneEntry(String n, long c) { name = n; cell = c; entries++; } /** Get the name of the entry. @return the entry's name */ // [4] public String getName() { return name; } /** Method which reports how many entries have been created. @return the number of entries */ // [5] public static int num() { return entries; } public String toString() { return name + " [" + cell + "]"; } } // end of PhoneEntry class ------------------------------------------------------------------------------- This set of questions are asking you to write statements as they would appear in a main driver program which uses the PhoneEntry class above. Write a general purpose statement to display on the screen how many entry objects have been created. Do not assume anything about any prior variable declarations. [3] System.out.println(PhoneEntry.num()); Write a statement to create a variable called "myself" which creates a PhoneEntry object that has your personal data in it. (If you don't have a cell phone, just make up a number.) [6] PhoneEntry myself = new PhoneEntry("Houlahan", 4105164117); Suppose a PhoneEntry variable named "pe" has already been created and initialized. Write a statement to display the name for that entry on the screen. [3] System.out.println(pe.getName()); Write a statement to create an array called "cellphone" that could hold up to 65 PhoneEntry objects. [6] PhoneEntry[] cellphone = new PhoneEntry[65]; Write a statement to put the "myself" variable from above into the first element of the array created in the previous statement. [3] cellphone[0] = myself; Is the following statement valid? Why or why not? [3] PhoneEntry e = new PhoneEntry(); No, because there is no default constructor. There are two errors in this statement - what are they? [4] System.out.println(cellphone[cellphone.length()]); 1) length is not a method 2) cellphone.length is not a valid index The next few questions refer to the actual PhoneEntry class definition, not a driver program. In order for the following statements to compile, a method must be defined in the PhoneEntry class. What is the exact header of that method? [4] Comparable [] cra = new Comparable[10]; cra[0] = new PhoneEntry("something",3241507896); public int compareTo(Object o) What else must be added to the PhoneEntry class in order for the above statements to compile, and where should it go? [3] implements Comparable after "class PhoneEntry" Write an equals method for the PhoneEntry class which overrides the one in the Object class. Compare entries based on their names and cell numbers, ignoring capitalization. Consider potential parameter problems in how the method might be called (but this does not mean you need to throw or catch exceptions). You do not have to write javadoc comments. [15] public boolean equals(Object o) { if (o instanceof PhoneEntry) { PhoneEntry e = (PhoneEntry) o; return name.equalsIgnoreCase(e.name) && cell == e.cell; } else return false; } ------------------------------------------------------------------------------- True/False - Circle your choice clearly. [9] T True False a) IOException is a checked type of exception. T True False b) NullPointerException is an unchecked type of exception. T True False c) The printStaceTrace() method in the Throwable class is inherited by all exception classes. T True False d) A "finally" block is always executed, regardless of whether or not an exception is thrown (assuming execution control has not been transferred with a return or exit, for example). F True False e) Exceptions are only thrown by statements that are in a "try" block, or are called indirectly from a "try" block. T True False f) Only checked exceptions must be reported or handled in order to avoid compilation errors. T True False g) If the first catch block after a try has a parameter of type Exception, then any following catches will never be executed. T True False h) If a class implements an interface, it must have a definition that matches every method header in the interface. T True False i) If an interface contains data, it is public, static and final by default. ------------------------------------------------------------------------------- public class Parent { private int a; protected double b; public Parent(int x, double y) { a = x; b = y; } public void set(int x) { a = x; } public String toString() { return a + " " + b; } } // end of class Parent ------------------------------------------------------------------------------- Given the Parent class definition above, write the definitions of the methods in the Child class below, based on the brief comments indicating their purpose. (Ask Dr. H if you are unclear as to these method purposes.) public class Child extends Parent { private int c; // x initializes a, y initializes b, z initializes c [3] public Child(int x, double y, int z) { super(x, y); c = z; } // y initializes b, z initializes c [2] public void set(double y, int z) { b = y; c = z; } // descriptor with all data members a, b, c [5] public String toString() { return super.toString() + " " + c; } } // end of class Child ------------------------------------------------------------------------------- Which method in the Child class overloads a method in the Parent class? [2] set Which method in the Child class overrides a method in the Parent class? [2] toString What is the output of the below program finalLAST? [7] p2 is 5 3.2 c2 is 6 .7 -40 For each marked statement below in main, state whether or not it is legal (will compile). Assume that the unmarked statements do compile. Also assume that this program is in the same directory as the Parent and Child class files. public class finalLAST { public static void main(String[] args) { // 8 points total Parent p1, p2 = new Parent(5, 3.2); Child c1, c2 = new Child(6, .7, -40); System.out.println("p2 is " + p2); System.out.println("c2 is " + c2); I c1 = p2; // LEGAL ILLEGAL I c1 = new Parent(13, 23); // LEGAL ILLEGAL L p1 = new Child(5, 10, 15); // LEGAL ILLEGAL I p2.set(4.1, 32); // LEGAL ILLEGAL L c2.set(7); // LEGAL ILLEGAL I c2.a = 8; // LEGAL ILLEGAL L p2.b = 12; // LEGAL ILLEGAL L p2.set(9); // LEGAL ILLEGAL } // main } ------------------------------------------------------------------------------- Multiple choice - indicate answer clearly. 2 points each [34 total] What reserved word is used to refer to the implicit parameter object within an instance method of a class definition? D a) me b) you c) other d) this What method in the Object class makes and returns a copy of an object? B a) copy b) clone c) double d) equals What reserved word indicates that a method does not return a value? C a) public b) static c) void d) private What reserved word is used to protect a class member from direct access outside its class? D a) public b) static c) void d) private Which sorting algorithm is most easily written using recursion? C a) selection b) bubble c) merge d) bucket How slowly will bubble sort and selection sort work (big O number of operations, roughly) on an array of N things, in the worst case? D a) log N b) N c) N log N d) N*N (N-squared) How quickly will a binary search work on a collection of N things, assuming they are in some sort of order already, if the item being searched for is not there? A a) log N b) N c) N log N d) N*N (N-squared) What is the state of this array after the first pass of the outer loop of a (minimum) selection sort, with the goal to make the array in ascending order? ra = {15, 9, 32, 38, 0, 21} D a) ra = {9, 15, 32, 0, 21, 38} b) ra = {0, 15, 9, 32, 38, 21} c) ra = {9, 15, 32, 0, 38, 21} b) ra = {0, 9, 32, 38, 15, 21} What is the state of this array after the first pass of a bubble sort, with the goal to make the array in ascending order? ra = {15, 9, 32, 38, 0, 21} A a) ra = {9, 15, 32, 0, 21, 38} b) ra = {0, 15, 9, 32, 38, 21} c) ra = {9, 15, 32, 0, 38, 21} b) ra = {0, 9, 32, 38, 15, 21} What is the order of the numbers that are examined when doing a binary search on this array for the number 13? ra = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256} A or B a) 16, 2, 8 b) 8, 64, 16 c) 16, 8 d) 0, 1, 2, 4, 8, 16 What is the order of the numbers that are examined when doing a linear search on this array for the number 13? ra = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256} A a) 0, 1, 2, 4, 8, 16, 32, 64, 128, 256 b) 8, 64, 16 c) 0, 1, 2, 4, 8, 16 d) 16, 8 What type of testing requires making sure that every possible execution path gets executed at least once? A a) whitebox b) blackbox c) regression d) unit What type of testing is done without any knowledge of the code being tested, other than what it's supposed to do? B a) whitebox b) blackbox c) regression d) unit Which statement will cause a listing of the method calls open at the time this statement was called to be displayed? B a) throw new InvalidArgument(); b) (new Throwable()).printStackTrace(); c) System.err.println("method calls"); d) System.exit(1); Which statement will cause the program to stop running immediately? D a) throw new InvalidArgument(); b) (new Throwable()).printStackTrace(); c) System.err.println("method calls"); d) System.exit(1); Which word do we use for a method to report or declare that an exception might be thrown? B a) throw b) throws c) try d) catch Which word do we use when we want to put statements that might throw exceptions into a block after which they can be caught? C a) throw b) throws c) try d) finally ------------------------------------------------------------------------------- For each pair of classes, indicate which one is a subclass of the other, or neither if they are not related by inheritance. [3] super Food <--- Bagel sub Blue ---> Color none Table --- Chair -------------------------------------------------------------------------------