These questions are representative of the ones that will be on the final exam. We will select around 10% to 20% of them for the exam. Note that we will possibly tweak the questions a little so some may not be not identical.
Here are the resources you should use for studying in addition to these sample questions:
The source code from the class demonstrations which you can find here: https://github.com/Cosi-12b
The complete set of slides from class: https://drive.google.com/a/brandeis.edu/folderview?id=0B2SSgva8RXyFNDdTY2hFeDNNRG8&usp=sharing
- Abstract classes can have constructors
- It is possible for an interface to have more than one constructor
- It is possible for a class to have more than one constructor
int
andInteger
are both examples of primitive values- You can instantiate a new instance of an interface
- Interfaces can
extend
other interfaces - An abstract class can implement more than one interface
- A class can extend at most two other classes
- A method that returns a value of type
boolean
must always return eithertrue
orfalse
- A method that returns a value of type
Integer
must always return a valid number - In general,
for
loops should be preferred overwhile
loops - An immutable object is an object that cannot be changed after it is created.
- Abstract classes can have main methods.
- A non-static variable is associated with the class as a whole rather than with specific instances of a class.
- Non-static variables take on unique values with each object instance.
- An object may implement multiple abstract classes
Object
is the supertype of all classes- Three sequential for loops will always run faster than three nested for loops
- A
LinkedList
has faster insertion time than anArrayList
- A
LinkedList
has faster access time for arbitrary indexes than anArrayList
You want to store information about ZIP codes in states. Specifically, you want to be able to lookup which state a particular ZIP code is in. Assume that ZIP codes are stored as int
egers, and that states are stored as String
s. Which data structure should you use?
List<String>
Map<String, Integer>
Map<Integer, String>
Set<Integer>
You want to store all the moves two players have currently made within a Chess game. Assume that a move is represented via the Move
class. Which data structure should you use?
Move[]
Map<Integer, Move>
Set<Move>
List<Move>
You want to write code to figure out how many unique lines there are in a particular file. Which data structure should you use?
String[]
List<String>
Set<String>
Map<String, String>
You want to store information about ZIP codes and states. You want to be able to get all of the ZIP codes within a given state. Assume that ZIP codes are int
s and states are String
s. Which data structure should you use?
Set<String>
Map<String, List<Integer>>
List<Map<String, Integer>>
Map<List<Integer>, String>
You want to store information about professors and departments. A department has multiple professors, and a professor may work in multiple departments. You want to be able to get all of the professors inside of a department. Assume that professors are represented by the Professor
class and departments are represented by the Department
class. Which data structure should you use?
Map<Department, Professor>
Map<Department, List<Professor>>
Map<List<Professor>, Department>
Map<Department, Set<Professor>>
Which of the following statements is false?
- A
Set
is an interface - Proper implementations of
Set
cannot contain duplicates - A
HashSet
is an implementation ofSet
- One can assume that a
Set
'siterator
will return items in some order
Which of the following statements is true?
- A
Map
can have duplicate keys - A
Map
can mapString
s to primitive types - A
Map
can have duplicate values - A
Map
does not have to have a proper ordering
You are designing an application to hold a list of orders for a particular product. You expect orders to be quickly added or canceled. Which class implementing List
should you use to store the orders?
LinkedList<Order>
ArrayList<Order>
List<Order>
Stack<Order>
You are designing an application to hold a collection of documents, and each document has a sequential ID number starting from 0. You need to be able to retrieve an item based on its ID. Which data structure should you use?
LinkedList<Order>
HashSet<Order>
ArrayList<Order>
Deque<Order>
In designing a simple game, you want to keep track of a score count integer for each user, with all users identified by a unique username. Which of the following data structures would you use for keeping track of scores?
Map<String,Integer>
Map<Integer,String>
List<String>
Map<List<String>,Integer>
What is a binary search tree?
- An acyclic binary tree, organized so that all the values contained in a left subtree are less than the values contained in the right subtree.
- A Java built-in class used for storing binary data
- None of the above
What is a stack?
- A data structure that imlements a last-in first-out (LIFO) access pattern
- A data structure that implements a first-in first-out (FIFO) access pattern
- None of the above
What is a Queue?
- A data structure that imlements a last-in first-out (LIFO) access pattern
- A data structure that implements a first-in first-out (FIFO) access pattern
- A data structure that allows an indefinite number of entries
- A data structure for short-lived information
What is an ArrayList
?
- A list that contains arrays
- A Java class that implements a variable length list
- An array that contains lists
- A Java collection that is used to store for very large multi dimenstional arrays efficiently.
The following method below should calculate the number of times a character "x" appears in a string. Select the line that will make the program function correctly.
public int countX(String s) {
if (s.length() == 0)
return 0;
if (s.charAt(0) == 'x')
MISSING LINE
return countX(s.substring(1));
}
return 1 + s.substring(1);
return countX(s.substring(1)) + 1;
return countX(s) + 1;
return countX(s.substring(1));
The following method should move all lowercase "x" characters to the end of the string, such that the string hxexllo
becomes helloxx
. Select the line that will make the program function correctly.
public String endX(String s) {
if (s.length() == 0)
return "";
if (s.charAt(0) == 'x')
return endX(s.substring(1)) + "x";
MISSING LINE
}
return endX(s.substring(0, 1)) + s.substring(1);
return s.charAt(0) + endX(s.substring(1));
return endX(s.substring(1));
return s + endX(s.substring(1));
Consider the following method:
public static void mystery3(int n) {
if (n <= 0) {
System.out.print("*");
} else if (n % 2 == 0) {
System.out.print("("); mystery3(n - 1); System.out.print(")");
} else {
System.out.print("["); mystery3(n - 1); System.out.print("]");
}
}
For each of the following calls, indicate the output that is produced by the method:
- mystery3(0);
- mystery3(1);
- mystery3(2);
- mystery3(4);
- mystery3(5);
Consider the following method:
public static int mystery4(int x, int y) {
if (x < y) {
return x;
} else {
return mystery4(x - y, y);
}
}
For each of the following calls, indicate the value that is returned:
mystery4(6, 13);
:mystery4(14, 10);
:mystery4(37, 10);
:mystery4(8, 2);
:mystery4(50, 7);
:
True or false: any recursive algorithm can be rewritten as a non-recursive algorithm.
Consider the following tree node class:
class TreeNode {
private TreeNode left;
private TreeNode right;
private int value;
public TreeNode(TreeNode left, TreeNode right, int value) {
this.left = left;
this.right = right;
this.value = value;
}
public void print() {
if (left != null) left.print();
System.out.println(value);
if (right != null) right.print();
}
}
What is the output (newlines replaced with commas) of the following code?
TreeNode tn = new TreeNode(null, null, 3);
TreeNode tn1 = new TreeNode(null, null, 5);
TreeNode tn2 = new TreeNode(tn, tn1, 8);
TreeNode tn3 = new TreeNode(null, null, 10);
TreeNode tn4 = new TreeNode(tn2, tn3, 9);
tn4.print();
3, 8, 5, 9, 10
8, 3, 5, 9, 10
5, 3, 8, 9, 10
10, 9, 8, 5, 3
In the code below, the hasChild(int val)
method is supposed to determine if a particular tree node has value == val
or if any of its children have value = val
. Select the correct code for the missing line.
class TreeNode {
private TreeNode left;
private TreeNode right;
private int value;
public TreeNode(TreeNode left, TreeNode right, int value) {
this.left = left;
this.right = right;
this.value = value;
}
public boolean hasChild(int val) {
if (value == val)
return true;
MISSING LINE
return false;
}
}
if (left.hasChild(val) == right.hasChild(val)) return true;
if (left.hasChild(val - 1) && right.hasChild(val + 1)) return true;
if (! (left.hasChild(val) || right.hasChild(val)) ) return false;
if (left.hasChild(val) || right.hasChild(val)) return true;
In the code below, the hasEvenOdd(int val)
method is supposed to return true
if every even node (a node with an even value) has only odd children and if every odd node (a node with an odd value) has only even children, and should return false
otherwise. Select the correct missing line.
class TreeNode {
private TreeNode left;
private TreeNode right;
private int value;
public TreeNode(TreeNode left, TreeNode right, int value) {
this.left = left;
this.right = right;
this.value = value;
}
public boolean isEvenOdd() {
if (left != null && left.value % 2 == value % 2)
return false;
if (right != null && right.value % 2 == value % 2)
return false;
MISSING LINE
}
}
return ((left == null || left.isEvenOdd()) && (right == null || right.isEvenOdd()));
return ((left != null && left.isEvenOdd()) && (right != null && right.isEvenOdd()));
return (left != null || right != null) && (left.isEvenOdd() || right.isEvenOdd());
return left.value % 2 == right.value % 2;
A tree is balanced if the left and right subtrees' heights differ by at most one, and both the left and right subtrees are themselves balanced. For example, these three trees are balanced:
a
/ \
b f
/ \ / \
c d e g
a
/ \
b f
/ \ /
c d e
a
/ \
f b
/ \
c d
... but this tree is not:
a
/ \
b f
/ \
c d
/
e
Which statement is true?
- It is easier to search an unbalanced binary tree because more values are concentrated in specific branches
- It is easier to search a balanced binary tree because each decision eliminates more possibilities
- It takes the same amount of time to search a tree regardless of if the tree is balanced or not
- None of the above
What is the output of the following program, replacing newlines with commas?
class Test {
public static boolean f1() {
System.out.println("hello");
return false;
}
public static boolean f2() {
System.out.println("world");
return true;
}
public static void main(String[] args) {
System.out.println(f1() && f2());
}
}
hello, true
hello, world, true
world, true
hello, false
What is the output of the following program, replacing newlines with commas?
class Test {
public static boolean f1() {
System.out.println("hello");
return false;
}
public static boolean f2() {
System.out.println("world");
return true;
}
public static void main(String[] args) {
System.out.println(f1() || f2());
}
}
hello, true
hello, world, true
world, true
hello, false
What is the output of the following code?
class Test {
public static void main(String[] args) {
ArrayList<Integer> hi = new ArrayList<Integer>();
hi.add(1); hi.add(2);
for (int i : hi) {
hi.add(2);
}
}
}
- The list will contain
1
,2
- The list will contain
1
,2
,2
,2
- The list will contain
1
,2
,2
- None of the above
What does the following code print out?
import java.util.*;
public class Test{
public static void main(String[] args){
Deeue<String> queue = new LinkedList<String>();
queue.add("first");
queue.add("second");
queue.remove();
queue.add("third");
System.out.println(queue.remove());
}
}
- first
- second
- third
- System will throw an exception
What does the following code print out?
public class Test{
public static void main(String[] args){
int x = 0;
for(int i = 0; i< 5; i++){
for(int j = 3; j< i; j++){
for(int k = 0; k< 3*j-2; k++){
x += 1;
}
}
}
System.out.println(x);
}
}
- 3
- 7
- 8
- 9
What does the following code print out?
public class Test{
public static void main(String[] args){
Deque<Integer> que = new LinkedList<Integer>();
Deque<Integer> stac = new LinkedList<Integer>();
for(int i = 10; i>=0 ; i--){
if(i%2==0){
que.add(i);
}else{
stac.push(i);
}
}
que.remove();
for(int i = 0; i<3; i++){
stac.push(que.remove());
}
System.out.println(stac.pop());
}
}
- 4
- 7
- 9
- System will throw an exception
You have an object x
of type Example
, with field y
, which is of type HashMap<String,ArrayList<String>>
, as shown here:
public class Example{
public HashMap<String,ArrayList<String>> y;
public Example(){
y = new HashMap<Integer,ArrayList<String>>();
y.put(1,new ArrayList<String>());
}
}
public class Test{
public static void main(String[] args){
Example x = new Example();
}
}
Which of the following lines, executed in the Test class above, will place a string "Hello" into one of the ArrayLists in x?
- x.y.get(1).put(1,"Hello");
- y.get(1).add("Hello");
- x.y.get(1).add("Hello");
- x.y.put(1,"Hello");
Consider the following code:
public class Example {
public static int x = 1;
public int y = 1;
public int[] z = {1};
public void increment(int i){
x++;
y++;
z[0]++;
i++;
}
public int returnSum(){
return x + y + z[0];
}
public static void main(String[] args){
int i = 0;
Example m = new Example();
System.out.println(m.returnSum());
m.increment(i);
System.out.println(m.returnSum());
Example n = new Example();
System.out.println(n.returnSum());
n.increment(i);
System.out.println(m.returnSum());
System.out.println(i);
}
}
What is the correct output?
- 4, 7, 5, 8, 1
- 3, 6, 4, 7, 0
- 2, 8, 4, 5, 2
- None of the above
Consider the following method:
public boolean mystery1 (int num) {
return (num % 3 == 0 && num % 5 != 0);
}
What does this method do?
- Determines whether a number is a multiple of 15.
- Determines whether a number is a multiple of 3 or 5, but not both.
- Determines whether a number is a multiple of 3, but not a multiple of 5.
- Determines whether a number is a multiple of 5, but not a multiple of 3.
Consider the following code:
public String mystery2(int num) {
String s = "";
for (int i = 1; i < num; i++) {
s += Integer.toString(i) + ", ";
}
s += Integer.toString(num);
return s;
}
What would be the String returned by calling mystery2(5)
?
- 1 2 3 4 5
- 5 4 3 2 1
- 1, 2, 3, 4, 5
- 5, 4, 3, 2, 1
Consider the following code:
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<String, Integer>();
for(int i = 0; i < 10; i++) {
m.put("key + i", i);
}
}
Which statement is true?
- The key 3 has value 3, and the size of
m.keySet()
is 1 - The key 3 has value 3, and the size of
m.keySet()
is 10 - The key 3 is not in the map, and the size of
m.keySet()
is 1 - None of the above
Consider the following code:
public class Exam {
private int score;
private String courseName;
private double gradeWeight;
public Exam(int s, String cN, double gW) {
this.score = s;
this.courseName = cN;
this.gradeWeight = gW;
}
public int getScore() { return this.score; }
public String getCourseName() { return this.courseName; }
public double getGradeWeight() { return this.gradeWeight; }
public void setScore(int newScore) { this.score = newScore; }
public static void main(String[] args) {
Exam e1 = new Exam(100, "COSI 12b", 0.25);
Exam e2 = new Exam(100, "COSI 12b", 0.25);
System.out.println(e1.equals(e2));
System.out.println(e1 == e2);
}
}
What is the output?
- true, false
- true, true
- false, true
- false, false
Consider the following code:
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
s.add("hello");
s.add("world");
s.add("hello");
}
What is s.size()
?
- 1
- 2
- 3
- It cannot be determined at compile time
Consider the following variable declarations:
Integer n1 = 15;
Integer n2 = 7;
Integer n3 = 15;
String s1 = "computer";
String s2 = "soda";
String s3 = "pencil";
Indicate whether the result of each of the following comparisons is positive, negative, or 0:
n1.compareTo(n2)
n3.compareTo(n1)
n2.compareTo(n1)
s1.compareTo(s2)
s3.compareTo(s1)
s2.compareTo(s2)
Consider the following method:
public static void mystery(int[] a) {
for (int i = 1; i < a.length - 1; i++) {
a[i] = (a[i - 1] + a[i + 1]) / 2;
}
}
Indicate in your response what would be stored in the array after the method mystery
executes given the following code:
// Response A
int[] a1 = {1, 1, 3};
mystery(a1);
// Response B
int[] a2 = {2, 1, 2, 4};
mystery(a2);
// Response C
int[] a3 = {6, 13, 0, 3, 7};
mystery(a3);
// Response D
int[] a5 = {7, 2, 3, 1, -3, 12};
mystery(a5);
- Response A:
- Response B:
- Response C:
- Response D:
Assume the following four classes have been defined:
public class Tulip extends Rose {
public void verse1() {
System.out.print("Tulip 1 ");
}
}
public class Violet {
public void verse1() {
System.out.print("Violet 1 ");
}
public void verse2() {
System.out.print("Violet 2 ");
}
public String toString() {
return "Violet";
}
}
class Rose extends Lily {
public String toString() {
return "Rose " + super.toString();
}
}
class Lily extends Violet {
public void verse1() {
super.verse1();
System.out.print("Lily 1 ");
}
public void verse2() {
System.out.print("Lily 2 ");
verse1();
}
public String toString() {
return "Lily";
}
}
Given the classes above, what output is produced by this code:
pretty = { new Tulip(), new Lily(), new Violet(), new Rose() };
for (int i = 0; i < pretty.length; i++) {
System.out.println(pretty[i]);
pretty[i].verse1();
System.out.println();
pretty[i].verse2();
System.out.println();
System.out.println();
}
- Line 1:
- Line 2:
- Line 3:
- Line 4:
Given this program:
public class MyStuff {
MyStuff(String n) {
name = n;
}
String name;
public static void main(String[] args) {
MyStuff m1 = new MyStuff("guitar");
MyStuff m2 = new MyStuff("tv");
System.out.println(m2.equals(m1));
}
public boolean equals(Object o) {
MyStuff m = (MyStuff) o;
if (m.name != null)
return true;
return false;
}
}
What is the result?
- The output is "true" and MyStuff fulfills the Object.equals() contract.
- The output is "false" and MyStuff fulfills the Object.equals() contract.
- The output is "true" and MyStuff does NOT fulfill the Object.equals() contract.
- The output is "false" and MyStuff does NOT fulfill the Object.equals() contract
- Compilation fails
Given this program:
import java.util.*;
public class Primes {
public static void main(String[] args) {
List p = new ArrayList();
p.add(7);
p.add(2);
p.add(5);
p.add(2);
p.sort(null);
System.out.println(p);
}
}
What is the result?
- [2, 5, 7]
- [2, 2, 5, 7]
- [7, 2, 5, 2]
- [7, 5, 2, 2]
- Compilation fails
Given this program:
interface Rideable {
String getGait();
}
public class Camel implements Rideable {
int weight = 2;
public static void main(String[] args) {
new Camel().go(8);
}
void go(int speed) {
++speed;
weight++;
int walkrate = speed * weight;
System.out.print(walkrate + getGait());
}
public String getGait() {
return " mph, lope";
}
}
What is the result?
- 16 mph, lope
- 18 mph, lope
- 24 mph, lope
- 27 mph, lope
- Compilation fails.
- An exception is thrown at run time.
Given this program:
class Alpha {
String getType() {
return "alpha";
}
}
class Beta extends Alpha {
String getType() {
return "beta";
}
}
class Gamma extends Beta {
String getType() {
return "gamma";
}
public static void main(String[] args) {
Gamma g1 = new Alpha();
Gamma g2 = new Beta();
System.out.println(g1.getType() + " " + g2.getType());
}
}
What is the result?
- alpha beta
- beta beta
- gamma gamma
- alpha alpha
- Compilation fails.
In this expression:
museum.getFloor(3).getExhibit(5).getCurator().name.toUpper();
What is the (probable) datatype of each subexpression?
museum
museum.getFloor(3)
museum.getFloor(3).getExhibit(5)
museum.getFloor(3).getExhibit(5).getCurator()
museum.getFloor(3).getExhibit(5).getCurator().name
museum.getFloor(3).getExhibit(5).getCurator().name.toUpper()
Java 8 Streams are also a new feature of Java 8. What will each of these programs print out?
// What gets printed out?
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
long count = strings.stream().filter(string -> string.isEmpty()).count();
System.out.println(count);
// What gets printed out?
Stream.of("Edgecomb", "Fan", "Felig", "Flores", "Gold", "Goncalves Dos Santos",
"Hakakian", "Hechtman")
.map(s -> s.toUpperCase())
.filter(s -> (s.length() > 5))
.sorted()
.forEach(s -> System.out.println(" " + s));
// What gets printed out?
System.out.println(
Arrays.asList(12, 100, 41, 9, -5, 3001)
.stream()
.reduce(Integer.MAX_VALUE, (accum, val) -> (val < accum) ? val : accum));```
A student creates a class to represent a list of integer values with methods for average
, sum
, and median
. When the student realizes that they also need to compute these things for Double
s, they copy/paste their class and change each instance of Integer
to Double
. What principle of good software engineering is being most violated?
- DRY (do not repeat yourself)
- YAGNI (you ain't gonna need it)
- PLS (principle of least surprise)
- KISS (keep it stupidly simple)
In order to calculate the sum of all positive even integers below one billion, a student writes three classes, one to represent even integers, another to represent positive integers, and another to represent integers less than a billion. What principle of good software engineering is being most violated?
- DRY (do not repeat yourself)
- YAGNI (you ain't gonna need it)
- KISS (keep it stupidly simple)
While designing a system to allow students to enroll in summer courses, a software developer spends time ensuring that their code can be expanded to allow students to find fun places to eat. What principle of good software engineering is being most violated?
- DRY (do not repeat yourself)
- YAGNI (you ain't gonna need it)
- PLS (principle of least surprise)
- KISS (keep it stupidly simple)
For the Library programming assignment, a student implemented all their code in one class called MyLibrary
, storing books into a 4D arary. What principle of good software engineering is being most violated?
- DRY (do not repeat yourself)
- YAGNI (you ain't gonna need it)
- PLS (principle of least surprise)
- KISS (keep it stupidly simple)
You are designing a system to represent simple geometric systems containing squares, circles, and trapezoids. To do so, you create three classses, Square
, Circle
, and Trapezoid
. Since all three classes share a method called calculateArea
, and because you follow the DRY principle, you only want to write the method once. Which of these is not an acceptable way to do this?
- Create an interface called
Areaable
with a default methodcalculateArea
- Create an abstract parent class called
Shape
with acalculateArea
method - Create a static class called
AreaCalculator
with a singe methodcalculateArea
that each of your shape classes will call - Create an interface
Areaable
and an abstract parent classShape
which implementsAreaable
While designing code for a chess game, you realize that many classes (Knight
, King
, etc.) need to share similar properties relating to being a piece. Piece
should be...
- an abstract class
- an interface
- a regular class
- an enum
When practicing object oriented programming, we often say that we are mapping objects from a real-world ____________ into an ____________ of classes, interfaces, methods, and variables.
- ontology
- epistemology
- axiology
- deontology
The first computer compiler was written by:
- Grace Hopper
- Alan Turing
- Ada Lovelace
- Richard Stallman
Who is commonly given credit for creating the field of information theory?
- Grace Hopper
- Alan Turing
- Claude Shannon
- Alan Kay
Which famous computer scientist is most well-known for their relationship to the free (as in speech) software movement?
- Ada Lovelace
- Alan Kay
- Richard Stallman
- Dennis Ritchie
Who was the first computer programmer?
- Ada Lovelace
- Charles Babbage
- Dennis Ritchie
- Alan Turing
Who is considered the creator of object oriented programming?
- Alan Kay
- Charles Babbage
- Claude Shannon
- Richard Stallman
Function overloading is ....
- when a subclass provides a specific implementation of a method that is already provided by its parent class
- when a subclass provides a method that is not provided by its parent class
- when a class has multiple functions by the same name but different parameters
- when a class has multiple functions by the same name, resulting in an error
The import keyword is used to...
- import only built-in packages into your java source file
- import both built-in packages and user-defined packages into your java source file
- import only user-defined packages into your java source file
- None of the above
How is an instance of a class created (order matters)?
- Declaration, instantiation, initialization
- Instantiation, declaration, initialization
- Initialization, declaration, instantiation
- Initialization, instantiation, declaration
Which of the following classes define the println()
method?
- System class
- Object class
- InputStream class
- PrintStream class
Code that recurses forever without termination will trigger what exception?
NullPointerException
ConcurrentModificationException
FileNotFoundException
StackOverflowException
Which of the following has to be given a size before it is utilized?
- LinkedList
- ArrayList
- Array
- Stack
Which of the following does NOT implement the Collection
interface?
- LinkedList
- Array
- HashSet
- Stack
Which of the following variables use value semantics?
int x
int[] y
Object z
- 1 and 2
A student named Bob writes the following two classes, putting both in the same package:
public class AccessControl{
public int a;
private int b;
protected int c;
int d;
}
public class SubAccessControl extends AccessControl{
public SubAccessControl(){
this.a = 5;
this.b = 5;
this.c = 5;
this.d = 5;
}
}
Sarah notes that the SubAccessControl
constructor should not compile, because not all the fields in AccessControl
are visible to the SubAccessControl
class. Which statement is true?
- Sarah is correct. Only
a
,c
, andd
are visible. - Sarah is correct. Only
a
andd
are visible - Sarah is incorrect, all fields are visible.
- Sarah is incorrect. The code will compile, but it is a bad practice.
How do you define a natural ordering for a class you've written? You may assume the class implements the Comparable
interface.
- The class must implement the compareTo() and equals() methods so that they are compatible with one another.
- The class must implement the compareTo() and toString() method.
- The class must implement the equals() and toString() method.
- All classes have their natural ordering defined at compile-time.
(Extra) Which of the following are valid reason(s) to create an inner class?
- The inner class will be used to perform some task in the outer class, so it will ensure that the outer class object is created to access it.
- Inner classes have access to the containing class's private fields.
- Inner classes always run in constant space and time.
- 1 and 2
- 2 and 3
- All of the above.
Consider the following code:
public class OverLoad {
public void method(int a, int b) { }
public int method(int a, int b) { }
}
- It will compile
- It will not compile
What is an abstract class?
- A kind of class that cannot be instantiated
- Another term for an interface
- A class which is written in pseudo code
- None of the above
What is a static method?
- A method that does not change (cannot be reassigned)
- A method that can be called on a class, as opposed to an instance of a class
- A method that takes no parameters
- All of the above
What is a primitive type?
- A type that has value semantics
int
, for example- Cannot be stored in an
ArrayList
directly - All of the above
What is an interface?
- A graphical user interface (frontend)
- A set of methods that form a contract
- None of the above
What is a Java package?
- A named collection of Java source files
- Each version of Java that is installed on your computer is considered a package
- An obsolete feature of Java which is no longer recommended
- An interface together with all the classes that implement it
What is recursion?
- Cursing something, again
- A method that calls itself
- A method of proof
- None of the above
What is a final class?
- A class that cannot be changed after it is instantiated
- A class that cannot be subclassed
- A class that is immutable
- All of the above
This code does not compile. Why not?
ArrayList<int> numbers = new ArrayList<int>();
numbers.add(7);
- You cannot add 7 to an empty list
- You must cast 7 to an Integer
- You cannot create an ArrayList of
int
s - All of the above
You know that if you redefine the equals()
method for a class, then you must also redefine the hashCode()
method. Please answer:
- If you don't redefine both, then your program will not compile. True or False.
- If you define an equals method and not a corresponding hashCode method, then your program will throw an exception. True or False.
- All classes inherit a standard version of equals and hashCode from where?
- If your class needs a "natural ordering" then you need to redefine hashCode and equals. True or false.
- If
a.equals(b)
: it is required thata.hashCode() == b.hashCode()
. True or false? - If
!a.equals(b)
: it is not required thata.hashCode != b.hashCode()
. True or false?
When running a Java program, execution begins by
- Executing the very first line in the file
- Executing the static void main method found in any of the files of the program
- Executing the very first line of the class called Main
- Depends on whether the program is run with Eclipse or from the command line
- None of the above
It is important to understand the method signature in order to properly use overloading, overriding as well as interfaces. Which of these are not part of the method signature?
- Return datatype
- Exceptions thrown
- Method name
- Parameter name
- Parameter datatype
- modifiers (e.g. private, public etc.)
Which of these are not valid statements:
String[] suits = ["Clubs", "Diamonds"];
String[] suits = { Clubs, Diamonds };
String[] year = { "Freshman", "Software", "Junior", "Senior" }
String year[] = new String[10];
String year = new String[];
int[] oneDim = new int[10];
int[][] twoDim = new int[3][5];
String[][][] threeDim = new String[2][3][2];
Assume the following context:
String name = "Brandeis";
ArrayList<String> longList = new ArrayList<String>();
For all these expressions, answer what the datatype is, and what they value they have, if it can be determined.
1 + 2
"Brandeis".equals("MIT")
"a" + " fine day"
'a' + " wonderful afternoon"
"Brandeis".equals("MIT") || true
new Random().nextInt(100) == 9
longList.size() > 0
name.charAt(0)
name.substring(4).length > 5
In PA2 (Game of 15), we wrote an interface to a slide puzzle game using a provided class that implemented various methods like moveUp
. This most closely represents...
- Inheritance
- Abstraction
- YAGNI
- None of the above
In PA3 (security and leaky abstractions), we learned that String
s were a bad way to store structured data. Consider the following code:
package edu.brandeis.cs12b.pa3;
/**
* YOU MAY NOT MODIFY THIS CLASS.
*
*
*/
public class UserAuthenticator {
private String users = "Bob//test//regular";
/**
* Adds a regular user with the given username and password to the database.
* @param username the username to add
* @param password the password of that user
*/
public void addRegularUser(String username, String password) {
if (password.contains("//"))
return;
users = username + "//" + password + "//regular\n" + users;
}
/**
* Authenticates a user based on a username or password. Will return
* either the user's access type ("regular" or "admin"), or the string
* "Authentication failure!" if the username or password is incorrect
*
* @param username the username to log in with
* @param password that user's password
* @return the user status or "Authentication failure!"
*/
public String authenticateUser(String username, String password) {
for (String line : users.split("\n")) {
String[] fields = line.split("//");
if (username.equals(fields[0]) && password.equals(fields[1])) {
return fields[2];
}
}
return "Authentication failure!";
}
}
An additional check to make sure that password
does not contain the separator sequence (//
) has been added. Which statement is true?
- The system is no longer vulnerable to an injection attack and the abstraction is no longer leaky
- The abstraction is still leaky, but the system is no longer vulnerable to an injection attack
- The system is no longer vulnerable to a timing attack
- The system is still vulnerable to an injection attack and the abstraction is still leaky.
In PA4 (stats), we wrote reducer classes that a reduce
method that took two values: an initial
value and a next
value. For each item in the list, the reduce
method was called with its previous return value as the initial
value. Which statement is true?
- A value of
0
is always appropriate for the initial value - This structure only lets the reducer look at a single value from the list at a time
- This structure is not general enough to express summation
- None of the above
In PA5 (graphs), we represented Brandeis University as a graph where the vertices were buildings and the edges were weighted paths between them. Kruskal's algorithm was used to compute the minimum spanning tree of the graph, which is...
- The minimum set of vertices such that all edges are still connected
- The minimum set of edges such that the sum of their weights is still positive
- The set of edges with minimal weight sums that still connects all the vertices
- All of the above
In PA6 (Twitter), we used several APIs in order to create a word cloud for tweets. Which statement is false?
- The Lucene API let us tokenize our input
- APIs all require registration with a website to get access keys
- The Kumo API helps build word clouds
- None of the above are false
(Extra) In PA7 (knowledge trees), we represented facts about the real world using is-a
relationships. This sort of representation is:
- Ontological, because it makes a statement about what is
- Ontological, because it makes a statement about how knowledge is represented
- Epistemological, because it makes a statement about how knowledge is represented
- Axiological, because it makes a statement about what should be
In PA7 (knowledge trees), we represented knowledge in a way that enabled a computer to answer simple questions. Which of the following was not a piece of information our system could have deduced?
- A bee is a bug
- A bird is an animal
- A rectangle is a shape
- None of the above
In PA8 (compression), we attempted to make an array of orders smaller. The primary lesson, due to Shannon, is:
- Making data smaller depends only on the algorithms you are capable of implementing
- The more we know about the data, the smaller we can make it.
- Making assumptions about the data does not help compress the data
- No matter how much you try, you'll never be able to beat ZIP
In PA9 (domain modeling), we represented a library as Java objects. Which statement is false?
- Java programs consist of classes and objects, so we map the attributes of a library (books, cases, shelves) into those terms
- In Java, classes and objects can be used to represent real world things, creating a useful separation of responsibilities
- The creation of classes or objects to represent real world objects is a process known as domain modeling
- None of the above are false
In PA10 (compilers), we created a lexer, a parser, an interpreter, and a compiler. Which statement is false?
- Lexers transform source code into a stream of meaningful lexemes
- If two programs have an identical stream of lexemes, their textual representation is also identical
- Lexers must always be lazy
- Lexers can be represented as finite state transducers
In PA10 (compilers), we created a lexer, a parser, an interpreter, and a compiler. Which statement is false?
- A parser is responsible for transforming a stream of lexemes into a parse tree
- It is easier to compare the parse trees of two programs than it is to compare the lexemes of two programs
- Generating a parse tree is usually done before interpretation or compilation
- None of the above are false
In PA10 (compilers), we created a lexer, a parser, an interpreter, and a compiler. Which statement is false?
- An interpreter evaluates PitoScript trees from the bottom-up, prompting the user when needed.
- An interpreter must keep track of the value of each variable as it processes statements.
- Interpretation generally happens before compilation
- Interpretation isn't always slower than compilation
In PA10 (compilers), we created a lexer, a parser, an interpreter, and a compiler. Which statement is false?
- A compiler transforms a parse tree into a sequence of low-level instructions
- The program generated by a compiler has nothing to do with the input lexemes
- The compiler must keep track of where it has stored values in memory
- None of the above are false
In PA10 (compilers), we created a lexer, a parser, an interpreter, and a compiler. Which statement is false?
- Registers are special places in memory
- Memory can be thought of as an array of values
- Instructions are executed one at a time by the VM
- The
OUTPUT
instruction is not needed in order to return the values of variables
Write a static method named samePattern that accepts two arrays of integers as parameters and returns true if the second array is composed of repetitions of the first array and false otherwise.
Your response implements this:
static boolean samePattern(int[]one, int[]two) ...
Write a static method named countCommon that accepts three arrays of strings as parameters and returns an integer count of how many indexes store exactly the same string in all three arrays. For example, if the arrays are:
// index 0 1 2 3 4 5 6 7
String[] a1 = {"hi", "Ed", "how", "are", "you", "folks", "DoIng", "today?"};
String[] a2 = {"hi", "Bob", "how", "are", "YOUR", "kids", "doing", "today?"};
String[] a3 = {"hi", "you", "how", "are", "you", "guys", "DOING", "today?"};
Then the call of countCommon(a1, a2, a3) should return 4 because indexes 0, 2, 3, and 7 store exactly the same string in all three arrays. Indexes 1, 4, 5, and 6 do not. (Index 6 differs by capitalization.)
The arrays might not be the same length. An index must be within the bounds of all three arrays to be considered. For example, given the arrays below, the call of countCommon(a4, a5, a6) should return 3 because all three arrays store the same values at indexes 0, 2, and 5:
// index 0 1 2 3 4 5 6 7
String[] a4 = {"hi", "Ed", "how", "ARE", "you", "Doing", "I'm", "fine"};
String[] a5 = {"hi", "Bob", "how", "are", "YOU", "Doing"};
String[] a6 = {"hi", "you", "how", "is", "you", "Doing", "this", "fine", "day?"};
For full credit, do not modify the elements of the arrays passed in. Do not make any assumptions about the length of the arrays or the length of the strings stored in them. You may assume that none of the arrays or elements are null.
int countCommon(String[] one, String[]two, String[] three) {} ...
At the bottom of the page, write the output produced by the following program, as it would appear on the console.
public class ParameterMystery {
public static void main(String[] args) {
String bril = "vorpal";
String gyre = "jubjub";
String slithy = "snack";
String tum = "mut";
String mut = tum + 1;
mystery(bril, slithy, gyre);
mystery(gyre, "gyre", mut);
mystery(gyre + slithy, bril, tum);
tum = "tumtum";
bril = "slithy";
mystery(tum, gyre, slithy);
}
public static void mystery(String gyre, String bril, String slithy) {
System.out.println("Twas " + bril + " and the " + slithy +
" toves did " + gyre);
}
}
- Answer:
Write a method called writeSequence that accepts an integer n as a parameter and prints to the console a symmet- ric sequence of n numbers composed of descending integers that ends in 1, followed by a sequence of ascending integers that begins with 1. The following table indicates the output that should be produced for various values of n:
Method call Output produced
-----------------------------------------
writeSequence(1); 1
writeSequence(2); 1 1
writeSequence(3); 2 1 2
writeSequence(4); 2 1 1 2
writeSequence(5); 3 2 1 2 3
writeSequence(6); 3 2 1 1 2 3
writeSequence(7); 4 3 2 1 2 3 4
writeSequence(8); 4 3 2 1 1 2 3 4
writeSequence(9); 5 4 3 2 1 2 3 4 5
writeSequence(10); 5 4 3 2 1 1 2 3 4 5
Notice that when n is odd the sequence has a single 1 in the middle, while for even values it has two 1s in the middle. Your method should throw an IllegalArgumentException if it is passed a value less than 1.
The Lambda expression was newly introduced in Java 8. Lambdas are useful on their own and also very important in the design Java 8 Streams. The general or generic syntax for a lambda is:
(parameters) -> expression
-or-
(parameters) -> { statements; ... }
- Write a lambda expression which returns true if a string parameter is longer than 5 characters
- Write a lambda expression which returns the square of a number parameter
- Write a lambda expression which returns true if a numeric parameter is even