CS2114 - First Halfish
Given the following Boolean expression: (jordan.getGridX() < 100) && (jordan.getGridY() >= 55) Which of the following is logically equivalent?
!((jordan.getGridX() >= 100) || (jordan.getGridY() < 55))
If the coke guy put a soda with "Bro" into the front of the vending machine, followed by "Sidekick" and "Better Half," in what order will the machine users receive the cokes?
"Better Half" "Sidekick" "Bro"
For large values of n which statement is true?
(n2 + n ) / 2 behaves like n^2
How many objects are created in the following declaration? String name;
0
What does the following Java code print? int sum=0; for (int i=0; i>100; i++) { sum += i; } System.out.println(sum);
0
A social media service is hosting a weeklong competition, awarding a limited number of prizes to participating users. To participate a user must post an amusing image, video, or story that matches a specific theme to the competition page. At the end of the week the software used to administer the competition anonymizes all posts, then forwards each to a human judge to evaluate and score. Once scored the software ranks each user's post. Posts with the same scores are put in groups and are further ranked first in lexical order based on their last name (earlier names are ranked higher, for example a user with a last name of Doe would rank higher than a user with a last name of Smith), then by the timestamp of their application (the earlier application ranked higher than the later application and so on). The software then starts from the top of the ranked listing, automatically awarding prizes to each user from top down until all prizes have been awarded. Consider the possible ethical implications or dilemmas and answer the questions below. What ethical principle could possibly be violated by the competition software ranking scored posts by last name, then by timestamp, instead of by timestamp then last name, ?
1.4 Be fair and take action not to discriminate.
The next two questions are based on the Social Media Competition Case Study described below. Case Study - Social Media Competition A social media service is hosting a weeklong competition, awarding a limited number of prizes to participating users. To participate a user must post an amusing image, video, or story that matches a specific theme to the competition page. At the end of the week the software used to administer the competition anonymizes all posts, then forwards each to a human judge to evaluate and score. Once scored the software ranks each user's post. Posts with the same scores are put in groups and are further ranked first in lexical order based on their last name (earlier names are ranked higher, for example a user with a last name of Doe would rank higher than a user with a last name of Smith), then by the timestamp of their application (the earlier application ranked higher than the later application and so on). The software then starts from the top of the ranked listing, automatically awarding prizes to each user from top down until all prizes have been awarded. Consider the possible ethical implications or dilemmas and answer the questions below. Anonymizing posts (removing identifying data etc.) before forwarding to the human judge supports which of the following ACM Ethical Principles?
1.4 Be fair and take action not to discriminate.
Going to work one day you notice a news headline describing a scandal implicating a celebrity of financial fraud, a celebrity who happens to be a customer of the financial organization you work for. Your curiosity is piqued and you wonder if the allegations are true. Which TWO ethical principles could possibly be violated if you give in to curiosity and look at the customer's financial information?Choose the TWO ACM Ethical Principles which BEST apply.
1.6 Respect privacy. 2.8 Access computing and communication resources only when authorized or when compelled by the public good.
Given: class Link { public Link next; //Point to next node in list public Object data; //Value for this node //Constructors public Link(Object dataIn, Link nextIn) { this.data = dataIn; this.next = nextIn; } public Link(Link nextIn) { this.data = null; this.next = nextIn; } Object getData() { // Return the data field return data; } void setData(Object newData) { // Set the data field data = newData; } Link getNext() { // Return the next field return next; } void setNext(Link newNext) { // Set the next field next = newNext; } } Given a linked chain of Integers reference by the variable head which contains data 20, 30, 10, 5 in that order. Consider the impact of the execution of the following lines of code: Link p = head; Link q = head.next; Link r = q.next; Integer myVal = q.data
10
Suppose you have an array of seven int values called test containing the following data: Trace the execution of the following code: int x = 0; int y = 0; for (int i = 0; i < test.length; i++) { if (test[i] % 2 == 1) { y += test[i]; } else { x += test[i]; } } What is the value of y when this loop is done? [8, 6, 0, 3, 4, 9, 2]
12
What does the following Java code print: int sum=0; for (int j=0; j<3; j++) { for (int i=0; i<4; i++) { sum += 1; } } System.out.println(sum);
12
What does the following Java code print? int sum=0; for (int i=0; i<10; i+=4) { sum += i; } System.out.println(sum);
12
Suppose you have an array of seven int values called test containing the following data: [18, 6, 0, 3, 36, 9, 24] Trace the execution of the following code: int x = 0; int y = 0; for (int i = 0; i < test.length; i++) { if (test[i] % 6 == 0) { x++; y += i; } } What is the value of y when this loop is done?
13
Imagine a class named Club, to be a member a person must be aged 15 or older, but less than50. What values would you use to boundary test a method designed to check if aperson was a suitable age to join?
14, 15, 49, 50
What does the following Java code print? int sum=0; for (int i=1; i<=5; i++) { sum += i; } System.out.println(sum);
15
Assume that an object of the following class has just been created: public class Unknown { private int x; public Unknown() { x = 17; method1(); method2(5); method3(); System.out.println(x); // Line D } public void method1() { --x; int x = this.x; x++; System.out.println(this.x); // Line A } public void method2(int x) { x++; System.out.println(x); // Line B } public void method3() { --x; int x = 2; x++; System.out.println(x); // Line C } }
16
For this question, refer back to the code in linkedchain.java What if the line statement chain.add(16); was added after the line chain.add(57); what would the the order of the integers be starting at the front of the chain?
16, 57, -2, 10
In Java, what value will the variable i have after this declaration: int i = 2 + 8 % 4;
2
How many objects and object references would we have if the following code is executed? Student first_st = new Student();Student second_st = new Student();Student third_st = second_st;
2 objects, 3 references
Given: class Link { public Link next; //Point to next node in list public Object data; //Value for this node //Constructors public Link(Object dataIn, Link nextIn) { this.data = dataIn; this.next = nextIn; } public Link(Link nextIn) { this.data = null; this.next = nextIn; } Object getData() { // Return the data field return data; } void setData(Object newData) { // Set the data field data = newData; } Link getNext() { // Return the next field return next; } void setNext(Link newNext) { // Set the next field next = newNext; } } Given a linked chain of Integers reference by the variable head which contains data 20, 30, 10, 5 in that order. Consider the impact of the execution of the following lines of code: Link p = head; Link q = head.next; Link r = q.next; Integer myVal = q.data What is the value of head.data?
20
Suppose you have an array of seven int values called test containing the following data: [8, 6, 0, 3, 4, 9, 2] Trace the execution of the following code: int x = 0; int y = 0; for (int i = 0; i < test.length; i++) { if (test[i] % 2 == 1) { y += test[i]; } else { x += test[i]; } }
20
If there is an if statement with 2 conditions, how many test cases are necessary?
3
Given: class Link { public Link next; //Point to next node in list public Object data; //Value for this node //Constructors public Link(Object dataIn, Link nextIn) { this.data = dataIn; this.next = nextIn; } public Link(Link nextIn) { this.data = null; this.next = nextIn; } Object getData() { // Return the data field return data; } void setData(Object newData) { // Set the data field data = newData; } Link getNext() { // Return the next field return next; } void setNext(Link newNext) { // Set the next field next = newNext; } } Given a linked chain of Integers reference by the variable head which contains data 20, 30, 10, 5 in that order. Consider the impact of the execution of the following lines of code: Link p = head; Link q = head.next; Link r = q.next; Integer myVal = q.data What is the value of head.next.data?
30
Suppose you have an array of seven int values called test containing the following data: Trace the execution of the following code: int x = 0; int y = 0; for (int i = 0; i < test.length; i++) { if (test[i] % 4 == 0) { x++; y += test[i]; } } [8, 14, 0, 12, 10, 9, 20]
4
In the Java language, what is the value of this expression? 8 / 5 + 3.2
4.2
Consider the following: When foo is executed, what is printed out? public void foo () { int x = 42; int y = 24; mystery (x, y); System.out.println (x + " " + y); } public void mystery (int var1, int var2) {int temp = var1; var1 = var2;var2 = temp;}
42 24
The following loop should reverse the order of the elements in the array. Trace the loop to find the bug. Which test case(s) fail? for (int i = 0; i < values.length / 2; i++) { int temp = values[i]; values[i] = values[values.length - 1]; values[values.length - 1] = temp; }
5 7 -3 19 42] [2 4 6 8 10] [-8 7 -6 5 -4 3]
For this question, refer back to the code in linkedchain.java What if the line statement chain.add(40); was added before the line chain.add(10); what would the the order of the integers be starting at the front of the chain?
57, -2, 10, 40
What will be printed by this code? public static void main(String [] args){ int number = 6; int secondNumber = changeNumber (number); System.out.print(number + " " + secondNumber); } public static int changeNumber(int number){ number = 12; return number; } 6 6 6 12 12 6 12 12
6 12
Given: class Link { public Link next; //Point to next node in list public Object data; //Value for this node //Constructors public Link(Object dataIn, Link nextIn) { this.data = dataIn; this.next = nextIn; } public Link(Link nextIn) { this.data = null; this.next = nextIn; } Object getData() { // Return the data field return data; } void setData(Object newData) { // Set the data field data = newData; } Link getNext() { // Return the next field return next; } void setNext(Link newNext) { // Set the next field next = newNext; } } Given the linked chain: head -> 55 -> 65 -> 75 -> 85 -> 95 -> 100 What is the value of myVal given the following code: Link q = head.next; Link r = q.next; MyVal = r.next.data;
85
Which of the following statements are true? Check all that apply. A try block can have only one catch block A catch block must have an associated try block A try block can have multiple catch blocks Code in a finally block will always execute whether or not an exception occurs in the try block
A catch block must have an associated try block A try block can have multiple catch blocks Code in a finally block will always execute whether or not an exception occurs in the try block
J.C. Knight (2002) describes safety-critical systems as "those systems whose failure could result in loss of life, significant property damage or damage to the environment". John C Knight. 2002. Safety critical systems: challenges and directions. In Proceedings of the 24th international conference on software engineering.547-550.1 As lead for a software development project involving a safety-critical system you are being pressured by your manager to release the system before it has been adequately tested. Approving the release of the system before completing testing would be:
A violation of the ACM Code of Ethics and Professional Conduct
What output is produced when the test method is invoked? public static void test() { String a = "6we"; String b = "0"; System.out.print("A"); try { int result = Integer.parseInt(a) / Integer.parseInt(b); System.out.println(result); } catch (NumberFormatException nfe) { System.out.print("B"); } catch (ArithmeticException ae) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E"); }
ABDE
What will be outputted? int income = 30;boolean condition1 = true, condition2 = true;if(income < 100)if(income > 10)if(condition1){System.out.print("A");if(income < 20)System.out.print("B");}elseSystem.out.print("C");if(!condition2){if(income > 50)System.out.print("D");}else{System.out.print("E");}
AE
Junit testing... Provides ability to test specific methods Uses assert statements instead of print statements Should be used throughout development Has a setUp method useful for initializing variables All of the above
All of the above
What is ethics? An area of study that deals with ideas about what is good and bad behavior Moral principles that govern a person's behavior or the conducting of an activity A branch of philosophy dealing with what is morally right or wrong All of the above
All of the above
Given the following statement: public ArrayList<Person> friends = new ArrayList<Person>(); Select all of the following that are true:
Any Person object can be added to friends Any object that is a subclass of Person can be added to friends
Based on the demonstrated implementation of LinkedBag1. What is the output of the following code? LinkedBag1 bag; bag = new LinkedBag1(); bag.add("Alisha"); bag.add("Ashley"); bag.add("Ariel"); System.out.println(bag.toArray(new String[25])[0]);
Ariel
What type of exception will be thrown when the myMethod() method is invoked? public static void myMethod() { int a = 6; int b = 0; try { int result = a/b; System.out.println(result); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } catch (ArithmeticException ae) { ae.printStackTrace(); }}
ArithmeticException
Which of the following could result in code throwing a null pointer exception? Check all that apply Attempting to invoke a method from a null object Attempting to use an object that was declared but never instantiated Attempting to use an object that was instantiated but never declared Using an object that became null
Attempting to invoke a method from a null object Attempting to use an object that was declared but never instantiated Using an object that became null
Where does new data get added to this linked implementation of a bag?
Beginning
Given an array of doubles named values, what does the following code do: double total = 0; for(double element : values) { total = total + element; } double average = 0; if (values.length > 0) { average = total/values.length; }
Calculates the sum and average of the values
Which of these relationships best exemplify the "IS-A" relationships in object-oriented programming (OOP)? Empire State Building IS-A Building Cat IS-A Mammal Angry Cat IS-A Cat (Note that "Angry Cat" is a specific cat that has become an online internet meme) All of the above None of the above
Cat IS-A Mammal A and C are wrong because the Empire State Building would be best be described as an instance of the category Building, while Angry Cat is an instance of the category Cat. B is correct because Cat is a sub-category of Mammal, which best exemplifies the IS-A relations. In OOP, the IS-A relationship is used to denote relationships between classes, which are sort of like categories.
Why are ethics important to computer scientists and computing professionals?
Computing Technology can have positive and negative effects on lives, society, and the world; computer scientists and computing professionals are responsible for considering the ethical implications and potential impact of the decisions they make
The simplified UML diagram above shows the relationships among Java classes Bird, Crow, and Duck. Suppose Bird has a fly(Location place) method, but we want Crows to makeNoise() just before they take off and then behave like other Birds. Assuming Crows have a makeNoise() method, we should Java OOP checkpoint 3
Define a fly method in Crow that just consists of makeNoise() and super.fly(place) public void fly(Location place) { this.makeNoise(); super.fly(place); }
A software bug resulted in incorrect calculations being applied to 100 account holder's financial data during a batch processing job. The organization's directors have requested that this be rectified as soon as possible. You need to advise your development team of the correct course of action. Which of the following would be the LEAST ethical approach to correcting the financial data for each of the affected accounts?
Directly interacting with the backend (database/data repository) to make changes, manually retrieving each account and updating the records by keyboard entry
For any JUnit test class, when is the setUp() method executed?
Each time before a test method is executed
What are the Eight Key questions used to evaluate the ethical dimensions of a problem or situation? Select all which apply.
Fairness Outcomes Responsibilities Character Liberty Empathy Authority Rights
Your organization's online services have recently been hit by a flurry of Denial of Service attacks. Denial of Service attacks occur when an attacker, or attackers, attempt to make a computing device, service, or network resource unavailable to users. Attacks may flood a server or resource with fake service requests to overload systems in order to prevent legitimate requests from being fulfilled. Analysis of the attacks suggests that you are dealing with a Distributed DOS (DDOS), where requests are sent from many machines, for example Botnets are zombie computers that receive/execute remote commands without the owner's knowledge. Your team is attempting to determine an appropriate course of action. One approach is to maintain a Blacklist/Whitelist in which access from blacklisted addresses (individual machines, networks or even whole countries) is prevented and access from whitelisted addresses is always allowed. Using the 8 Key questions you must consider if permanently blacklisting is an ethical solution. Which FOUR questions would best help you determine if permanently blacklisting certain addresses is an ethical course of action? (Select the best 4 options.)
Fairness, liberty, responsibilities, outcomes
Match the subset of the Eight Key questions used to evaluate the ethical dimensions of a problem or situation to their associated descriptions provided by James Madison University in the article titled "The Eight Key Questions (8KQ)".
Fairness: How can I act justly etc. Outcomes: What achieves the best etc... Liberty: How does respect for etc... Empathy: What would i do if I etc....
Given an array of ints named values, what does the following code do: for (int i = 0; i < values.length; i++) { values[i] = i * i; }
Fills the array with squares (0, 1, 4, 9, 16, ...)
Given an array of ints named values, what does this code do? double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }
Find the max value
The lifetime of a parameter in Java is
From when its method is called until it returns
Given: Link head = new Link(null); head.data = new Integer(20); head.next = new Link(new Integer(30), null); head.next.next = new Link(new Integer(10), null); Link temp = head.next.next; temp.next = new Link(new Integer(5), null); What would the linked chain look like if the following code was executed next? temp.next.next = head; head.next = null; head = temp;
Head -> 10 ->5 -> 20
What should be done to correct the following code? public class exam {float mark;public static void main(String[]arg){float aCopyofMark;exam e = new exam();System.out.println( e.mark + aCopyofMark);}}
Initialize aCopyofMark
Given the following code: public class MoveData { public static <T> void shiftUpArray(T[] dataset) { for (int i =1; i < dataset.length; i++) { dataset[i] = dataset[i-1]; } } public static void main(String args[]) { } ... } Select all of the following that are possible code inside the main method of MoveData?
Integer[] bits = {32, 64, 256, 512}; shiftUpArray(bits); WritingInstrument[] box = new WritingInstrument[20];box[0] = new Marker(); box[1] = new Marker(); box[2] = new Pencil(); shiftUpArray(box); String[] oceans = {"Pacific", "Indian", "Atlantic", "Arctic"}; shiftUpArray(oceans);
What is usually an advantage of using a chain to implement the ADT bag?
It avoids moving data when adding or removing bag entries.
The use of a generic data type is preferred over using Object as a general class in a collection because...
It ensures that all the members of the collection are objects related by inheritance.
For this question, refer back to the code in linkedchain.java If the first line of the add method was changed from Node newNode = new Node(newEntry); to Node newNode = new Node(newEntry, null);
It wouldn't impact the final linked chain
A stack is
LIFO (last in first out)
Quickly peruse the article titled "Facebook has a new process for discussing ethics. But is it ethical?" (link below), paying particular attention to the "emotional contagion study", then answer the question below. https://www.theguardian.com/technology/2016/jun/17/facebook-ethics-but-is-it-ethical (Links to an external site.) (Links to an external site.)_ _ _ A social media service has uncovered evidence to suggest that manipulating the nature and priority of the content a user sees in their social media feed could affect their emotional state. Being an unanticipated effect of their technology the social media company is considering exploratory research involving deliberately manipulating the content for a portion of the users, then monitoring and observing the subsequent impact. Which of the 8 Key questions would be most relevant if users were not previously advised that they would become part of such research when they registered to use the service?
Liberty
Which loop starts at the first node of a non-empty linked chain and loops all the way through the chain?
Link curr = head; While (curr.next != null) curr = curr.next;
Which of the following is not true about an interface in Java?
Must include a constructor
Developers must be able to assess the quality of their code before submitting it for review. In addition to assessing code logic and testing code functionality a developer should also assess code quality with respect to style and documentation. Which of the following should, at a minimum, be included in a developer's style and documentation review checklist? (Select ALL that apply)
Naming Formatting and Indentation Documentation and Commenting Other matters of style
Given the code: if (x >= 0) System.out.println("1"); else if (x < 20) System.out.println("2"); else System.out.println("3"); System.out.println("4"); x < 0 x >= 0 x < 20 All values of x None of the above.
None of the Above
What code would you use to test if the sum() method of the MyCalculator class (below) is throwing the correct exception? public int sum(String num1String, String num2String) { int sum = 0; try { int num1 = Integer.parseInt(num1String); int num2 = Integer.parseInt(num2String); sum = num1 + num2; } catch (NumberFormatException nfe) { throw new NumberFormatException(); } return (sum); }}
NumberFormatException myNFE = null; try { calc.sum("2hello", "3"); } catch (NumberFormatException nfe) { myNFE = nfe; } assertNotNull(myNFE);
If an algorithm requires 7 basic operations for an algorithm with a problem size of n, the algorithmic complexity is
O(1)
If the top of the stack is the last element in the array what is the complexity for pop() in big Oh notation?
O(1)
If the top of the stack is the last element in the array what is the complexity for push(newEntry) in big Oh notation?
O(1)
What is the time complexity for adding an entry to a fixed-size array-based bag ADT?
O(1)
What is the time complexity for adding an entry to a linked-based bag ADT?
O(1)
What is the big Oh of the following code snippet?
O(logn)
If the top of the stack is the first entry of the array what is the complexity for pop() in big Oh notation?
O(n)
If the top of the stack is the first entry of the array what is the complexity for push(newEntry) in big Oh notation?
O(n)
What is the worst-case time complexity for searching a linked-based bag ADT for a particular entry?
O(n)
What is the big Oh of the following code snippet?
O(n^2)
What is the big Oh of the following code snippet?
O(n^3)
Imagine you have an empty stack of strings named stack. List the contents of the stack from top to bottom after the following operations have executed. (Assume that the pop method returns the element that waspopped.) stack.push("K");stack.pop();stack.push("P");stack.push("G");stack.push("R");String str = stack.pop();stack.push("V");stack.push(str);
R V G P
Why is the method signature for the equals method in a Hokie class: public boolean equals(Object obj)?
So that it overrides the equals method defined for the Object class
You are looking for a method getSequence(int n, char c) that returns a String of n characters c. Which of the following will not meet your needs?
String getSequence(int n, char c) { String s = ""; while (n > 0) { s += c; } return s; }
Which of the following recommendations for testing software is good advice? Limit your test cases to one assertion, since each test should check only one expected outcome. Save your testing until after the solution is completely written, so you can concentrate solely on testing without distractions. Test a program with all possible values of input data. Test each piece of your solution as you build it, so you will find errors as quickly as possible. Longer tests that focus on combinations of multiple features are preferable, because they test your code more strenuously.
Test each piece of your solution as you build it, so you will find errors as quickly as possible.
The scope of a variable in Java is:
The part of the program in which it can be used
What will be ouput as a result of a call to the calculate method? private int sum = 0; private int product = 0; public static final int AMOUNT = 5; public void output(){ System.out.println("The sum of the numbers from 1 to " + AMOUNT + " is " + sum); System.out.println("The product of the numbers from 1 to " + AMOUNT + " is " + product); } public void calculate(){ int sum = 0; int product = 1; for (int i = 1; i <= AMOUNT; i++){ sum = sum + i; product = product * i; } output(); }
The sum of the numbers from 1 to 5 is 0 The product of the numbers from 1 to 5 is 0
The following is a valid combination of try and finally blocks. try { // statements } finally { // statements }
True
What does the add method return?
True if the addition is successful, or false if not.
When adding an item to a bag, which of the following statements are true?
You cannot specify the position of the item in the bag.
Suppose you are writing a method in a new class. You are also writing unit test cases to demonstrate that this method works correctly. You know you have written enough test cases to demonstrate the method works as desired when? You have written at least one test case that uses the method. You have written separate test cases for each identifiable "group" of input values and/or output values where the behavior is expected to be similar. You have written at least one test case for every input value that can be given to the method. You have written at least one test case for every output value that can be produced by the method. You have written at least one test case for every input/output value combination that can be given to/produced by the method.
You have written separate test cases for each identifiable "group" of input values and/or output values where the behavior is expected to be similar.
The following loop should make all of the even elements negative. Trace the loop to find the bug. Which test case(s) fail? for (int i = 0; i < values.length; i++) { if (values[i] % 2 == 0) { values[i] *= -1; } } [] [5] [-2 -4] [5 7 -3 19 42] [2 4 6 8 10] [-8 7 -6 5 -4 3] none of the above
[-2 -4] [-8 7 -6 5 -4 3]
The following loop should make all of the odd indices double the entry before it. Trace the loop to find the bug. Which test case(s) fail? for (int i = 1; i < values.length; i+=2) { values[i] = 2 * values[i-1]; } [5] [-2- 4] [5 7 -3 19 42] [2 4 6 8 10] [-8 7 -6 5 -4 3] [] none of the above
[5] [-2- 4] [5 7 -3 19 42] [2 4 6 8 10] [-8 7 -6 5 -4 3] [] none of the above
What does a reference type represent?
a memory address instead of the actual item stored in that address
Suppose you are writing a program for a robot that will go around a building and clean the floor. Your program will contain, among other things, a Robot class and a Building class (with information about the layout of the building). The Building class is also used in a different program for scheduling maintenance of various parts of the building. The relationship between your Robot class and your Building class is best modeled as:
a peer relationship
A set is an abstract data type that is similar to a bag. It is also unordered, but it does not allow duplicates. Examples of sets would be even integers or a collection of the movies you have previously seen. Which bag behavior would need to be modified for a set?
add
Which behavior(s) change the contents of a bag?
add()
Which of the following is usually an advantage of using an array to implement the ADT bag?
adding an entry to a bag is fast
A fixed size array has a limited capacity can waste memory prevents expansion when the bag becomes full all of the above
all of the above
What are the consequences of returning a reference to the bag array in the toArray method? the return variable is an alias for the private instance array variable the client will have direct access to the private instance array variable the client could change the contents of the private instance array variable without using the public access methods all of the above
all of the above
What does the"new" operator do in the following code from the LinkedBag add method:Node newNode = new Node(newEntry); a new node is created the JRE allocates memory for a node object a new object is instantiated all of the above
all of the above
Which of the following are good reasons to write tests that use your bag ADT before the implementation is done? it helps confirm the design it helps check the suitability of the specification it helps check your understanding of the specification all of the above
all of the above
Which of the following JUnit tests will fail?
assertNull(50-25-25);
Assume we have a null variable foo. Which is the correct way to use assert statements when writing junit tests with student.TestCase?
assertNull(foo);
When testing a method that returns a boolean, what assert statements should you use?
assertTrue or assertFalse
An algorithm has time requirements space requirements both a & b none of the above
both a & b
Which method removes all entries of a bag?
clear()
What will be outputted? int num = 3;int counter = 1;boolean condition = true;while(condition){num+= counter++;if(num>10){condition=false;num+= ++counter;}}
counter = 6 num = 19
What are the two fields of a Node?
data and next
Consider the following class for a Ninja: public class Ninja { private int honor; public Ninja(int h) { this.honor=h; } }
false
Which method returns a count of the current number of items in a bag?
getCurrentSize()
A reference to the first node in a linked list is called the _____ reference.
head
The following code will create a series of Link nodes, with the first one pointed to by head. What order will the Link nodes be in after this code is executed? Link head = new Link("A", null);head.next = new Link("C", new Link("B", null));Link p = head.next;head.next = new Link("F", p);Link q = head;Link temp = head.next.next;temp.next = new Link("Z", null);
head -> A ->F -> C -> Z
The following code will create a series of Link nodes, with the first one pointed to by head. What order will the Link nodes be in after this code is executed? Link head = new Link("R", null); head.next = new Link("A", new Link("T", null)); Link c = head.next.next; head.next = new Link("D", c);
head -> R -> D -> T
Given a Node<T> class with constructors Node(T data, Node next) and Node(T data), and the code below, select the resulting list pointed to by head: Node a = new Node("R"); Node b = new Node("S", a); Node d = new Node("T", b); Node c = new Node("U", d); Node head = c;
head -> U->T->S->R
The following code will create a series of Link nodes, with the first one pointed to by head. What order will the Link nodes be in after this code is executed? Link head = new Link("K", null); head.next = new Link("D", new Link("R", null)); head.next.next.next = new Link("F", null); Link c = head; head = c.next; head.next.next.next = c; c.next = null;
head ->D->R->F->K
Which of the following choices will NOT produce the same result as the following condition? if ( mark == 'A' && GPA > 3.5)System.out.println("First Class");else if ( mark == 'A' && GPA <= 3.5)System.out.println("Second Class");else if ( mark != 'A' && GPA > 3.5)System.out.println("Third Class");else if ( mark != 'A' && GPA <= 3.5)System.out.println("Fourth Class");
if ( mark != 'A' || GPA < 3.5)System.out.println("First Class");else if ( mark != 'A' || GPA >= 3.5)System.out.println("Second Class");else if ( mark == 'A' || GPA < 3.5)System.out.println("Third Class");else if ( mark == 'A' || GPA >= 3.5)System.out.println("Fourth Class");
Placing the Node class inside the LinkedBag class makes it a(n)
inner class
What kind of variable is label? public class Labeller extends JFrame {public Labeller () {JLabel label = new JLabel("Field or Variable");}public static void main (String[] args) {new Labeller();}}
local variable, Object Reference
Trace the code starting at line 5. What method activation records are on the call stack from top to bottom at line 10?
method1
Trace the code starting at line 5. What method activation records are on the call stack from top to bottom at line 17?
method2, method1
Trace the code starting at line 5. What method activation records are on the call stack from top to bottom at line 30?
method4, method3, method2, method1
Consider this method skeleton for findDigit(): /** * Returns the number of times the digit d occurs in the decimal * representation of n. * @param n The number to consider (must be non-negative). * @param d The digit to look for (must be 0-9). * Returns the number of times d occurs in the printed representation * of n. */ public int findDigit(int n, int d) // Line 1 { int count = 0; // Line 2 if (__________) // Line 3 { __________; // Line 4 } while (n > 0) // Line 5 { if (n % 10 == d) // Line 6 { count++; // Line 7 } __________; // Line 8 } return count; // Line 9 }
n = n / 10;
Given the following code: for (int i=0; i < values.length; i++) {if (values[i] == searchedValue){found = true; } else {found = false;}} if (found) { System.out.println("found " + searchedValue); } else { System.out.println ("not found"); }
not found
One of the key features of Object-oriented programming is encapsulation. Because of encapsulation, we generally have _________ instance variables and _____________ methods.
private, public
You should express the complexity of an algorithm in terms of its
problem size
Which of the following choices cannot be another constructor for academic class? class Personnel{String name, ID;char qualificationCode;public Personnel(String n, String i, char q){name = n;qualificationCode = q;}public Personnel (){name = null;qualificationCode = ' ';}}class Academic extends Personnel{int teachingHours;public Academic(String n, String i, char q, int t){super(n,i,q);teachingHours = t;}public Academic(int t){super(null, null, ' ');teachingHours = t;}}
public Academic(){super(null, null, ' ');this (0);}
Which of the following would not be an alternate way to write remove() method?
public T remove() {T result = removeEntry(getIndexOf(null)); return result; }
Which of the following 4 implementations could not be used for contains?
public boolean contains(T anEntry) { Node currentNode = firstNode; while (!anEntry.equals(currentNode.getData())) { currentNode = currentNode.getNext(); } // end while return true; } // end contains
Which of the following 5 implementations could not be used for contains?
public boolean contains(T anEntry) { return !isEmpty(); }
Which of the following is a correct implementation of getFrequencyOf?
public int getFrequencyOf(T anEntry) { int frequency = 0; Node currentNode = firstNode; while ((currentNode != null)) { if (anEntry.equals(currentNode.getData())) { frequency++; } // end if currentNode = currentNode.getNext(); } // end while return frequency; } // end getFrequencyOf
Which of the following 5 implementations could not be used for getFrequency?
public int getFrequencyOf(T anEntry) { int i = 0; int count = 0; while(anEntry.equals(contents[i])) { i++; count++; } return numberOfEntries - count; }
A method called myMethod has been defined in a class with the following signature. Which of these four choices cannot be an overloaded alternative for myMethod? public void myMethod (int i, double d)Hint: Overloading a method means creating two methods with the same name but different parameters
public int myMethod (int i, double d)
We implement the following code and receive an error message on the riskyCodeThatWantsToDefer() method call indicating "Unhandled exception type IOException". public void riskyCodeThatWantsToDefer ( ) throws IOException { // some code } public void callingMethod() { riskyCodeThatWantsToDefer(); } We realize that the riskyCodeThatWantsToDefer ( ) method has passed exception handling responsibility to callingMethod( ). To resolve this error we must modify callingMethod ( ). Which of the modifications listed below would resolve the error? (select all which apply)
public static void callingMethod() {try {riskyCodeThatWantsToDefer();}catch (IOException e) {e.printStackTrace();} } Correct! public static void callingMethod() throws IOException {riskyCodeThatWantsToDefer(); }
Which method is in the ArrayBag class is overloaded?
remove
The method remove that has no parameter in the linked implementation
removes the first element in the chain
The fixed array implementation of the method remove that has no parameter in the bag
removes the last entry in the array
Which behavior is not represented in a bag?
reorder the bag
The most efficient approach to dealing with a gap left in an array after removing an entry from a bag is to
replace the entry being removed with the last entry in the array and replace the last entry with null
What does a primitive type represent?
simple indecomposable values
Based on the described approach for BagArray that replaces the removed value with the last value in the array instead of shifting. What would be the state of the following array after a call to remove("twix")? skittles, snickers, snickers, twix, nerds, kitkat
skittles, snickers, snickers, kitkat, nerds
Given [twix, snickers, kitkat, skittles] What would be the result of the call add("snickers")?
snickers, twix, kitkat, skittles, snickers
An incomplete definition of a method is called a _____.
stub
Which one of the codes bellow will NOT compute the summation of 10 consecutive even numbers starting from zero?
sum = 0;for (int i = 0; i <10 ; i= i+2){sum+=i;}
What is the scope error in the main method? public static void main(String[] args) { int target = 4; sum = mystery(target + 1); System.out.println(sum); } public static int mystery(int target) { int sum = 0; for (int i = 0; i < target; i++) { int target = i + 1; sum = sum + target; } return sum; }
sum is not declared
Using the information in the UML diagram above, suppose an Oak prepares for winter like a Tree, but it drops its leaves first. What code should replace ??? in the following code? public class Oak extends Tree { ... public void prepareForWinter(){ this.dropLeaves(); ??? } } Java OOP checkpoint 3
super.prepareForWinter();
Given: Link head = new Link(null);head.data = new Integer(20);head.next = new Link(new Integer(30), null);head.next.next = new Link(new Integer(10), null);Link temp = head.next.next;temp.next = new Link(new Integer(5), null); Which line of code would add another node to the end of the chain?
temp.next.next = new Link(new Integer(45), null);
In the Fixed Size Array implementation of a Bag, depicted below as ArrayBag1, what happens when a client tries to add an element to the ArrayBag1 but the underlying array is full?
the element does not get added
In the demoed array-based implementation of a Stack ADT, the entry peek returns may be found at
the last occupied location in the array
Problem size is defined as the amount of memory an algorithms uses the amount of execution time an algorithm takes Answer the number of items an algorithms processes You Answered none of the above
the number of items an algorithms processes
In the demonstrated linked-chain implementation of a StackADT, when a node is popped from the stack the original first node will no longer be referenced the original first node will have a new value the second to last node will now be the top all of the above
the original first node will no longer be referenced
What is the scope error in the mystery method? public static void main(String[] args) { int target = 4; target = mystery(target + 1); System.out.println(sum); } public static int mystery(int target) { int sum = 0; for (int i = 0; i < target; target++) { int target = i + 1; sum = sum + target; } return sum; }
there are two local variables named target that overlap
Which on these four following definitions is not allowed? abstract class first{void firstMethod(){}}abstract class second{abstract void secondMethod();}class third {abstract void thirdMethod();}class fourth{void fourthMethod(){}}
third (A non-abstract class cannot have abstract methods.)
In Java, what word is used to refer to the current object, or to call one constructor from another in the same class?
this
Which of these Java keywords can be used to intentionally cause an exception?
throw
When an exception occurs within a method, the method creates an Exception object then hands it off to the Java runtime system to take further action, this is referred to as
throwing an exception
Which pair of code blocks are used to enclose exception-prone code, and to check for and handle exceptional events?
try and catch
If the following hierarchy of exception is defined by a user, which option is the correct order of catching these exceptions? class firstLevelException extends Exception{}class secondLevelException_1 extends firstLevelException{}class secondLevelException_2 extends firstLevelException{}class thirdLevelException extends secondLevelException_1{}
try{//code was removed}catch (thirdLevelException e){e.printStackTrace();}catch (secondLevelException_1 e){e.printStackTrace();}catch (secondLevelException_2 e){e.printStackTrace();}catch (firstLevelException e){e.printStackTrace();}
Twix, snickers, skittles, kitkat What does the linked chain look like after remove("kitkat") is called?
twix, snickers, skittles
The operator == tests to see if
two variables reference the same place in the computer's memory
onsider the following Java code: public interface toyCollectionInfo<T> { // 1 private T favoriteToy;private T[] toys;public T getFavorite();public void setFavorite(T fav); } The capital letter "T" on line 1 stands for:
type to be used for the toys
Consider the following Java method: public xxx printGreeting() { // 1 System.out.println("Hello!"); // 2 } // 3 The xxx in line 1 is best replaced by:
void
Why would the add method return false?
when the addition of a new item was not successful
If currentSize is 8, trace int[] values = { 35, 16, 100, 12, 100, 200, 250, 500, 0, 0}; int newElement = 11; if (currentSize < values.length) { currentSize++; values[currentSize - 1] = newElement; } What is the array after the code executes?
{ 35, 16, 100, 12, 100, 200, 250, 500, 11, 0};
If pos is 4 and currentSize is 7, trace this code that removes an item: int[] values = {10, 20, 30, 40, 50, 60, 70}; for (int i = pos + 1; i < currentSize; i++) { values[i - 1] = values[i]; } What is the array after the code executes?
{10, 20, 30, 40, 60, 70, 70}