Ancient One

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Assume that you want to create an array containing ten Die objects. Which of the following code segment accomplishes this correctly? A: Die[] dice = new Die[10]; for (int i = 0; i < dice.length; i++) { dice[i] = new Die(); } B: Die[] dice = new Die[10]; Die die = new Die(); for (int i = 0; i < dice.length; i++) { dice[i] = die; }

A

What is the output of executing the following code if it compiles correctly and has no exceptions? System.out.print("Another day another $ "); System.out.println("I wish it were $10!");

Another-day-another---I-wish-it-were--10-

By calculating number % 10, you can:

Extract the rightmost digit

A switch statement evaluates a boolean expression and then jumps to the appropriate case statement.

False

Given the following set of Java expressions, what value will print in the final line: String str1 = "Hello"; String str2 = "Hello"; System.out.println( str1 == str2 );

False

In order to call another method in the same class, it must be declared before (above) the method that calls it.

False

Tabs are allowed for indentation in a java file that passes checkstyle with no errors.

False

The following two expressions are logically equivalent: if ( a && b ) doSomething(); ________________ if ( a ) if ( b ) doSomething();

False

A constructor

Has the same name as the class

What does the == operator do when it is used to compare reference variables?

It returns true if the two variables contain the same address.

How do you write \pi^5 π 5 in Java? Write the expression itself, not the value 148.413. (Don't write any semicolons or extra spaces.)

Math.pow-Math.PI--5

The toString method that you created for the Car class is:

NOT a mutator method or constryuct

What does the following statement output? System.out.print("Programming is \"magic\"! :\\");

Programming-is--magic---:-

On the command-line the < and > symbols mean:

Redirect input and output

The compiler says "cannot find symbol" when you:

Refer to a class that has not been imported AND Use a variable that has not been declared

Write a Java statement to define a Scanner object to read from the keyboard called userInput.

Scanner-userInput---new-Scanner-System.in--

When an individual element of a primitive array is passed to a method

The element is passed just as an object would be passed

The scope of a private instance field is

The instance methods of the same class

Which of the following is an important difference between arrays and ArrayLists in Java?

The size of an array cannot change. ArrayLists can grow or shrink as needed.

Which of the following would be a good reason to use a for loop instead of a while loop?

You need a loop to execute a known number of iterations.

What will be printed by the following code snippet, assuming that letters is an initially empty ArrayList? letters.add("A"); letters.add("B"); letters.add("C"); letters.add(1, "D"); System.out.println(letters.toString());

[A, D, B, C]

In order to run, a Java application must have

a method named main

The storage location of a variable or object in memory

address

What is the term for a class that includes other classes as instance variables?

aggregation

Computer science is the science of ___________? (Use the correct answer I mention in the AboutMe video and discussed in class.)

algorithms

When a method is called, the values between the parentheses are referred to as?

arguments

Consider the following code fragment: boolean penalty; if (income > 100.0 && payment < 10) { penalty = true; } else { penalty = false; } Which (if any) of the code fragments below are equivalent to this? More than one answer may be correct.

boolean penalty = false; if (income > 100.0 && payment < 10) { penalty = true; } AND boolean penalty; penalty = income > 100.0 && payment < 10;

What extra step is necessary to read a mix of integers and text using a Scanner?

call nextLine after nextInt

What is the two letter command line command that lets you change directories?

cd

What can automated style checkers do well? (check all that apply)

check the indenting/spacing of your code AND warn you if you forgot to write comments

A "final" variable that can be assigned only one time.

constant

You want to create a table that looks like: 12 -9 8 7 14 -32 -1 0

double[][] table = { {12, -9, 8}, {7, 14}, {-32, -1, 0} };

Comments can be used by the Java compiler to help find logic errors in a program.

false

Java will automatically do both widening and narrowing conversion of data values.

false (i think)

Write a Java statement to create a constant that is a floating point value of 0.1 called FEE_RATE.

final-double-FEE_RATE---0.1-

var i = 0; while (i < 3) { println("hi"); i++; } What does the code output?

hi hi hi

What is the result type of Math.abs(-948)?

int

Which of these is an incorrect array declaration?

int arr[] = int [5] new;

Given the following: int[][] items = { {0, 1, 3, 4}, {4, 3, 99, 0, 7 }, {3, 2} } ; Which of the following statements replaces the 99 with 77?

items[1][2] = 77;

What is the full command to run the class file Bottles?

java Bottles

What is the full command to run the class Bottles with input from test1.in and send output to test1.out?

java-Bottles---test1.in---test1.out

What is the command to compile the java file Bottles.java?

javac-Bottles.java

A basic element of code, such as a word or symbol.

literal

What is the 2 letter Linux command that allows you to list the contents of the current directory?

ls

Assume that a Scanner object named userInput has been declared and instantiated to read input from System.in. Write a Java statement that would read from this Scanner object an integer and store it in an already declared integer variable named myInt.

myInt userInput.nextInt

Computer scientists frequently draw diagrams representing the state of memory after a certain set of instructions have been executed. Memory is represented in these pictures as a series of boxes with the "address" on the outside of the box and the contents of the memory location inside the box. Which of the following accurately represents the state of memory ( i.e. is the state or memory diagram) after the following assignments are executed? name = "Anna"; pin = 1234; year = 2000; pin = year;

name = "Anna"; pin = 2000; year = 2000;

Which of the following for loops is valid, given the following declaration?

no parenthesis on top .length but yes parenthesis on bottom .length

A variable's scope ends at the closing brace of the code block in which it is declared.

not sure but i think its true

A symbol that represents a computation like addition.

operator

What is the term for two methods in the same class that have the same name but different signatures?

overloading

Files are to folders as classes are to

packages

The values between the parentheses in a method definition are referred to as the ?

parameters

The ability to run on more than one kind of computer.

portable

The order in which certain operations are evaluated

precedence

Consider the following partially completed class:

public Hat(int size) { size = this.size; } public Hat(int s) { size = s; }

Write the signature (i.e., the part before the { symbol) of a method printToday that has no parameters and returns no value.

public-static-void-printToday

What is the 3 letter Linux command that displays the path of the current directory?

pwd

Classes with all static methods are sometimes referred to as...

utility classes

In Java, all argument types are passed by:

value

What keyword in Java indicates that a method does not return a value?

void

Newlines, tabs, and other "invisible" characters

whitespace

The expression: if ( a < 0 && a > 7 )

will never be true

A partially-filled array is normally used

with an accompanying integer value that holds the number of items stored in the array

What would be the results after the following code was executed? char[] x = {'a', 'b', 'a'}; char[] y = {'x', 'y', 'w'}; char[] temp; temp = x; y = x; x = temp;

x[] = { 'a', 'b', 'a' } and y[] = { 'a', 'b', 'a' }

What would be the results after the following code was executed?

x[] = {36, 78, 12, 24} and y[] = { 36, 78, 12, 24 }

What would be the results after the following code was executed? int[] x = {23, 55, 83, 19}; int [] y = {42, 65, 19, 2}; x = y; y = x; y[2] = 4;

x[] = {42, 65, 4, 2} and y[] = {42, 65, 4, 2}

Which type of comment does Javadoc process?

/**

Given the following: double[][] things = { {1.2, 9.0}, {9.2, 0.5, 0.0}, {7.3, 7.9, 1.2, 3.9} } ; What is the value of things[2].length ?

4

How many arguments are passed to the printf method? System.out.printf("Hello %s, the time is %02d:%02d.\n", first + " " + last, hour - 2, minute);

4

How many times will the loop be executed? int i = 1, months = 5; while (i < months) { futureValue = futureValue * (1 + monthlyInterestRate); i = i+1; }

4

All of the following are valid identifiers EXCEPT...

4tenors

What is the output of the following program? (Answer without copying/pasting/running the code.) public class Hello { public static void other(String[] args) { int x = 7; System.out.print(x); System.out.print(" "); } public static void main(String[] args) { int x = 5; other(args); System.out.println(x); } }

7 5

Given the following for loop: for (int ii = 1; ii < 10; ii++) { System.out.println(ii); } How many lines will this loop print?

9

To output a number with two decimal places, what four characters should be inside the quotes?

-.2f

Evaluate the following Java expressions. If an expression is invalid (will cause a compiler error) mark both boxes INVALID.

// its data type - then result (18 % 4) * 3.0 // double - 6 !false && (2.0 > 4.0) // boolean - false "out: " + (1 / 3 == 0) // string - out:true false && (false || true) // boolean - false false && false || true // boolean - true 3 < "4" < "5" // invalid - invalid

What is the value of (int) -0.999999?

0

What value does the variable x have after the following Java statements are executed without compilation errors or exceptions? int x; x = 333 % 3;

0

What will be the output of the following code? int[] arr = new int[9]; System.out.println(arr[0]);

0

What is the output of the following code fragment: for ( int count=0; count <= 9; ++count ) { System.out.print( count + " " ); } System.out.println( );

0 1 2 3 4 5 6 7 8 9

If final int SIZE = 15 and int[] x = new int[SIZE], what would be the range of subscript values that could be used with x[]?

0-14

What is the output of this program? class evaluate { public static void main(String args[]) { int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = 6; n = arr[arr[n] / 2]; System.out.println(arr[n] / 2); } }

1

class array_output { public static void main(String args[]) { int array_variable [] = new int[10]; for (int i = 0; i < 10; ++i) { array_variable[i] = i; System.out.print(array_variable[i] + " "); i++; } } }

1 2 3 4 5 6 7 8 9 10

Given the following for loop: int x = 2; int y = 0; for ( ; y < 10; ++y) { if (y % x == 0) continue; else if (y == 8) break; else System.out.print(y + " "); }

1 3 5 7 9

What will be the value of x after the following code is executed? int x = 11; do { x += 10; } while (x > 100);

21

What is the value of the variable x after the following Java commands are executed, assuming they compile and run without an exception? double x; x = (5 / 4) * Math.abs(-257) + 3.0;

260

What is the output of the following java statement? System.out.print("The world is \"crazy\"!");

The-world-is--crazy--

Two or more methods in a class may have the same name as long as

They have different parameter lists

How man times will "Hello" be printed by the following code? int i = 7; while(i <= 100) { System.out.println("Hello"); }

This is an infinite loop. Hello will be printed until the program is forced to stop.

Changing the order that methods are declared in a source file has no effect on the runtime behavior of the program.

True

Methods are often used to divide a complex problem into smaller, more manageable pieces.

True

The contents of a variable can change during the execution of a program, but the address corresponding to the variable name will not change.

True

The following two expressions are equivalent: a && b || ( c > 0 ); ( a && b ) || c > 0;

True

When calling a method, the arguments in the method call must have compatible types to those in the method definition.

True

You can compile a Java program on Windows and then run it on a Mac.

True

Which of the following best describes "overloading"?

Two methods in a class have the same name but different signatures.

Trace command line arguments. Given the following code: public class Quiz { public static void main (String[] args) { int number; char letter; if (args.length > 1) { number = Integer.parseInt(args[0]); letter = args[1].charAt(0); for (int ii = number; ii >= 0; ii--) { System.out.print(letter); } System.out.println(); } else System.out.println("Invalid input"); } } What is output by the following command: java Quiz 5 rabbit

rrrrrr

In the previous question, each variable x has a different

scope

The assignment operator is used to ( its an = sign)

store a value in memory

Rules that must be followed when writing a program, dictating how key words and operators must be used along with where punctuation symbols must appear.

syntax

What's wrong in the following "for" loop statement? for (int k = 2, k <= 12, k++)

the commas should be semicolons

An actual value written directly in the source code

token

In java, 3.14, main, and "Hello" are examples of:

tokens

In the Java statement x = input.nextInt(); nextInt is the name of a method.

true

Variable names (local to a method) should always begin with a lowercase letter

true

public, static, void, and main are all examples of Java Language Keywords.

true

6) Consider the following recursive sum method: public int sum(int x) { if(x = = 0) return 0; else return sum(x - 1) + 1; } If the base case is replaced with "if(x = = 1) return 1;" the method will still compute the same thing.

Answer: False. Explanation: The original method causes infinite recursion if called with a parameter < 0, but works properly if called with any parameter >= 0. With the new base case, the method now works properly if called with any parameter >= 1 but causes infinite recursion if the parameter < 1. So, sum(0) now differs from what it had previously.

10) We can define a list of int values recursively as: a list_item, followed by a comma, followed by a list where a list_item is any int value.

Answer: False. Explanation: The recursive definition does not include a base case so that all lists of int values will be infinitely long!

9) Since iterative solutions often use loop variables and recursive solutions do not, the recursive solution is usually more memory efficient (uses less memory) than the equivalent iterative solution.

Answer: False. Explanation: The recursive solution may use no local variables whatsoever, but the recursive solution usually uses parameters. Every time the method is called recursively, new parameters are required, and so recursively solutions usually use a substantially larger amount of memory than an iterative solution (it depends on how many times the method is called recursively).

24) A priority queue could not be implemented using an array.

Answer: False. Explanation: There are trade-offs between different implementations, but it is certainly possible to implement a priority queue using an array.

25) If method f1 calls method f2 calls method f3, we have indirect recursion.

Answer: False. Explanation: There is no recursion in that. Indirect recursion would be f1 calling f2 calling f1 again (and so on).

9) All classes are considered Abstract Data Types.

Answer: False. Explanation: To be considered an Abstract Data Type, the type must define a data structure and the methods to manipulate the data structure. However, a programmer does not have to set up a data structure in this way. For instance, if the instance data are made public, then there is no need to implement methods to manipulate those instance data, they can be directly modified from other classes. Therefore, just because a class exists does not mean that the class is an ADT

23) When a method is called by itself, it the second invocation uses the same storage space for local variables, so in effect the invocation share the variables.

Answer: False. Explanation: When a method is called recursively new local variables are created.

2) The push and enqueue operations are essentially the same operations, push is used for Stacks and enqueue is used for Queues.

Answer: False. While both operations are "add" or "insert" operations for their respective Abstract Data Types, they differ in that push always adds at the top (or front) of the Stack while enqueue always adds at the rear of the Queue

15) Aside from writing recursive methods, another way that recursion is often used is to define mathematical functions.

Answer: True . Explanation: Mathematics often defines functions recursively for simplicity.

2) The following method lacks a base case. public int noBaseCase(int x) { if(x > 0) return noBaseCase(x - 1) + 1; else return noBaseCase(x - 2) + 2; }

Answer: True. Explanation: A base case is a condition that, when taken, stops the recursion by not calling the method recursively. In the above method, there is a condition, but whether the condition is true or false, the method invokes itself recursively.

22) A priority queue is a dynamic data structure.

Answer: True. Explanation: A priority queue can grow and shrink during use, so it is a dynamic data structure.

13) After the instructions execute, z has the value 9.

Answer: True. Explanation: At that point that the int z = s.pop( ); executes, a previous s.pop( ); will have removed the most recently pushed item (4), so this pop removes the next most recently pushed item (9).

17) Recursion can be used when sorting an array of elements.

Answer: True. Explanation: Both merge sort and quick sort are often implemented recursively.

21) A stack could be simulated with a priority queue.

Answer: True. Explanation: Consider a priority queue where each item's priority is its time of arrival into the queue, and later times are given higher priority. This produces LIFO processing which is what a stack uses.

10) All Abstract Data Types are defined as classes in Java.

Answer: True. Explanation: In Java, all data are either primitives or classes. An ADT is a data structure, so it is more than just a primitive type, but a structure of different types. Therefore, the ADT must be defined in a class. Not all classes are necessarily ADTs, but all ADTs are defined as classes.

16) Merge sort and quick sort are more time efficient than insertion sort and selection sort.

Answer: True. Explanation: Merge sort has time efficiency O(nlogn) and quick sort, while it's worst case efficiency is O(n2) has average O(nlogn). O(nlogn) is more efficient than O(n2) which is what insertion and selection sort are.

4) Some problems are easier to solve recursively than iteratively.

Answer: True. Explanation: Since recursion performs backtracking automatically, any problem that requires backtracking is easier to solve using recursion. Such problems include traversing a maze and searching through a "search space", a topic covered in Artificial Intelligence and Advanced Algorithms courses. In some cases, it is easy to find a recursive solution and so the recursive solution is easier than the iterative solution.

8) A Koch snowflake of order = 1 can be drawn without recursion.

Answer: True. Explanation: The Koch snowflake of order 1 is made up of straight lines. It is not until the order is greater than 1 that recursion is applied.

19) The LinkedList class in the Java standard class library represents a list and is implemented using a linked list.

Answer: True. Explanation: The LinkedList class implements the List interface using a linked list implementation.

7) Queues and Stacks can be implemented using either arrays or linked lists.

Answer: True. Explanation: The Queue and the Stack are both Abstract Data Types, their method of implementation is immaterial, it is the operations (enqueue, dequeue, push, pop) that define them. So, both ADTs can be implemented using either arrays or linked lists.

8) In order to input a list of values and output them in order, you could use a Queue. In order to input a list of values and output them in opposite order, you could use a Stack.

Answer: True. Explanation: The Queue provides First-in First-out access, so the items would be accessed in the order that they were entered. The Stack provides Last-in First-out access, so the items would be accessed in the opposite order that they were entered.

15) After the code above executes, 4 elements remain in q.

Answer: True. Explanation: The constructor creates an initially empty Queue. Each enqueue operation adds one int to the Queue and each dequeue operation removes one int from the Queue. There are 7 enqueue operations and 3 dequeue operations, leaving 4 int values in q at the end.

10) Assume that the linked list has at least two Nodes in it. Which of the following instructions will return the second int value in the list? a) return head.info; b) return head.next.info; c) return head.next.next.info; d) return head.next.next.next.info; e) It is not possible to return the second int value in the list using head.

Answer: b. Explanation: The variable head references the first Node in the list, so that head.info is the first int value. The statement head.next references the second Node in the list, so head.next.info references the second Node's data item.

11) Assume Node temp is currently set equal to head. Which of the following while loops could be used to iterate through each element of a linked list? a) while (head != null) head = temp.next; b) while (temp != null) temp = temp.next; c) while (head != null) temp = temp.next; d) while (head != null) head = head.next; e) while (temp != null) head = head.next;

Answer: b. Explanation: To iterate through the list, we will use a different reference variable than head so that we do not lose our reference to the list, so we use temp instead. To iterate through the list, temp starts at head and continues until temp becomes null (it no longer references a node). To move to the next item in the list, temp is updated to be temp.next. The answer in d is correct but it loses the reference to the list and so is not what we would desire to do. The other loops have incorrect logic resulting in either infinite loops, or loops that cause run-time Exceptions.

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 5) What is returned if factorial(0) is called? a) 0 b) 1 c) 2 d) nothing, factorial(0) causes infinite recursion e) nothing, factorial(0) produces a run-time error

Answer: b. Explanation: With factorial(0), (x > 1) is not true, so the base case is executed and 1 is returned. Therefore, even though ordinarily 0 * value = 0, the factorial(0) is computed as 1.

13) Which of the following methods could be used to count the number of items in the linked list? a) public int countIt(Node temp) { while(temp != null) { count += temp.info; temp = temp.next; } return count; } b) public int countIt(Node temp) { while(temp != null) { count++; } return count; } c) public int countIt(Node temp) { while(count != null) { count++; temp = temp.next; } return count; } d) public int countIt(Node temp) { while(temp != head) { count++; temp = temp.next; } return count; } e) public int countIt(Node temp) { while(temp != null) { if(next != null) count++; temp = temp.next; } return count; }

Answer: c. Explanation: Answer a sums all items in the array. Answer b does not advance temp to reference the next Node, and is therefore an infinite loop. Answer c properly counts each Node and moves on to the next Node. Answer d has the wrong loop condition and answer e counts all of the items in the list except for the last one.

6) A linked list that stores int values would be comprised of a group of Nodes. We might define the Node by a) class Node { Node next; } b) class Node { int next; } c) class Node { int data; } d) class Node { int data; Node next; } e) class Node { int[ ] data; Node next; }

Answer: d. Explanation: The linked list stores int values, so each Node requires an int data type. Further, because it is a linked list, each node must contain a reference to the next Node, which is defined as Node next; where next is the reference.

22) Define the magnitude of a number as the location of the decimal point from the left of the number (that is, if a number has 4 digits followed by the decimal point, it will have a magnitude of 4). 100 would then have amagnitude of 3 and 55,555.555 would have a magnitude of 5. A partial recursive method is given below to compute a positive int parameter's magnitude. Which answer below is needed to complete the method? public int magnitude(double x) { if (x < 1) return 0; else return _______; } a) magnitude(x - 1) + 10; b) magnitude(x - 10) + 1; c) magnitude(x / 10) + 10; d) magnitude(x / 10) + 1; e) magnitude(x / 10) * 2;

Answer: d. Explanation: The method must count the number of digits to the left of the decimal point, so it continually divides the value by 10 until the value has no digits to the left of the decimal point (this is the case if value < 1). Each time the value is divided by 10, 1 is added to the return value. 55,555.555 will be divided by 10 five times before it becomes < 1, and thus return 5.

1) An Abstract Data Type is a data structure, that is, it is the listing of the instance data and the visibility modifiers for those instance data.

Answer: False. An Abstract Data Type includes the data structure, but also includes the methods implemented to access/manipulate the data structure.

20) Merging two lists of n sorted elements would take O(n2) time.

Answer: False. Explanation: 2n elements would need to be examined and this is O(n).

20) A priority queue uses FIFO processing

Answer: False. Explanation: A priority queue uses priorities to determine which element comes off in a dequeue operation.

19) The pivot value selected in a quick sort should be the smallest element in the list.

Answer: False. Explanation: Choosing the smallest element causes the list to be divided unevenly. The best choice would be to choose the middle element, but often an element is chosen randomly because that takes less time.

21) Infinite recursion is impossible as long as you have a base case.

Answer: False. Explanation: If the recursive case is such that the base case will never be reached, then you have infinite recursion. For example: int bar(int n) { if (n < 0) return 0; else return bar(n); }

25) In a doubly linked list, every node has a pointer to both the first node in the list and the last node in the list.

Answer: False. Explanation: In a doubly linked list every node points to the node before it and the node after it.

5) A linked list that contains 6 Nodes will have 6 reference pointers.

Answer: False. Explanation: In order to access the linked list, there needs to be a 7th reference pointer at least, one that references the first item in the list.

24) A recursive method that doesn't return anything with result in infinite recursion.

Answer: False. Explanation: It is possible to have a void recursive method. (For example maybe it prints something rather than returning anything.)

3) Traversing a maze is much easier to do iteratively than recursively.

Answer: False. Explanation: One reason that recursion is appealing is that it automatically backtracks to the point of the last decision. In traversing a maze, when one reaches a dead end, the best place to continue is at the point of the previous intersection (or decision). So, backtracking is performed. To solve a maze iteratively requires implementing a backtracking mechanisms, which is available automatically in recursion.

13) A recursive algorithm is superior to an iterative algorithm because it is computationally more efficient.

Answer: False. Explanation: Recursion is more inefficient than iteration.

11) To simulate people waiting in a line you could use a stack.

Answer: False. Explanation: The FIFO access of a Queue is the same access of people waiting in line, the first person to enter will be the first to leave. So, simulations of any kind of line structure will use the Queue data structure. The Stack uses LIFO (last in, first out) access which does not make sense for a line.

12) After the instructions execute, x has the value 12.

Answer: False. Explanation: The Stack offers a last-in first-out access, so at the point when s.pop( ) is first executed, the item removed is the last item pushed onto s, or 19.

7) The recursive method to solve the Towers of Hanoi is usable only if the parameter for the number of disks is 7 or smaller.

Answer: False. Explanation: The Towers of Hanoi solution can be used for any sized disk as long as it is at least 1.

6) The linked list is superior to the array in all ways when it comes to implementing a list.

Answer: False. Explanation: The advantage of the linked list is that it is dynamic while the array is static. However, the array supports random access (the ability to access any element of the array easily) whereas a linked list does not support this (to access the 8th element, the first 7 elements must be traversed). So, the linked list has a major disadvantage, and even though is dynamic, many programmers choose to use an array to implement a list because of this drawback.

4) An array is a List Abstract Data Type.

Answer: False. Explanation: The array is a data structure that can be used to store a List of values, but the array does not have operations already implemented to perform List operations such as add to the end, or delete a given value.

16) The value 5 is returned by the last dequeue operation (denoted above with a d3 in comments).

Answer: False. Explanation: The dequeue operations remove the next item in the Queue, so the dequeue in d1 removes 3, the dequeue in d2 removes 5 and the dequeue in d3 removes 9.

11) Assume the method below is called initially with i = 0 public int question(String a, char b, int i) { if (i = = a.length( )) return 0; else if (b = = a.charAt(i)) return question(a, b, i+1) + 1; else return question(a, b, i+1); } The method returns 1 if char b appears in String a at least once, and 0 otherwise.

Answer: False. Explanation: The method compares each character in String a with char b until i reaches the length of String a. 1 is added to the return value for each match. So the method returns the number of times char b appears in String a.

2) A collection whose items are of different types is referred to as a(n) _______ type. a) homogeneous b) heterogeneous c) dynamic d) abstract e) vector

Answer: b. Explanation: The term heterogeneous means that the elements are different types. In Java, classes can store heterogeneous types, for instance one instance data might be an int and another a String and a third a double. Arrays on the other hand are homogeneous types because every element stored in the array is the same type.

3) The Abstract Data Type (ADT) is thought of as abstract because the operations that are to be implemented are separated from the actual implementation, that is, an ADT can be implemented in more than one way and that implementation is separate from how we might use the ADT.

Answer: True. Explanation: The importance of the ADT is that the operations are implemented as we would expect so that the operation is performed correctly even if we do not know how the operation is implemented. In this way, we assume that a Queue adds at the rear and removes from the front so that we have a FIFO access even though we do not know how the Queue is implemented itself.

5) The following two methods will both compute the same thing when invoked with the same value of x. That is, method1(x) = = method2(x). public int method1(int x) { if(x > 0) return method1(x - 1) + 1; else return 0; } public int method2(int x) { if(x > 0) return 1 + method2(x - 1); else return 0; }

Answer: True. Explanation: The only difference between the two methods is the order of the recursive call and adding 1 to the return value. The difference is denoted by calling the first method head recursive and the second tail recursive. So both methods will compute the same value, but arrive at the value in different ways.

17) If we replace each System.out.println statement (denoted in comments as d1, d2 and d3) with the statement q.enqueue(q.dequeue( )); q would contain the following values in the order given: 3, 2, 4, 5, 9, 1, 8

Answer: True. Explanation: The original order of int values in q is 3, 5, 9. At d1, the first item is dequeued and then enqueued resulting in 5, 9, 3. Two more enqueues result in 5, 9, 3, 2, 4. At d2 and d3, the first two items are dequeued and then enqueued resulting in 3, 2, 4, 5, 9. Finally, 1 and 8 are enqueued leaving q as 3, 2, 4, 5, 9, 1, 8.

23) There is no way to go backwards in a singly linked list.

Answer: True. Explanation: The pointers only point forward in a singly linked list. You would need a doubly linked list in order to go backwards.

18) A recursive sort typically divides the list into smaller sublists which are sorted recursively.

Answer: True. Explanation: The sublists are then combined.

14) The method below computes the value of x % y (x mod y) recursively, assuming that x and y not negative numbers. public int recursiveMod(int x, int y) { } if (x < y) return x; else return recursiveMod(x - y, y);

Answer: True. Explanation: The value x % y can be computed by continually subtracting y from x until x < y. Then, theresultisx. Forinstance,7%3=4%3=1%3=1.

12) The recursive method below would execute approximately log 2 n times for an initial parameter n. public void logcode(int n) { if (n > 1) logcode(n / 2); }

Answer: True. Explanation: This method recursively calls itself with n being half its original value. If n starts at 16, thesecondcallhasn=8,thethirdhasn=4,thefourthhasn=2,thefifthandfinalcallhasn=1. Ifnstartsat32,it adds one additional call. If we double n again, it only adds 1 more recursive call. This is a log 2 n behavior.

22) Infinite recursion can occur with indirect recursion.

Answer: True. Explanation: Two or more methods could call each other inifintely.

18) The first node in a linked list often requires special handling

Answer: True. Explanation: When inserting or deleting a node from the beginning of the linked list, a special case is required.

14) After the instructions execute, y has the value 4.

Answer: True. Explanation: When int y = s.pop() is executed, the most recently pushed item is 4, so 4 is popped off assigned to y.

1) A recursive method without a base case leads to infinite recursion.

Answer: True. Explanation: Without the base case, the recursive method calls itself without the ability to stop, and thus leads to infinite recursion.

4) Abstract Data Types have which of the following object-oriented features? a) Information hiding b) Inheritance c) Polymorphism d) Message Passing e) All of the above

Answer: a. Explanation: All of these answers are types of object-oriented features. An Abstract Data Type encapsulates a data structure and the methods to manipulate the data structure such that information hiding is preserved. Therefore, all ADTs make use of information hiding so that the data structure cannot be manipulated directly from outside of the ADT, but the other object-oriented features are not required.

14) Which of the following methods could be used to sum all of the items in the linked list? a) public int sumIt(Node temp) { while(temp != null) { sum += temp.info; temp = temp.next; } return sum; } b) public int sumIt(Node temp) { while(temp != null) { sum += temp.info; } return sum; } c) public int sumIt(Node temp) { while(temp != null) { sum++; temp = temp.next; } return sum; } d) public int sumIt(Node temp) { while(temp != head) { sum += temp.info; temp = temp.next; } return sum; } e) public int sumIt(Node temp) { while(temp != null) { if(next != null) sum += temp.info; temp = temp.next; } return sum; }

Answer: a. Explanation: Answer b does not advance temp to reference the next Node, and is therefore an infinite loop. Answer c counts the number of items in the list but does not sum up the values of these items. Answer d has the wrong loop condition and answer e counts all of the items in the list except for the last one.

24) If the method is called as patternRecognizer(x) where x is "aa", what will the result be? a) true b) false c) a NullPointerException d) a run-time error e) infinite recursion

Answer: a. Explanation: One of the base cases tests to see if the String has 2 characters and if so, returns true if the two characters are the same.

21) One operation that we might want to implement on a Stack and a Queue is full, which determines if the data structure has room for another item to be added. This operation would be useful a) only if the Queue or Stack is implemented using an array b) only if the Queue or Stack is implemented using a linked list c) only for a Queue d) only for a Stack e) none of the above, a full operation is not useful at all

Answer: a. Explanation: Since the array is a static sized object, if it becomes filled, then any add type of operation, whether it is a List insert, a Queue enqueue or a Stack push, should be prevented. This can be determined by first checking to see if the structure is full or not. This is not necessary if the data structure is implemented using a linked list since (we assume that) there will always be dynamic memory available to add a new element.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 11) What is the result of calling foo(a, 2, 9);? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: a. Explanation: The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 9) results in the base case being executed immediately because 9 = = a.length and the base case returns 0.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 10) What is the result of calling foo(a, 3, 0);? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: a. Explanation: The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 3, 0) finds the number of 3s in a. There are none.

23) Which String below would result in patternRecognizer returning true? "abcba" "aaabbb" "abcde" "aabba" all of the above Strings will result in the method returning true

Answer: a. Explanation: The method patternRecognizer returns true if the String is a palindrome. This can be seen by analyzing the code. If the String has 1 character, or 2 characters which are equal, it returns true, otherwise if the first and last characters are the same, it recursively calls itself with the substring starting at character 1 and going to the second to last character (so, since in "abcba" the first and last characters are the same, the method is called recursively with the substring "bcb"). Only if the first and last characters do not match is false returned. The only palindrome in the list of options is a, "abcba".

16) What is returned by return head.info; ? a) 20 b) 11 c) 13 d) 19 e) 6

Answer: a. Explanation: The variable head references the first item, and so head.data is the instance data info of the first item, which stores 20.

12) Assume Node2 is defined as follows: int data; Node2 a, b; where a refers to the Node2 before this one in a linked list and b refers to the Node2 after this one in a linked list. Node2 could then be used to create which of the following variations of a linked list? a) singly linked list b) doubly linked list c) singly linked list with a header node d) singly linked list with a top node e) circularly linked list

Answer: b. Explanation: Because each item in the linked list has a reference to both the next node and the previous node, the list is known as a doubly linked list. With only a reference to the next node, the list would be known as a singly linked list. A list with a header node has a special node which has references to both the first node in the list and the last node in the list (often refered to as a head and a tail).

9) Assume Node temp references the last element of the linked list. Which of the following conditions is true about temp? a) (temp.info = = 0) b) (temp.next = = null) c) (temp = = head) d) (temp = = null) e) (temp.next = = null && temp.info = = null)

Answer: b. Explanation: Since temp is the last Node in the list, there is no next node, so temp.next is null. The answer in e is incorrect because temp references the last Node and this Node does have a value, so temp.info will equal some int value.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 13. What is the result of bar(a, 8);? a) 0 b) 5 c) 6 d) 12 e) 34

Answer: b. Explanation: The bar method recursively sums the elements of array a starting at the location of the second parameter (8 in this case). So, bar(a, 8) sums up only the last element in the array, 5, and so 5 is returned.

14) What does the following recursive method determine? public boolean question16(int[ ]a, int[ ] b, int j) { if(j = = a.length) return false; else if (j = = b.length) return true; else return question16(a, b, j+1); } a) Returns true if a and b are equal in size, false otherwise b) Returns true if a is larger than b, false otherwise c) Returns true if b is larger than a, false otherwise d) Returns true if a and b have no elements e) Returns the length of array a + length of array b

Answer: b. Explanation: The method returns true if the third parameter, j, is equal to the length of b but not equal to the length of a. Thus, the method returns true if the third parameter has reached the value indicating the end of array b butnottheendofarrayasothisistrueifaislargerthanb. Ifaandbareequallengthorifaisshorterthanb,falseis returned.

18) What will the statement head.next.next = head.next.next.next; accomplish? a) it will result in the list ending after 13 b) it will result in the value 13 being deleted from the list c) it will result in the list ending after 19 d) it will result in the value 19 being deleted from the list e) it will result in the list ending after 12

Answer: b. Explanation: The reference head.next.next is of the second Node in the list's next instance data, or 11's next. By setting this Node's next field to be head.next.next.next, this Node now references the Node storing 19 rather than 13, so it deletes 13 from the list.

17) What is the result to the linked list of the following instructions? Assume that newNode is a Node, already constructed. newNode.data = 1; newNode.next = head.next; head.next = newNode; a) The value 1 is inserted into the linked list before 20 b) The value 1 is inserted into the linked list after 20 and before 11 c) The value 1 is inserted into the linked list after 11 and before 13 d) The value 1 is inserted into the linked list after 13 and before 19 e) The value 1 is inserted into the linked list after 20 and the rest of the list is lost

Answer: b. Explanation: The statement newNode.next = head.next; sets the new node's next field to equal the second item in the list, so the new node, which stores 1, is inserted before 11. The statement head.next = newNode resets the first Node's next field to reference the new node, so 1 is now inserted after 20 and before 11.

18) The solution to the Towers of Hanoi has a(n) _____ complexity. a) linear b) polynomial c) logarithmic d) exponential e) bad

Answer: d. Explanation: The complexity for Towers of Hanoi is 2^n - 1, which is known as exponential because, as n increases by 1, the number of moves doubles, or the complexity increases exponentially.

19) A variation of a linked list is a circular linked list where the last Node in the list has next = head rather than next = null. One problem with this type of list is that a) it wastes memory space since head already points at the first Node, so the last one does not need to b) there is no ability to add a new Node at the end of the list since the last Node points at the first Node c) it is more difficult to traverse the list since the old terminating condition, (next = = null), is no longer true for the last node d) a header Node for this type of list is more complex e) all of the above

Answer: c. Explanation: Answers a, b and d are not true. This list uses no more memory than an ordinary linked list, adding a Node at the end requires the same amount of effort as before, and a header Node would be no different than before. However, answer c is true, the decision of whether there is another Node in the list or not can no longer be determined by testing (next = = null) since the last Node's next field is equal to head instead of null.

19) If traverse is first called with traverse(0, 0); what will the first recursive call of traverse be? a) traverse(0, 0); b) traverse(0, 1); c) traverse(1, 0); d) traverse(1, 1); e) traverse(0, -1);

Answer: c. Explanation: Since row and grid do not equal the bottom right node in the grid (that is, we haven't found the solution yet), the else clause, done = traverse(row + 1, column);, is executed, resulting in traverse(1, 0); being called.

8) Which of the following instructions would create an initially empty linked list? a) Node head = new Node( ); b) Node head = Node; c) Node head = null; d) Node head = new Node(0); e) Node head = list;

Answer: c. Explanation: The initial linked list will be empty, and so head should be null to indicate that there are no Nodes in the list yet. The answer in b is syntactically invalid, and the answers in a and d may be invalid depending on what parameter(s) the Node constructor expects, but in any event, the answers in a and d will create a Node, and therefore the initial list will not be empty.

24) This type of linked list is referred to as a a) singly linked list b) doubly linked list c) singly linked list with a header node d) doubly linked list with a header node e) singly linked list with a head and rear references

Answer: c. Explanation: The list is singly linked because there is only a next reference in each Node rather than a next and previous. Further, header is a header node for the list. The header node does contain a reference to head and rear, making answer e partly correct, but the references are part of a header node that includes the count (number of Nodes) in the list, so answer c is more correct.

For questions 1 - 2, use the following recursive method. public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } 1) If the method is called as question1_2(8, 3), what is returned? a) 11 b) 8 c) 5 d) 3 e) 24

Answer: c. Explanation: The method computes x - y if x > y. The method works as follows: each time the method is called recursively, it subtracts 1 from x until (x == y) is becomes true, and adds 1 to the return value. So, 1 is added each time the method is called, and the method is called once for each int value between x and y.

8) What is wrong with the following recursive sum method? The method is supposed to sum up the values between 1 and x (for instance, sum(5) should be 5 + 4 + 3 + 2 + 1 = 15). public int sum(int x) { if(x = = 0) return 0; else return sum(x - 1) + x; } a) the base case should return 1 instead of 0 b) the recursive case should return sum(x - 1) + 1; instead of sum(x - 1) + x; c) the base case condition should be (x <= 0) instead of (x = = 0) d) the recursive case should return sum(x) + 1; e) the method should return a boolean instead of an int

Answer: c. Explanation: The method does not appropriately handle a negative parameter, such as sum(-5). The result is infinite recursion. We might define a negative parameter as something that should return 0, or allow a negative parameter to compute a negative sum as in: public int sum(int x) { } if(x = = 0) return 0; else if (x < 0) return -1 * sum(-x); else return sum(x - 1) + x;

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 9) What is the result of calling foo(a, 2, 0);? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: c. Explanation: The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 0) finds the number of 2s in a. 2 appears 3 times in array a.

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 6) How many times is the factorial method invoked if originally called with factorial(5)? Include the original method call in your counting. a) 1 b) 4 c) 5 d) 6 e) 7

Answer: c. Explanation: The method is first invoked with factorial(5), which in turn returns 5 * factorial(4), so factorial is invoked again, which in turn returns 4 * factorial(3), so factorial is invoked again, which in turn returns 3 * factorial(2), so factorial is invoked again, which in turn returns 2 * factorial(1), so factorial is invoked again, and finally factorial(1) invokes the base case and returns 1. So, factorial was invoked 5 times.

3) The following method should return true if the int parameter is even and either positive or 0, and false otherwise. Which set of code should you use to replace ... so that the method works appropriately? public boolean question3(int x) { ... } a) if (x = = 0) return true; else if (x < 0) return false; else return question3(x - 1); b) if (x = = 0) return false; else if (x < 0) return true; else return question3(x - 1); c) if (x = = 0) return true; else if (x < 0) return false; else return question3(x - 2); d) if (x = = 0) return false; else if (x < 0) return true; else return question3(x - 2); e) return(x = = 0);

Answer: c. Explanation: The method will recursively call itself subtracting 2 from x until x = = 0 or x < 0. If x = = 0, then it x - 2 * i == 0 (for some int value i) or x = = 2 * i, so x must be even. Otherwise, the recursion ends when x < 0, meaning that the original x was odd or less than 0.

20) Assume at some point in processing, grid's row 0 has become 3 3 3 1 1 1 0 0. Which direction will next be tried? a) up b) down c) left d) right e) none, the recursion ends at this point

Answer: d. Explanation: The current position is (2, 0), so it is not out of bounds or the lower right corner, and the current grid value was a 1, so the path is still valid. Therefore, the first instruction inside the else statement is executed, calling traverse with (row + 1, column) which represents the next position to the right.

15) Why is the following method one which has infinite recursion? public int infiniteRecursion(int n) { if (n > 0) return infiniteRecursion(n) + 1; else return 0; } a) Because there is no base case b) Because the base case will never be true c) Because the recursive call does not move the parameter closer to the base case d) Because the recursive call moves the problem further away from the base case e) None of the above, there is no infinite recursion in this method

Answer: c. Explanation: The recursive case has the method calling itself with the same parameter, and so n does not change, thus if (n > 0) is initially true, it will remain true.

5) Which of the following criticisms of an array is applicable to a Java array? a) It is an inefficient structure to access random elements b) It only supports First-in First-out types of accesses c) It is fixed in size (static) d) It cannot be used to create an Abstract Data Type such as a Queue or Stack e) All of the above

Answer: c. Explanation: The size of any array in Java is fixed when the array is instantiated. If, in adding elements to the array, it becomes filled, the array itself cannot change in size. A new array could be created with the old array elements moved into the new array, but this is inefficient.

20) Which of the following lists of operations is used to see the top item of a stack without removing it from the stack? a) push b) pop c) peak d) see e) top

Answer: c. Explanation: The three commands associated with a Stack are push, pop and peak. Push adds a new element to the top of the Stack, pop removes the top element off of the Stack and peak returns the top of the Stack without removing it.

21) Which of the following grids would be the result after traverse has completed all of its recursive calls? a) 11111100 00100100 00100110 00110010 00011000 00001111 b) 33333300 00300300 00300330 00330030 00033000 00003333 c) 77733300 00700300 00700330 00770030 00077000 00007777 d) 77777700 00300700 00300770 00330070 00033000 00003333 e) 33377700 00300700 00300770 00330070 00033000 00003333

Answer: c. Explanation: When a point in the maze is tried, its value is changed from 1 to 3, but if the end of the maze is found, the current row, column index is changed to 7. So the path is reflected as 7s and the tried but incorrect path is reflected as 3s and any untried parts of the path are reflected as 1s. For this maze, all legal path parts will have been tried before the solution is found, so the path leading to the exit is comprised of 7s and the remaining paths are comprised of 3s.

15) What will be returned by return head.next.next.next.info; ? a) 20 b) 11 c) 13 d) 19 e) 12

Answer: d. Explanation. The variable head references the first item, which stores 20, head.next references the second item, which stores 11, head.next.next references the third item, which stores 13, and head.next.next.next references the fourth item, which stores 19.

3) Which of the following is considered an Abstract Data Type? a) array b) reference variable c) any of the primitive types (e.g., int, double, char) d) ArrayList e) all of the above

Answer: d. Explanation: An Abstract Data Type comprises a data structure and the methods to manipulate and access the data structure. Of those listed, only the ArrayList combines both of these. The array is a data structure but without the methods (such as an insert method or a search method) while the reference variables and primitive types are data but not data structures.

For questions 1 - 2, use the following recursive method. public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } 2) Calling this method will result in infinite recursion if which condition below is initially true? a) (x = = y) b) (x != y) c) (x > y) d) (x < y) e) (x = = 0 && y != 0)

Answer: d. Explanation: If (x < y) is true initially, then the else clause is executed resulting in the method being recursively invoked with a value of x - 1, or a smaller value of x, so that (x < y) will be true again, and so for each successive recursive call, (x < y) will be true and the base case, x == y, will never be true.

23) Previously, to iterate through a linked list, we used a while loop. Which of the following for-loops could replace the previous while loop that would start at head and go until temp == null? a) for(Node temp = header.front, int j = 0; j < header.count; temp = temp.next) { ... } b) for(int j = 0; j < header.count; j++) { ... } c) for(Node temp = header.front; temp != header.rear; temp = temp.next) { ... } d) for(Node temp = header.front, int j = 0; j < header.count; temp = temp.next, j++) { ... } e) for(Node temp = header.front, int j = 0; j < header.count && temp != header.rear; temp = temp.next, j++) { ... }

Answer: d. Explanation: Since header stores the number of elements in the linked list, we can start with a counter (j) at 0 and iterate while the counter is less than header.count, adding 1 after each iteration. We also need to make sure that we go from Node to Node. Only the loop in answer d accomplishes both of those steps. Note that answer c might seem right, but would stop once the loop has reached the last Node, not once the loop has finished with the last Node.

25) The expression LIFO stands for a) LIst FOundation b) LInk FOrmation c) Last In Front Of d) Last In First Out e) Long Int Float Object

Answer: d. Explanation: The Stack is a data structure in which items are added at the top end and removed from the top end, so the most recent item added is the first one removed (last in, first out). It is abbreviated as LIFO for convenience.

17) If there are 6 disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a) 6 b) 13 c) 31 d) 63 e) 127

Answer: d. Explanation: The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1 extra move, or 1 move + 1 move + 1 extra move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks. For 3 disks this takes 7 moves, for 4 disks this takes 15 moves, for 5 disks this takes 31 moves and for 6 disks this takes 63 moves.

16) If there are 2 disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: d. Explanation: The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1, or 1 move + 1 move + 1 move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks.

25) If the statement a.substring(1, a.length( ) - 1) were changed to be (a.substring(1, a.length( )), then the method would a) have infinite recursion unless the String were null b) always return true c) always return false d) return true only if all characters of the String were the same e) return true only the String had only two characters and they were the same

Answer: d. Explanation: The original method recursively calls itself with a substring equal to the String minus the first and last characters. This new version would recursively call itself with a substring equal to the String minus the first character. The method would return true if the first character of the String (or substring) equaled the last character. Since the substring for each recursive call is the same as the previous String less the first character, it winds up comparing each character in the String to the last in the String and returning true only if each character of the String equals the last character. This means all of the characters are the same.

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 4) What is returned if factorial(3) is called? a) 0 b) 1 c) 3 d) 6

Answer: d. Explanation: With factorial(3), x > 1, so it returns 3 * factorial(2), with factorial(2), x > 1 so it returns 2 * factorial(1), with factorial(1), 1 is returned, so we have 3 * 2 * 1 = 6.

1) An array can be classified as what type of object? a) dynamic b) ordered c) first-in first-out d) heteogeneous e) collection

Answer: e. Explanation: An array stores a group of items and is dubbed a collection type (as opposed to other types that can store a single item). There are numerous collection types, the array being one composed only of homogeneous items (the array stores multiple items but they all must be of the same type).

22) In order to gain a last-in first-out access to data, which type of structure should be used? a) ArrayList b) Array c) Linked List d) Queue e) Stack

Answer: e. Explanation: The Stack is a data structure that allows only a last-in first-out (LIFO) access. Queues offer only a first-in first-out (FIFO) access. The Vector, Array and Linked List all offer any form of access desired.

7) The advantage of creating a BookList using a linked list instead of using an array is that the linked list a) offers easier access to a random element in the list b) uses less memory c) is easier to implement and debug d) can store types other than Books unlike the array e) is dynamic and so can be any size needed

Answer: e. Explanation: The advantage of the linked list over the array to implement such data structures as lists of items is that more items can always be added to it. This is known as a dynamic structure, unlike the fixed-sized array which is known as a static structure. Disadvantages of the linked list are that they are no easy to access randomly, unlike an array, and they are often more difficult to implement and debug than code using arrays. Further, while the linked list stores one Node for each item in the list, each Node requires at least two data items, the information, and a link to the next Node, so they may use more memory than an array.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 12) What is the result of calling bar(a, 0);? a) 0 b) 5 c) 6 d) 12 e) 34

Answer: e. Explanation: The bar method recursively sums the elements of array a starting at the location of the second parameter. Since the starting point is location 0, this call sums all elements of a (which equals 34).

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 7) What condition defines the base case for this method? a) (x>1) b) (x==1) c) (x==0) d) (x<=0) e) (x<=1)

Answer: e. Explanation: The if condition is (x > 1) but this is the recursive case, so the base case is the opposite condition. The opposite of (x > 1) is (x <= 1).


संबंधित स्टडी सेट्स

Patient Care Ch. 7 Review Questions

View Set

Osmoconformers and osmoregulators

View Set

Operations CH 3: Statistical Process Control

View Set

Chapter 66: Care of Patients with Urinary Problems

View Set

Theorems 5-1 to 5-12 and Corollary

View Set

Chapter 4 - The Tissue Level of Organization

View Set