C212 - Final Exam - questions
What does the array list names contain after the following statements? ArrayList<String> names = new ArrayList<String>(); names.add("Bob"); names.add(0, "Ann"); names.remove(1); // thanks to skmonsey for catching this names.add("Cal");
"ann", "cal"
Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java? (a) BankAccount account = new SavingsAccount(); (b) SavingsAccount account2 = new BankAccount(); (c) BankAccount account = null; (d) SavingsAccount account2 = account; For (d) assume account is defined of type BankAccount.
(a) BankAccount account = new SavingsAccount();
Do linked lists take more storage space than arrays of the same size?
1) A linked list needs store the neighboring node references, which are not needed in an array. 2) Overhead for storing several objects in linked list, where an array is just one.
for (int n = 10; n >= 0; n--) System.out.println(n);
11: 10 9 8 7 6 5 4 3 2 1
How many solutions are there altogether for the four queens problem?
2: where a and it's mirror image b
What is the value of the reverse Polish notation expression 2 3 4 + 5 * *?
70
W hat does this code print? Queue<String> q = new LinkedList<>(); q.add("A"); q.add("B"); q.add("C"); while (q.size() > 0) { System.out.print (q.remove() + " " ); }
A B C
rule of thumb for finding classes
A class should represent a single concept from a problem domain, such as business, science, or mathematics
What is a hash function? What is a good hash function?
A hash function computes an integer value from an object, a food one mins collisions - identical hashcodes for different objects
What is the difference between a set and a map?
A set stores elems, a map stores associations between keys and values.
substring method of the String class
Accessor - calling substring doesn't modify the string on which the method is invoked. Also all methods of the String class are accessors
What action should you take beyond fixing a error?
Add a test case to the test suit that verifies that the error is fixed
Arrays and lists remember the order in which you added elements, sets do not. Why would you want to use a set instead of an array or list?
Adding and removing elems as well as testing for membership is more efficient with sets
What is the design purpose of the Comparable interface?
Allows objects of your class to be compared ex: sort() methods
How can you accidentally replicate instance variables from the superclass?
Because a subclass has no access to the private instance variables of the superclass
accessing instance variables in static methods directly
Can go wrong when operate on an object, there is no implicit parameter, and one cannot directly access any instance variables
Why can't the Arrays.sort method sort an array of Rectangle objects?
Class does not implement the Comparable interface
coin toss with the Random class (or the Math.random() method)
Compute generator.nextInt(2) and use 0 for heads, 1 for tails, or the other way around.
simulate the picking of a random playing card?
Compute generator.nextInt(4) and associate the numbers 0 ... 3 with the four suits. Then compute generator.nextInt(13) and associate the numbers 0 ... 12 with Jack, Ace, 2 ... 10, Queen, and King.
Why wouldn't you want to use a stack to manage print jobs?
Cuz if you sent it to the printer first, it would be the last thing to be printed
Why wouldn't you want to use an array list for implementing a queue?
Depending on whether you consider the 0 pos the head of tail of the queue, you would want to remove or add at that pos
Encrypt CAESAR using the Caesar cipher
FDHVDU
debugger vs. trace a program by hand?
For short programs, you certainly could. But when programs get longer, it would be very time-consuming to trace them manually.
How large does n need to be so that (1/2)n^2 is bigger than (5/2) * n - 3
If n = 4, then (1/2)n^2 = 8 and (5/2) * n - 3 = 7
What's wrong with this? System.out.println("Enter values, Q to quit: "); do { double value = in.nextDouble(); sum = sum + value; count++; } while (in.hasNextDouble());
If the user doesn't provide any numeric input, the first call to in.nextDouble() will fail
How do you convert Strings to numbers in Java?
Integer.partInt / Double.parseDouble to get num value
What is a Map<String, HashSet<String>>? Give a possible use for such a structure.
It associates string with sets of strings, thesaurus
How do you find all keys and values in a map?
Iterate through the key set and find the values that correspond to the keys for (String key : game.getKey()) { Process key and players.get(key) }
Write a loop that removes all strings with length less than four from a linked list of strings called words.
ListIterator<String> iter - words.iteraror(); while (iter.hasNext()) { String str = iter.next(); if (str.length() < 4) {iter.remove(); } }
Write a loop that prints every second element of a linked list of strings called words.
ListIterator<String> iter = words.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); if (iter.hasNext()) { iter.next(); // Skip next elem } }
Suppose you want to track how many times each word occurs in a document. Declare a suitable map variable.
Map<String, Integer> wordFrequency * not int, as you can't use prim types as params in java
Math class static variables
Math.pi
static method
Method not invoked on an object
Why is the collection of the values of a map not a set?
Might have duplicates
When designing a program how do you decide what classes you will need in your program?
Nouns + concepts of problem domain = possible classes
You are implementing a system to manage a library, keeping track of which books are checked out by whom. Should the Book class aggregate Patron or the other way around?
Patron aggregates Book, unless the lib really wants to know who has the book, in which case Book gets Patron
Your input file contains a sequence of numbers, but sometimes a value is not available and is marked as N/A. How can you read the numbers and skip over the markers?
REad them as strings, and conver those strings to numbers that are not equal to N/A String input = in.next(); if ( !input.equals("N/A")) { double value = Double.parseDouble(input); Process value) }
Why are set iterators different from list iterators?
Sets do not have an ordering, so it doesn't/t make sense to add an elem at a particular iterator pos, or to traverse a set backwards.
find the position of the last space in a string?
Start the loop at the end of the string: boolean found = false; int i = str.length() - 1; while ( !found && i > 0) { char ch = str.charAt(i); if (ch == ' ') { found = true; } else { i--; } }
array called words that can hold ten elements of type String
String[] words = new String[10]
array containing two strings, "Yes" and "No"
String[] words = {"Yes", "No"}
System class static variables
System.in and System.out
Will the following code fragment compile? Will it run? If not, what error is reported? Object obj = "Who was the inventor of Java?"; Question q = (Question) obj; q.display(); Assume Question is something reasonable (for example as designed in the text in chapter 9, p. 426).
The code will compile, but the second line will throw a class cast exception because Question is not a superclass of String
public static double average(double[] values) Why should it not be defined as an instance method
The method needs no data of any object. The only requirement input is the values argument
Why is the collection of the keys of a map a set and not a list?
The ordering does not matter & no duplicates
Will the following code fragment compile? Will it run? If not, what error is reported? Object obj = "Hello"; System.out.println(obj.length());
The second line will not compile, the class Object does not have a method length
Why does a timer require a listener object?
The timer needs to call some method whenever the time interval expires. It calls the actionPerformed method of the listener object.
Assuming that x is an object reference, what is the value of x instanceof Object?
The value is false if x is null and true otherwise
Why don't we simply store all objects in variables of type Object?
There are only a few methods that can be invoked on variables of type object
Why do the format methods return String objects instead of directly printing to System.out?
This design decision reduces coupling. It enables us to reuse the classes when we want to show the invoice in a dialog box or on a webpage.
Why would you want to declare a variable as Queue<String> q = new LinkedList<>() instead of simply declaring it as a linked list?
This was we can ensure that only queue operations can be involed on the q object
Can you compare floating point numbers by subtraction? How about integers?
Yes integers. You cannot compare floating-point values by subtraction, instead must use Double.compare.
Can you add an element to a set at an iterator position? Explain why or why not.
You cannon add an element to a set at an iterator position
Can you convert from an interface type to a class type?
You must cast to convert an interface type to an class type
enhanced for loop vs. basic for loop
an enhanced 4 loop may be shorter, but it cannot have the index i with values[i]
permutations of the word beat?
b followed by the six permissions of eat, e followed bat, a followed by six permissions of bet, and t followed by the six permissions of bea
Which of the following are packages? (a) java (b) java.lang (c) java.util (d) java.lang.Math?
b) java.lang c) java.util
Why is ArrayIndexOutOfBoundsException no a checked exception?
becasue programers should simply check that their array index values are valid,
Why does System.out.println(System.out); produce a result such as java.io.PrintStream@7a84e4
because the implementor of the PrintStream class did not supply a toString method
static variable
belongs to the class, not to any object of the class
print all positive values in an array separated by commas
boolean first = true; for (int 1 = 0; i < values.length; i++) { if (values[i] > 0)) { if (first { first = false; } else { System.out.print(", "); } System.out.println(Values[i]); }
Why should coupling be minimized between classes?
dependency between classes bad, as a change in will affect others.
Write a loop that prints all elements that are in both Set<String> s and Set<String> t.
for (String str : s) { if (t.contains(str)) { S.o.p(str); } }
8 x 8 array for a board game: int[][] board = new int[8][8]; Using two nested loops, initialize the board so that zeroes and ones alternate, as on a checkerboard: 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0
for (int 1 = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { board[i][j] = i * j) % 2; } }
generate a random floating-point number >= 0 and < 100?
generator.nextDouble() * 100.0
How do you check that two objects belong to the same class (even if you don't know the name of the class)?
if (getClass() != otherObject.getClass() { return false; }
Why don't we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }
if all elements of values are negative, then the result is incorrectly computed to 0
criterion of cohesion for a class's public interface
if all of its features are related to the concept that the class represents
loop that counts how many elements in an array are equal to zero
int count = 0; for (double x : values) { if (x == 0 ){ count ++ } }
do loop that reads integers and computes their sum. Stop when reading the value 0.
int x = 0; int previous; do { previous = x; x = in.nextInt(); sum = mum + x; } while (x != 0 && previous != x) ;
Explain: the Character class has methods for classifying characters
isDifit, isLetter, isUppercase etc.
Suppose the input contains the characters Hello, world! What are the values of world and input after this code fragment? String word = in.next(); String input = in.nextLine();
word = "Hello" input = "World!"
Math.sqrt(2) resolved through dynamic method lookup
ya can't you fool. This is a static method of the Math class, there is no implicit param object that could be used to dynamically look it up
Can you have two dimensional arrays with variable row lengths in Java? If no, explain why. If yes, give an example.
yes .
Suppose Java didn't have a do loop. Could you rewrite any do loop as a while loop?
yes, do while do {body} while {condition} = boolean first = true; while (first || condition) { body; first = false; }
Suppose you need to look through 1,000,000 records to find a telephone number. How many records do you expect to search before finding the number?
~ 500,000
whats wrong with: ArrayList<String> names; names.add("Bob");
the names variable has not be initialized
Why don't we need iterators with arrays?
we can simply access each array elements with an integer index