Prog 2 final 2
Consider the following code snippet in Java 6 or later: String[] data = { "abc", "def", "ghi", "jkl" }; String[] data2 = Arrays.copyOf(data, data.length - 1); What does the last element of data2 contain? "abc" "def" "ghi" "jkl"
"ghi"
Which of the following conditions is true exactly when the integer variable middle is between the values 0 and 10? (0 <= middle) && (middle <= 10) 0 <= middle <= 10 (0 <= middle) || (middle <= 10) (0 <= 10) && (middle <= 10)
(0 <= middle) && (middle <= 10)
Select an appropriate expression to complete the following code segment, which is designed to print a message if the string stored in name is the first element of the players linked list. LinkedList<String> players = new LinkedList<>(); // code to add elements to the linked list if ______________________________________ { System.out.print(name + " is the first player on the list."); } (players.getFirst().equals(name)) (players[0].equals(name)) (players.contains(name)) (players.indexOf(name) == 1)
(players.getFirst().equals(name))
Consider the classes shown below: public class Parent { private int value = 100; public int getValue() { return value; } } public class Child extends Parent { private int value; public Child(int number) { value = number; } public int getValue() { return value; } } What is the output of the following lines of code? Child kid1 = new Child(-14); Child kid2 = new Child(21); System.out.println(kid1.getValue() + " " + kid2.getValue()); -14 21 21 21 21 100 100 100
-14 21
Consider the classes shown below: public class Parent { public int getValue() { return 24; } public void display() { System.out.print(getValue() + " "); } } public class Child extends Parent { public int getValue() { return -7; } } Using the classes above, what is the output of the following lines of code? Child kid = new Child(); Parent adult = new Parent(); kid.display(); adult.display(); 24 24 -7 -7 -7 24 24 -7
-7 24
What is the value of the count variable after the execution of the given code snippet? ArrayList<Integer> num = new ArrayList<Integer> () ; num.add(1) ; num.add(2) ; num.add(1) ; int count = 0 ; for ( int i = 0 ; i < num.size( ) ; i++) { if (num.get (i) % 2 == 0 ) { count++; } } 1 2 0 3
1
What is the output of the following code snippet? int i = 1; while (i < 20) { System.out.print(i + " "); i = i + 2; if (i == 15) { i = 19; } } 1 3 5 7 9 11 13 15 17 19 1 3 5 7 9 11 13 19 1 3 5 7 9 11 13 15 17 1 3 5 7 9 11 13 17 19
1 3 5 7 9 11 13 19
Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many more recursive calls to fib will be made from the original call of fib(7) than from the original call of fib(6) (not counting the original calls)? 2 10 5 1
10
Consider the classes shown below: public class Parent { private int value = 100; public int getValue() { return value; } } public class Child extends Parent { private int value; public Child(int number) { value = number; } } What is the output of the following lines of code? Child kid = new Child(-14); Parent kid2 = new Child(21); System.out.println(kid.getValue() + " " + kid2.getValue()); 100 100 -14 21 21 21 -14 100
100 100
What is the output of the following code snippet? int num = 100; if (num < 100) { if (num < 50) { num = num - 5; } else { num = num - 10; } } else { if (num > 150) { num = num + 5; } else { num = num + 10; } } System.out.println(num); 95 100 105 110
110
What is the output of the following code snippet? int s1 = 20; if (s1 <= 20) { System.out.print("1"); } if (s1 <= 40) { System.out.print("2"); } if (s1 <= 20) { System.out.print("3"); } 1 2 3 123
123
What is the output of the following code snippet? int i = 1; while (i < 10) { System.out.print(i + " "); i = i + 2; if (i == 5) { i = 9; } } 1 3 5 1 3 9 1 3 5 7 9 1 3 5 9
139
Assume you are using a doubly-linked list data structure with many nodes. What is the minimum number of node references that are required to be modified to remove a node from the middle of the list? Consider the neighboring nodes. 3 2 4 1
2
What is the output of the following code? int[][] counts = { { 0, 0, 1 }, { 0, 1, 1, 2 }, { 0, 0, 1, 4, 5 }, { 0, 2 } }; System.out.println(counts[3].length); 2 3 4 5
2
Suppose we are using binary search on an array with approximately 1,000,000 elements. How many visits should we expect to make in the worst case? 16 30 20 1
20
Assume the following variable has been declared and given a value as shown: Random rand = new Random(); int number = rand.nextInt (27) * 2 + 3; What are the smallest and largest values number may be assigned? 3, 57 0, 27 3, 55 0, 26
3, 55
When method makeMenuItem is called, how many objects are being created? public JMenuItem makeMenuItem(final String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(); System.out.println(menuLabel); } } mi.addActionListener(new MyMenuListener()); return mi; } 1 2 3 4
4
What will be printed by the statements below? int[] values = { 4, 5, 6, 7}; for (int i = 1; i < values.length; i++) { values[i] = values[i - 1] + values[i]; } for (int i = 0; i < values.length; i++) { System.out.print (values[i] + " "); } 4 9 11 13 4 9 15 22 9 11 13 7 4 5 6 7
4 9 15 22
What is the output of the following code snippet? final int MIN_SPEED = 45; final int MAX_SPEED = 65; int speed = 55; if (!(speed < MAX_SPEED)) { speed = speed - 10; } if (!(speed > MIN_SPEED)) { speed = speed + 10; } System.out.println(speed); 45 55 65 50
55
Consider the following code snippet: int[][] arr = { { 1, 2, 3, 0 }, { 4, 5, 6, 0 }, { 0, 0, 0, 0 } }; int[][] arr2 = arr; System.out.println(arr2[2][1] + arr2[1][2]); What is the output of the given code snippet on execution? 5 6 7 9
6
Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (n % 10) + newCalc(n / 10); } } What value will be returned when this code is executed with a call to newCalc(15)? 2 6.5 2.5 6
6
How many elements can be stored in an array of dimension 2 by 3? 2 3 5 6
6
What is the output of the following code snippet? public static int check(ArrayList<Integer> listData) { int sum = 0; for (int i = 0; i < listData.size(); i++) { sum = sum + listData.get(i); } return sum; } public static void main(String[] args) { ArrayList<Integer> vdata = new ArrayList<Integer>(); int rsum; for (int cnt = 0; cnt < 3; cnt++) { vdata.add(cnt + 1); } rsum = check(vdata); System.out.println(rsum); } 4 2 3 6
6
What is the output of the following statements? ArrayList<String> cityList = new ArrayList<String>(); cityList.add("London"); cityList.add("New York"); cityList.add("Paris"); cityList.add("Toronto"); cityList.add("Hong Kong"); cityList.add("Singapore"); System.out.print(cityList.size()); System.out.print(" " + cityList.contains("Toronto")); System.out.print(" " + cityList.indexOf("New York")); System.out.println(" " + cityList.isEmpty()); 5 true 1 false 6 true 2 false 5 false 1 false 6 true 1 false
6 true 1 false
What output does this while loop generate? j = 6; while (j > 0) { System.out.print(j + ", "); j--; } No output is generated. 6, 5, 4, 3, 2, 1 6, 5, 4, 3, 2, 1, The output is infinite.
6, 5, 4, 3, 2, 1,
Which of the following statements about a Java interface is NOT true? A Java interface must contain more than one method. A Java interface defines a set of methods that are required. A Java interface specifies behavior that a class will implement. All methods in a Java interface must be public.
A Java interface must contain more than one method.
When the reserved word super is followed by a period and a method name, what does it indicate? A call to a superclass method. A call to a superclass constructor. A call to a subclass method. A call to a subclass constructor.
A call to a superclass method.
Consider the following code snippet, which is meant to override the equals() method of the Object class: public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . . } What is wrong with this code? A class cannot override the equals() method of the Object class. The equals() method must be declared as private. A class cannot change the parameters of a superclass method when overriding it. There is nothing wrong with this code.
A class cannot change the parameters of a superclass method when overriding it.
Which of the following is true regarding subclasses? A subclass that inherits methods from its superclass may not override the methods. A subclass that inherits instance variables from its superclass may not declare additional instance variables. A subclass may inherit methods or instance variables from its superclass but not both. A subclass may inherit methods and instance variables from its superclass, and may also implement its own methods and declare its own instance variables.
A subclass may inherit methods and instance variables from its superclass, and may also implement its own methods and declare its own instance variables.
This is arguably the most important type of testing, as it is conducted by the Quality Assurance Team who will gauge whether the application meets the intended specifications and satisfies the client's requirement. The QA team will have a set of prewritten scenarios and test cases that will be used to test the application. Acceptance Testing Regression Testing Beta Testing Integration Testing
Acceptance Testing
How do you add two buttons to the south area of a frame using the BorderLayout? Add them to a panel, then add the panel to the SOUTH Add one to the SOUTH, then add the second one to the SOUTH Add one to the SOUTH, then add the second one to the CENTER Add one to the CENTER, then add the second one to the SOUTH
Add them to a panel, then add the panel to the SOUTH
This test is the first stage of testing and will be performed amongst the teams (developer and QA teams). The other types of testing when combined together is known as alpha testing. Alpha Testing Beta Testing Performance Testing Unit Testing
Alpha Testing
Which of the following statements about abstract methods is true? An abstract method has a name, parameters, and a return type, but no code in the body of the method. An abstract method has parameters, a return type, and code in its body, but has no defined name. An abstract method has a name, a return type, and code in its body, but has no parameters. An abstract method has only a name and a return type, but no parameters or code in its body.
An abstract method has a name, parameters, and a return type, but no code in the body of the method.
A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What does the condition left >= right refer to? You have reached the middle of the string. It cannot be determined if the string is a palindrome. An empty or one-character string is considered a palindrome. The string is not a palindrome.
An empty or one-character string is considered a palindrome.
If you increase the size of a dataset fivefold, how much longer does it take to sort it with the selection sort algorithm? Approximately 100 times longer Approximately 5 times longer Approximately 20 times longer Approximately 25 times longer
Approximately 25 times longer
Which layout manager constructor call would be best-suited to create a telephone keypad GUI which has 3 rows of 3 keys that are labeled 1,2,3; 4,5,6; and 7,8,9; respectively, as well as a fourth row of three keys labeled *, 0, #? A) new GridLayout (3,4) B) new GridLayout (4, 3) C) new FlowLayout (4,3) D) new BorderLayout (3,4)
B) new GridLayout (4,3)
Which statement is true about backtracking? Backtracking starts with a partial solution and builds it up to get closer to the goal. Backtracking never abandons a partial solution. Backtracking starts from the end of the program and works backward to the beginning. Backtracking explores only one path toward a solution
Backtracking starts with a partial solution and builds it up to get closer to the goal.
Consider the following code snippet: BankAccount account = new BankAccount(500); Which of the following statements correctly clones the account? BankAccount clonedAccount = Object.clone(account); BankAccount clonedAccount = account.super.clone(); BankAccount clonedAccount = account.clone(); BankAccount clonedAccount = (BankAccount) account.clone();
BankAccount clonedAccount = (BankAccount) account.clone();
The code below will not compile successfully unless the argument to the makeMenuItem method is final. Why not? public JMenuItem makeMenuItem(final String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(); System.out.println(menuLabel); } } mi.addActionListener(new MyMenuListener()); return mi; } JMenuItem labels must be final This prevents the menuLabel argument from being modified Because a local variable is being accessed from an inner classes Because the String class is final
Because a local variable is being accessed from an inner classes
This test is performed after alpha testing has been successfully performed. A sample of the intended audience tests the application. Beta testing is also known as pre-release testing. This tests the versions of software are ideally distributed to a wide audience on the Web, partly to give the program a "real-world" test and partly to provide a preview of the next release. Beta Testing Alpha Testing Non-Functional Testing System Testing
Beta Testing
What is the default layout manager of the content pane of a JFrame? FlowLayout GridLayout BoxLayout BorderLayout
BorderLayout
Suppose a JPanel with a BorderLayout manager contains two components: comonent1, which was added to the EAST, and component2, which was added to the WEST. Which parts of the JPanel appear? I North II South III Center IV West V East A) I and II B) I, II, and III C) III, IV, and V D) IV and V
C) III, IV, and V
When using a list iterator, on which condition will the NoSuchElementException be thrown? Calling next when you are past the end of the list. Calling remove after calling add. Calling remove after calling previous. Calling next when the iterator points to the last element.
Calling next when you are past the end of the list.
which of the following generate action events? A) buttons B) menu items C) combo box D) all of the above
D) all of the above
Why does the best recursive method usually run slightly slower than its iterative counterpart? Each recursive method call takes processor time. Multiple recursive cases must be considered. Checking multiple terminating conditions take more processor time. Testing the terminating condition takes longer.
Each recursive method call takes processor time.
Which layout manager places objects left-to-right, and creates a new row only if when the current row cannot accommodate another object? FlowLayout BorderLayout BoxLayout GridLayout
FlowLayout
This is a type of black-box testing that is based on the specifications of the software that is to be tested. The application is tested by providing input and then the results are examined that need to conform to the functionality it was intended for. Functional Testing System Testing Alpha Testing Beta Testing
Functional Testing
What is the outcome of the following code snippet? boolean val1 = true; boolean val2 = false; while (val1) { if (val1) { System.out.println("Hello"); } val1 = val2; } No output will be displayed because of a compilation error. Hello will be displayed only once. Hello will be displayed infinite times. No output will be displayed even after successful compilation of the code snippet.
Hello will be displayed only once.
Which layout manager allows you to add components to it by invoking the container's add method with the component as the only argument to add. I FlowLayout II BorderLayout III GridLayout Only I Only II Only III I and III
I and III
We might choose to use a linked list over an array list when we will not require frequent ____. I random access II inserting new elements III removing of elements III only II only II and III only I only
I only
Which statements are true about the buffer overrun attack launched over the Internet in 1988? I. The buffer overrun exploited a program that was written in C running on the Unix operating system. II. The Java programming language generates a run-time exception when buffer overrun occurs. III. In recent years computer attacks have lessened. I, II only I, III only II, III only I, II, III
I, II only
When does quicksort's worst-case run-time behavior occur? I when the data is randomly initialized in the array II when the data is in ascending order III when the data is in descending order III only I only II only II and III only
II and III only
If a call to the Arrays static method binarySearch returns a value of 7, what can be concluded? I the element is not in the array II the element is at index 7 III the element occurs 7 times in the array II and III only I only II only III only
II only
Which of the sorts in the textbook can be characterized by the fact that the best case will have a running time of θ(n) if the data is already sorted? I quicksort II selection sort III insertion sort III only II only I only I and III only
III only
Consider the following code snippet. Assuming that the user inputs 75 as the age, what is the output? int age = 0; Scanner in = new Scanner(System.in); System.out.print("Please enter your age: "); age = in.nextInt(); if (age < 10) { System.out.print("Child "); } if (age < 30) { System.out.print("Young adult "); } if (age < 70) { System.out.print("Old "); } if (age < 100) { System.out.print("Impressively old "); } Impressively old Child Young adult Old Young adult Old Child Young adult Old Impressively old
Impressively old
Which of the following statements about white space in Java is correct? In Java, white space includes spaces, tab characters, newline characters, and punctuation. In Java, white space includes spaces and tab characters only. In Java, white space includes spaces, tab characters, and newline characters. In Java, white space includes spaces only.
In Java, white space includes spaces, tab characters, and newline characters.
____ recursion can occur when a recursive algorithm does not contain a special case to handle the simplest computations directly. Non-mutual Terminating condition Mutual Infinite
Infinite
When identifying the proper instance variables to use in the design of an inheritance hierarchy, how do you decide where in the hierarchy a variable should be placed? Instance variables should only be declared in the superclass and then accessed using the super keyword. Instance variables should only be declared in subclasses. Instance variables that are common to all classes should be placed at the base of the hierarchy. Instance variables that are relevant to only one class should be placed at the base of the hierarchy.
Instance variables that are common to all classes should be placed at the base of the hierarchy.
This type of testing is defined as the testing of combined parts of an application to determine if they function correctly. It can be done in two ways: Bottom-up testing and Top-down testing. Integration Testing Unit Testing Acceptance Testing Performance Testing
Integration Testing
Consider the permutations method from the textbook, which is intended to return all permutations of the word passed in as a parameter. How does the permutations method simplify its input for the recursive call? public static ArrayList<String> permutations(String word) { ArrayList<String> result = new ArrayList<String>(); if (word.length() == 0) // line #1 { result.add(word); // line #2 return result; // line #3 } else { for (int i = 0; i < word.length(); i++) // line #4 { String shorter = word.substring(0, i) + word(substring(i + 1); // line #5 ArrayList<String> shorterPermutations = permutations(shorter); // line #6 for (String s : shorterPermutations) // line #7 { result.add(word.charAt(i) + s); // line #8 } } return result; // line #9 } } It finds permutations of a shorter word by removing both the first and last character. It finds permutations of a shorter word by removing the last character. It finds permutations of shorter words formed by removing the ith character. It finds permutations of a shorter word by removing the first character. Question 17
It finds permutations of shorter words formed by removing the ith character.
Consider the following code snippet: public class Auto extends Vehicle { . . . public Auto(int numberAxles) { super(numberAxles); } } What does this code do? It invokes the constructor of the Vehicle class from within the constructor of the Auto class. It invokes the constructor of the Auto class from within the constructor of the Vehicle class. It invokes a private method of the Vehicle class from within a method of the Auto class. This code will not compile.
It invokes the constructor of the Vehicle class from within the constructor of the Auto class.
In big-Oh notation, suppose an algorithm requires an order of n3 element visits. How does doubling the number of elements affect the number of visits? It number of visits goes up by a factor of eight. It triples the number of visits. It quadruples the number of visits. It doubles the number of visits.
It number of visits goes up by a factor of eight.
A portion of your program includes the method shown in the code snippet below to examine the elements of an array arr: private int findElement(int[] arr, int newVal) { int pos = Arrays.binarySearch(arr, newVal); return pos; } What can you conclude about the running time of this section of code? Its running time will be O(log (n)). Its running time will be O(n). Its running time will be O(n log (n)). Its running time will be O(n2).
Its running time will be O(log (n)).
A portion of your program includes the loop shown in the code snippet below to examine the elements of an array arr: int count = 0; int targetVal = 70; for (int i = 0; i < arr.length; i++) { if (arr[i] >= targetVal) { count++; } } What can you conclude about the running time of this section of code? Its running time will be O(n log (n)). Its running time will be O(n2). Its running time will be O(n). Its running time will be O(log (n)).
Its running time will be O(n).
Which of the following classes has a Boolean state that can be set or unset through the GUI? JCheckBox JButton ButtonGroup JMenuItem
JCheckBox
Which GUI element allows text entry from the program user? ButtonGroup JComboBox JSlider JPanel
JComboBox
Which of the following classes have a user-editable area? JCheckBox JComboBox ButtonGroup JRadioButton
JComboBox
Which of the following statements about character encodings is NOT true? It is recommended to specify the UTF-8 encoding when processing files with special symbols or characters in multiple languages. Java assumes the UTF-8 encoding. A character is encoded as a sequence of bytes, each having a value between 0 and 255. Java supports the reading and writing of files in the UTF-8 encoding.
Java assumes the UTF-8 encoding.
Consider the classes shown below: public class Parent { public void doSomething(){/* Implementation not shown */} } public class Child extends Parent { public void doAnotherThing(){/* Implementation not shown */} } Which lines in the following code will compile without error? Parent kid = new Child(); kid.doSomething(); // line 1 kid.doAnotherThing(); // line 2 Line 1 only Line 2 only Lines 1 and 2 Neither line will compile without error
Line 1 only
All rodents are mammals and all canines are mammals. No canines are rodents and no rodents are canines. What hierarchy best captures this information? Mammal is a superclass of Rodent and Mammal Rodent is a superclass of Mammal and Canine is a superclass of Mammal Mammal is a superclass of Rodent and Rodent is a superclass of Canine Mammal is a superclass of Canine and Canine is a superclass of Rodent
Mammal is a superclass of Rodent and Mammal
Consider the classes shown below: public class Parent { public void doSomething() // method 1 { /* Implementation not shown */ } } public class Child extends Parent { public void doSomething(int n) // method 2 { /* Implementation not shown */ } public void doSomething() // method 3 { /* Implementation not shown */ } } If the variable kid is defined below, which version of the doSomething method can be called on the variable kid? Parent kid = new Child(); Method 1 only Methods 2 and 3 only Methods 1 and 2 only Methods 1, 2, and 3
Method 1 only
To process mouse events, you need to define a class that implements the ____ interface. EventListener TimerListener ActionListener MouseListener
MouseListener
What is the best way to improve the following code fragment? if ((counter % 10) == 0) { System.out.println("Counter is divisible by ten: " + counter); counter++; } else { System.out.println("Counter is not divisible by ten: " + counter); counter++; } Move the duplicated code outside of the if statement Shorten variable names Move the brackets to save several lines of code Add semicolons after the if condition and the else reserved word
Move the duplicated code outside of the if statement
This is testing an application from its non-functional attributes. It involves testing a software from the requirements which are nonfunctional in nature but important such as performance, security, user interface, etc. Non-Functional Testing Performance Testing Integration Testing System Testing
Non-Functional Testing
Select an expression to complete the program segment below, which displays an error message and terminates normally if the String variable accountNumber does not contain an integer value. try { int number = Integer.parseInt(accountNumber); } catch ( ________________________ ) { System.out.println("Account number is not an integer value"); } NumberFormatException exception InputMismatchException exception ArithmeticException exception IOException exception
NumberFormatException exception
Which layout manager uses a grid, but allows selected grid locations to span multiple rows or columns? I GridBagLayout II BorderLayout III GridLayout Only I Only II Only III I and III
Only I
Which layout manager allows you to add components in different orders, with the result being the same GUI appearance? I FlowLayout II BorderLayout III GridLayout Only I Only II I and III II and III
Only II
Consider the following code snippet: Scanner in = new Scanner(. . .); in.useDelimiter("[A-Za-z]+"); What characters will be read in using this code? Only alphabetic characters will be read in. Only numeric characters will be read in. Only non-numeric characters will be read in. Only non-alphabetic characters will be read in.
Only non-alphabetic characters will be read in.
This type of testing is mostly used to identify any bottlenecks or performance issues rather than finding bugs in a software. There are different causes that contribute in lowering the performance of a software including: Network delay, Client-side processing, Database transaction processing, Load balancing between servers and Data rendering. Performance Testing Alpha Testing Beta Testing Functional Testing
Performance Testing
The PrintWriter class is an enhancement of the ____ class. File ReadStream Scanner PrintStream
PrintStream
Consider the recursive method myPrint shown in this code snippet: public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What does this method do? Prints a positive int value forward, digit by digit. Divides the int by 10 and prints out the result. Divides the int by 10 and prints out its last digit. Prints a positive int value backward, digit by digit.
Prints a positive int value forward, digit by digit.
What operation is least efficient in a LinkedList? Linear traversal step. Random access of an element. Adding an element in a position that has already been located. Removing an element when the element's position has already been located.
Random access of an element.
Whenever a change in a software application is made, it is quite possible that other areas within the application have been affected by this change. Regression testing is performed to verify that a fixed bug hasn't resulted in another functionality or business rule violation. Regression Testing Unit Testing Performance Testing Alpha Testing
Regression Testing
What does the getClass method do? Returns an object that describes a class and its properties. Returns a string that contains the instance variables of a class. Returns an object that describes all subclasses of a given object. Returns an object that describes all superclasses of a given object.
Returns an object that describes a class and its properties.
Complete the following code, which is intended to print out all key/value pairs in a map named myMap that contains String data for student IDs and names: Map<String, String> myMap = new HashMap<>(); . . . _______________________________ for (String aKey : mapKeySet) { String name = myMap.get(aKey); System.out.println("ID: " + aKey + "->" + name); } Map<String, String> mapKeySet = myMap.keySet(); Set<String, String> mapKeySet = myMap.keySet(); Set<String> mapKeySet = myMap.keySet(); Set<String> mapKeySet = myMap.getKeySet();
Set<String> mapKeySet = myMap.keySet();
How do you specify what the program should do when the user clicks a button? Specify the actions to take in a class that implements the ButtonListener interface. Specify the actions to take in a class that implements the EventListener interface. Specify the actions to take in a class that implements the ButtonEvent interface. Specify the actions to take in a class that implements the ActionListener interface.
Specify the actions to take in a class that implements the ActionListener interface.
If recursion does not have a special terminating case, what error will occur? Illegal argument Out of memory Stack overflow Index out of range
Stack overflow
Which of the following correctly declares a stack that will hold String elements? Stack s = new Stack<>(); Stack<String> s = new Stack<>(); String s = new Stack(); String s = new Stack<>();
Stack<String> s = new Stack<>();
Which of the following statements about exception handling is correct? Statements that may cause an exception should be placed within a catch block. Statements that may cause an exception should be placed within a try block. The main method of a Java program will handle any error encountered in the program. Statements that may cause an exception should be placed within a throws block.
Statements that may cause an exception should be placed within a try block.
What is a class called that represents the most general entity in an inheritance hierarchy? Default class. Superclass. Subclass. Inheritance class.
Superclass.
This type of testing tests the system as a whole. Once all the components are integrated, the application as a whole is tested rigorously to see that it meets the specified Quality Standards. This type of testing is performed by a specialized testing team. System Testing Integration Testing Unit Testing Non-functional Testing
System Testing
Select an appropriate expression to complete the method below, which is designed to print the element at the bottom of a Stackcollection. The contents of the original stack are restored before the method terminates. It is safe to assume that the original stack contains at least one element. public static void printBottom(Stack<String> theStack) { Stack<String> anotherStack = new Stack<>(); while (!theStack.empty()) { anotherStack.push(theStack.pop()); } ____________________________ while (!anotherStack.empty()) { theStack.push(anotherStack.pop()); } } System.out.println(theStack.pop()); System.out.println(anotherStack.pop()); System.out.println(anotherStack.peek()); System.out.println(theStack.peek());
System.out.println(anotherStack.peek());
What does the MouseAdapter class provide? A class can implement the MouseAdapter class to handle mouse events. The MouseAdapter class allows your program to accept input from multiple mice. The MouseAdapter class implements all of the methods of the MouseListener interface as do-nothing methods, eliminating the need to provide an implementation for all 5 methods of the MouseListener interface. The MouseAdapter class implements all of the methods of the ActionListener interface as do-nothing methods, eliminating the need to implement the ActionListener interface.
The MouseAdapter class implements all of the methods of the MouseListener interface as do-nothing methods, eliminating the need to provide an implementation for all 5 methods of the MouseListener interface.
Consider the following code snippet: class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } } What is wrong with this code? There is nothing wrong with this code. The class has implemented the wrong interface. repaint() method was not called. The mouseClicked method cannot access the x and y coordinates of the mouse.
The class has implemented the wrong interface.
What can be determined about obj from the code below? JMenuItem menuItem = new JMenuItem("Exit"); menuItem.addActionListener(obj); The class of obj implements ActionListener menuItem implements ActionListener obj is of type MenuListener obj is an object of an inner class
The class of obj implements ActionListener
Consider the following code snippet, assuming that filename represents the name of the output file and writeData outputs the data to that file: try (PrintWriter outputFile = new PrintWriter(filename)) { writeData(outputFile); } Which of the following statements about this code is correct? The close method of the outputFile object will be automatically invoked when the try block ends, but only if no exception occurred. The program will terminate with an unhandled exception if the PrintWriter constructor fails. The close method of the outputFile object will be automatically invoked when the try block ends, whether or not an exception has occurred. The close method of the outputFile object will be automatically invoked when the try block ends, but only if an exception occurs.
The close method of the outputFile object will be automatically invoked when the try block ends, whether or not an exception has occurred.
Using the given definition of the Measurable interface: public interface Measurable { double getMeasure(); } Consider the following code snippet, assuming that BankAccount has a getBalance method and implements the Measurable interface by providing an implementation for the getMeasure method: Measurable m = new Measurable(); System.out.println(m.getMeasure()); Which of the following statements is true? The code executes, displaying the measure of the Measurable object. The code does not compile because interface types cannot be instantiated. The code compiles but generates an exception at run time because getMeasure does not return a String. The code compiles but generates an exception at run time because m does not reference a BankAccount object.
The code does not compile because interface types cannot be instantiated.
Consider the following code snippet, where the array lists contain elements that are stored in ascending order: ArrayList<Integer> list1 = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); . . . int count = 0; for (int i = 0; i < list1.size() && i < list2.size(); i++) { if (list1.get(i) == list2.get(i)) { count++; } } Which one of the following descriptions is correct for the given code snippet? The code snippet finds the highest value out of the two array lists. The code snippet finds the lowest value out of the two array lists. The code snippet compares the values of two array lists and stores the count of total matches found. The code snippet adds the values of the two array lists.
The code snippet compares the values of two array lists and stores the count of total matches found.
Which of the following statements about checked and unchecked exceptions is true? Checked exceptions are handled by the Java runtime. The compiler ensures that the program is handling unchecked exceptions. The compiler ensures that the program is handling checked exceptions. All exceptions that are descendants of RunTimeException are checked exceptions.
The compiler ensures that the program is handling checked exceptions.
Which nodes need to be updated when we insert a new node to become the fourth node from the beginning of a doubly-linked list? The current third and fourth nodes. The current fourth and fifth nodes. The current first node. The current third node
The current third and fourth nodes.
Which of the following statements is true about the if statement? The if statement can have only one condition that evaluates to an integer value. The if block is optional. The else block is optional. The if and else blocks should always be included within curly braces.
The else block is optional.
Consider the following code snippet, assuming that filename represents the name of the output file and writeData outputs the data to that file: try (PrintWriter outputFile = new PrintWriter(filename)) { writeData(outputFile); } catch (IOException exception) { . . . } Which of the following statements about this code is correct? The file will be closed regardless of when an exception occurs. The file will be closed only if the writeData() statement throws an exception. The file will be closed only if the PrintWriter constructor throws an exception. It is not possible to determine whether the file will be closed if an exception occurs.
The file will be closed regardless of when an exception occurs.
Consider the following code snippet: class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println(event); } } Timer t = new Timer(interval, listener); t.start(); What is wrong with this code? The Timer object must be declared as final. There is nothing wrong with the code. The listener has not been attached to the Timer object. The Timer object should be declared before the MyListener class.
The listener has not been attached to the Timer object.
Consider the following code snippet: public static void main(String[] args) throws FileNotFoundException Which of the following statements about this code is correct? The main method is designed to catch and handle all types of exceptions. The main method will not terminate if any exception occurs. The main method is designed to catch and handle the FileNotFoundException. The main method terminates if the FileNotFoundException occurs.
The main method terminates if the FileNotFoundException occurs.
What will be the output of the following code snippet? int i; int j; for (i = 0; i <7; i++) { for (j = 7; j > i; j--) { System.out.print("*"); } System.out.println(""); } The output will be a rectangle with six rows and seven columns of asterisks. The numberof rows increments by one on completion of one iteration of the inner loop. The output will be a right triangle with six rows and seven columns of asterisks. Thenumber of columns increments by one on completion of one iteration of the inner loop. The output will be a rectangle with seven rows and six columns of asterisks. The numberof rows increments by one on completion of one iteration of the inner loop. The output will be a right triangle with six rows and seven columns of asterisks. The number of columns decrements by one on completion of one iteration of the inner loop.
The output will be a right triangle with six rows and seven columns of asterisks. The number of columns decrements by one on completion of one iteration of the inner loop.
Consider the sort method shown below for selection sort: public static void sort(int[] a) { for (int i = 0; i < a.length - 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } Suppose we modify the loop condition to read i < a.length. What would be the result? The sort would work exactly the same as before the code modification. The sort would work, but run one more iteration. The sort would work but with one less iteration. An exception would occur.
The sort would work, but run one more iteration.
What must a subclass do to modify a private superclass instance variable? The subclass must simply use the name of the superclass instance variable. The subclass must declare its own instance variable with the same name as the superclass instance variable. The subclass must use a public method of the superclass (if it exists) to update the superclass's private instance variable. The subclass must have its own public method to update the superclass's private instance variable.
The subclass must use a public method of the superclass (if it exists) to update the superclass's private instance variable.
Consider the following class hierarchy: public final class Shape { private String mycolor; public Shape(String mycolor) { this.type = mycolor; } public String getColor() { return mycolor; } } public class Triangle extends Shape { public Triangle(String mycolor) { super(mycolor); } } } What is wrong with this class hierarchy definition? Nothing is wrong with the code. There should be more subclasses of the Shape class than just Triangle. There cannot be any subclasses of the Shape class. It is not possible to use super in the Triangle constructor.
There cannot be any subclasses of the Shape class.
Consider the following code snippet. Scanner inputFile = new Scanner("hoursWorked.txt"); Which of the following statements is correct? This code will open an existing file named "hoursWorked.txt" for reading. This code will create a new file named "hoursWorked.txt". This code will treat the string "hoursWorked.txt" as an input value. This code will open a file named "hoursWorked.txt" for writing.
This code will treat the string "hoursWorked.txt" as an input value.
Which of the following statements about exception handling is recommended? Throw an exception as soon as a problem is detected, but only catch exceptions when the problem can be handled. All exceptions should be handled at the top of the chain of methods. All exceptions should be handled where they are first detected. Throw an exception only when the problem can be handled.
Throw an exception as soon as a problem is detected, but only catch exceptions when the problem can be handled.
This type of testing is performed by developers before the setup is handed over to the testing team to formally execute the test cases. It is performed by the respective developers on the individual units of source code assigned areas. Unit Testing Functional Testing Beta Testing Performance Testing
Unit Testing
You wish to implement a callback method for an object created from a library class that you cannot change. What is the preferred way to accomplish this? Extend the library class. Use an inner class in the interface. Create a new class that mimics the library class. Use a helper class that implements the callback method.
Use a helper class that implements the callback method.
Which of the following statements about inheritance is correct? You can always use a superclass object in place of a subclass object. You can always use a subclass object in place of a superclass object. A superclass inherits data and behavior from a subclass. A superclass inherits only behavior from a subclass.
You can always use a subclass object in place of a superclass object.
You have opened a command prompt window and you have entered the following: java myProg Bob Smith Which of the following statements is correct? You have supplied two argument values, and these values can be accessed in the main method using the args parameter. You have supplied one argument value, and this value can be accessed in the main method using the arg1 parameter. You have supplied one argument value, and this value can be accessed in the main method using the args parameter. You have supplied two argument values, and these values can be accessed in the main method using the arg1 and arg2 parameters.
You have supplied two argument values, and these values can be accessed in the main method using the args parameter.
Which of the following statements about events and graphical user interface programs is true? Your program must instruct the Java window manager to send it notifications about specific types of events to which the program wishes to respond. The Java window manager will automatically send your program notifications about all events that have occurred. Your program must override the default methods to handle events. Your program must respond to notifications of all types of events that are sent to it by the Java window manager.
Your program must instruct the Java window manager to send it notifications about specific types of events to which the program wishes to respond.
Consider the following code snippet: PriorityQueue<String> stringQueue = new PriorityQueue<>(); stringQueue.add("ab"); stringQueue.add("abc"); stringQueue.add("a"); while (stringQueue.size() > 0) { System.out.print(stringQueue.remove() + ","); } What output will be produced when this code is executed? ab,abc,a, a,ab,abc, abc,ab,a, a,abc,ab,
a,ab,abc,
A method that has no implementation is called a/an ____ method. abstract overloaded interface implementation
abstract
Consider the scope of the three objects menuLabel, mi, and the anonymous object new MyMenuListener() within the JmenuItem class. How do thier lifetimes compare? public JMenuItem makeMenuItem(final String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(); System.out.println(menuLabel); } } mi.addActionListener(new MyMenuListener()); return mi; } all have the same lifetimes menuLabel and new MyMenuListener() are the same and both longer than mi mi and new MyMenuListener() are the same and both longer than menuLabel from shortest to longest:menuLabel, new MyMenuListener(), mi
all have the same lifetimes
Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What parameter values for n would cause an infinite recursion problem in the following method? all n with n < 0 n == 0 all n with n >= 0 n == 1
all n with n < 0
Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: public static int calcPower(int baseNum, int exponent) { int answer = 0; if (exponent == 0) { _____________________ } else { answer = baseNum * calcPower (baseNum, exponent - 1); } return answer; } answer = 0; answer = 1; answer = calcPower(1); answer = -1;
answer = 1;
Assume that bands is an ArrayList of String objects, which contains a number of elements in ascending order. Select a statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string "Beatles". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains sorted. int index = Collections.binarySearch(bands, "Beatles"); if (index < 0) { __________________________ } bands.add(-1 * index, "Beatles"); bands.add(-1 - index, "Beatles"); bands.add(-1 * index + 1, "Beatles"); bands.add(index + 1, "Beatles");
bands.add(-1 - index, "Beatles");
A search technique where, in each step, you split the size of the search in half is called a____ search. random merging linear binary
binary
You can add a(n) _________ to a panel to make it visible. component JFrame border another panel
border
Consider the following code snippet. Assuming that the user enters first 20 and then 12 as the two input values, what is the output of the code snippet? int num1 = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num1 = in.nextInt(); System.out.print("Enter a number: "); num2 = in.nextInt(); if (num1 < num2) { num3 = num1; } else { num3 = num2; } if (num1 < num2 + 10) { num4 = num1; } else if (num1 < num2 + 20) { num5 = num1; } System.out.println("num1 = " + num1 + " num2 = " + num2 + " num3 = " + num3 + " num4 = " + num4 + " num5 = " + num5); a.)num1 = 20 num2 = 12 num3 = 20 num4 = 20 num5 = 0 b.)num1 = 20 num2 = 12 num3 = 12 num4 = 0 num5 = 20 c.)num1 = 20 num2 = 12 num3 = 12 num4 = 20 num5 = 0 d.)num1 = 20 num2 = 12 num3 = 20 num4 = 0 num5 = 20
c.)num1 = 20 num2 = 12 num3 = 12 num4 = 20 num5 = 0
How many times does the following loop execute? double d; Random generator = new Random(); double x = generator.nextDouble() * 100; do { d = Math.sqrt(x) * Math.sqrt(x) - x; System.out.println(d); x = generator.nextDouble() * 10001; } while (d != 0); exactly once exactly twice can't be determined always infinite loop
can't be determined
Suppose you wish to sort an array list of objects, but the object class does not implement the Comparable interface. Because you are not allowed to modify this class, you decide to provide a comparator object that implements the Comparator interface. Which method must you implement from this interface to achieve your objective? sort compareObject compare compareTo
compare
The flow chart shows the order in which steps should be executed, and the diamond-shaped boxes indicate input algorithms tasks conditional tests
conditional tests
Consider the following 2-dimensional array. Which expression gives the number of elements in the third row? int[][] counts = { { 0, 0, 1 }, { 0, 1, 1, 2 }, { 0, 0, 1, 4, 5 }, { 0, 2 } }; counts[2].size() counts.length[2] counts.length counts[2].length
counts[2].length
The integer array numbers will be filled with values from the Scanner object in. If there are more input values than there are spaces in the array, only enough values to fill the array should be read. The integer variable currentSize should be set to the number of values read. Partial code to do this is given below: int[] numbers = new int[100]; Scanner in = new Scanner (System.in); int currentSize = 0; while (/* Put condition here */) { int value = in.nextInt(); numbers[currentSize] = value; currentSize++; } What condition will complete this code? currentSize < numbers.length && in.hasNextInt() currentSize < numbers.length || in.hasNextInt() currentSize <= numbers.length && in.hasNextInt() currentSize <= numbers.length || in.hasNextInt()
currentSize < numbers.length && in.hasNextInt()
Consider the following code snippet: String[] data = { "abc", "def", "ghi", "jkl" }; String [] data2; In Java 6 and later, which statement copies the data array to the data2 array? data2 = Arrays.copyOf(data, data2.length); data2 = Arrays.copyOf(data, data.length); data2 = Arrays.copyOf(data, data.size()); data2 = Arrays.copyOf(data);
data2 = Arrays.copyOf(data, data.length);
Which method is NOT part of the ListIterator interface? next delete add previous
delete
Java7 introduced enhanced syntax for declaring array lists, which is termed angle brackets method lists diamond syntax symmetric slants
diamond syntax
A store provides 10 percent discount on all items with a price of at least $100. No discount is otherwise applicable. Which of the following DOES NOT correctly compute the discount? double discount = 0; if (price >= 100) { discount = 0.10 * price; } double discount = 0.10 * price;if (price <= 100) { discount = 0;} double discount; if (price < 100){ discount = 0;}else { discount = 0.10 * price;} double discount = 10; if (price >= 100) { discount = 0.1 * price; } else { discount = 0; }
double discount = 0.10 * price;if (price <= 100) { discount = 0;}
Which code snippet finds the largest value in an array that is only partially full? double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } } double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] < largest) { largest = values[i]; } } double largest = values[0]; for (int i = 1; i < currSize; i++) { if (values[i] > largest) { largest = values[i]; } } double largest = values[0]; for (int i = 1; i < currSize; i++) { if (values[i] < largest) { largest = values[i]; } }
double largest = values[0]; for (int i = 1; i < currSize; i++) { if (values[i] > largest) { largest = values[i]; } }
When an event occurs, the event source notifies all ____. event listeners components panels interfaces
event listeners
Which keyword is used to create a subclass? inherits implements interface extends
extends
In general, the expression ____ means that f grows no faster than g. f(n) = log g f(n) = log g2 g(n) = O(f(n)) f(n) = O(g(n))
f(n) = O(g(n))
A binary search is generally ____ a linear search. faster than less efficient than slower than equal to
faster than
What is the purpose of the following loop? int upperCaseLetters = 0; int position; String str = "abcdEfghI"; boolean found = false; for (position = 0; position < str.length() && !found; position++) { char ch = str.charAt(position); if (Character.isUpperCase(ch)) { found = true; } } finds the position of the first digit (0 through 9) in a string, starting from the left finds the position of the first digit (0 through 9) in a string, starting from the right finds the position of the first uppercase character in a string, starting from the left finds the position of the first uppercase character in a string, starting from the right
finds the position of the first uppercase character in a string, starting from the left
Consider the following code snippet: JFrame frame = new JFrame(); JPanel panel = new JPanel(); Which statement would add the panel to the frame? frame.add(JPanel panel); frame.addComponent(JPanel panel); frame.add(panel); frame.addComponent(panel);
frame.add(panel);
Which of the following methods returns the object that was selected in the JComboBox? getSelected getItem getChoice getSelectedItem
getSelectedItem
To create a _____ layout, you supply the number of rows and columns in the constructor, then add the components, row by row, left to right. border grid grid bag boxed
grid
Which of the following completes the selection sort method minimumPosition()? private static int minimumPosition(int[] a, int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) { ________________ } return minPos; } if (a[i] > a[minPos]) { minPos = i; } if (a[i] < a[j]) { minPos = i; } if (a[i] < a[minPos]) { minPos = i; } if (a[i] < a[minPos]) { i = minPos; }
if (a[i] < a[minPos]) { minPos = i; }
Consider the code for the recursive method riddle shown in this code snippet: public static int riddle(int n) { if (n == 0) { return 0; { else { return (n + riddle(n - 1)); } } To avoid infinite recursion, which of the following lines of code should replace the current terminating case? if (n <= 0) if (n == -1) if (n >= 0) The terminating case as shown will avoid infinite recursion.
if (n <= 0)
Insert the missing code in the following code fragment. This fragment is intended to read all words from a text file named dataIn.txt. File inputFile = new File("dataIn.txt"); Scanner in = new Scanner(inputFile); while (____________) { String input = in.next(); System.out.println(input); } in.getNext() in.nextWord() in.hasNext() in.peek()
in.hasNext()
Insert the missing code in the following code fragment. This fragment is intended to read characters from a text file. Scanner in = new Scanner(. . .); in.useDelimiter(""); while (in.hasNext()) { char ch = ____________; System.out.println(ch); } in.getNext() in.next().charAt(0) in.next() in.nextChar()
in.next().charAt(0)
Event listeners are often installed as ____ classes so that they can have access to the surrounding fields, methods, and final variables. interface helper inner abstract
inner
Consider the following code snippet: public static void sort(int[] a) { for (int i = 1; i < a.length; i++) { int next = a[i]; int j = i; while (j > 0 && a[j - 1] > next) { a[j] = a[j - 1]; j--; } a[j] = next; } } What sort algorithm is used in this code? quicksort insertion sort merge sort selection sort
insertion sort
Which of the following loops will print the odd numbers between 0 and 20? int num = 1;while (num < 20){ System.out.print(num + " "); num += 2;} int num = 1; while (num < 20){ System.out.print(num + " "); num ++; } int num = 0; while (num < 20) { System.out.print(num + " "); num += 2; } int num = 1; while (num < 20) { num += 2; System.out.print(num + " "); }
int num = 1;while (num < 20){ System.out.print(num + " "); num += 2;}
Which code snippet calculates the sum of all the even elements in an array values? int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] % 2) == 0) { sum += values[i]; } } int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] % 2) == 0) { sum++; } } int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] / 2) == 0) { sum += values[i]; } } int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] / 2) == 0) { sum++; } }
int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] % 2) == 0) { sum += values[i]; } }
Identify the correct statement for defining an integer array named numarray of ten elements. int[] numarray = new int[9]; int[] numarray = new int[10]; int[10] numarray; int numarray[10];
int[] numarray = new int[10];
In UML, a dotted arrow with a triangular tip denotes ____________________. interface implementation dependency inheritance aggregation
interface implementation
The ____ method of the Character class will indicate if a character contains white space. isValid() getChar() hasNext() isWhiteSpace()
isWhiteSpace()
What is the best first step in picking the layout managers for a set of nested panels? use a single panel with a GridBagLayout manager construct a set of JPanel objects make a sketch of the layout use multiple panels with FlowLayout managers
make a sketch of the layout
Which sort algorithm starts by cutting the array in half and then recursively sorts each half? insertion sort quicksort merge sort selection sort
merge sort
Assume that you have declared a map named myMap to hold String values with Integer keys. Which of the following statements will correctly retrieve the value associated with a key from myMap? myMap.peek(3); myMap.get("apple"); myMap.peek("apple"); myMap.get(3);
myMap.get(3);
Assume that you have declared a stack named myStack to hold String elements. Which of the following statements will correctly add an element to myStack? myStack.addItem("apple"); myStack.put("apple"); myStack.insert("apple"); myStack.push("apple");
myStack.push("apple");
The number of element visits for merge sort totals n + 5n log2 n. Which of the following is the appropriate big-Oh notation for merge sort? n log2 n n+ log2 n n+ 5n 5n log2 n
n log2 n
Consider an array with n elements. If we visit each element n times, how many total visits will there be? n^n n 2^n n^2
n^2
A recursive method without a special terminating case would _________ be more efficient. never terminate. end immediately. not be recursive.
never terminate.
Insert the missing code in the following code fragment. This fragment is intended to read an input file named dataIn.txt and write to an output file named dataOut.txt. public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = _________________; Scanner in = new Scanner(inputFile); . . . } new File(inputFile) new File(System.in) new File(outputFileName) new File(inputFileName)
new File(inputFileName)
Insert the missing code in the following code fragment. This fragment is intended to write an output file named dataOut.txt that resides in a folder named reports on the C: drive of a Windows system. public static void main(String[] args) throws IOException { PrintWriter outputFile = _______; . . . } new PrintWriter("c:\\reports\\dataOut.txt") new PrintWriter("c:/reports/dataOut.txt") new PrintWriter("c://reports//dataOut.txt") new PrintWriter("c:\reports\dataOut.txt")
new PrintWriter("c:\\reports\\dataOut.txt")
Based on the statement below, which of the following adds a title to the border? JPanel panel = new JPanel(); panel.setBorder(new TitledBorder()); panel.setBorder(new TitledBorder(new EtchedBorder(), "Size")); panel.setBorder(new TitledBorder(new EtchedBorder())); panel.setTitle("Size");
panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));
Consider the method below, which displays the characters from a String in reverse order. Each character appears on a separate line. Select the statement that should be used to complete the method so that it performs a recursive method call correctly. public static void printReverse(String word) { if (word.length() > 0) { ___________________________ System.out.println(word.charAt(0)); } } printReverse(word.length() - 1); printReverse(word.substring(1)); printReverse(word); printReverse(new String(word.charAt(1)));
printReverse(word.substring(1));
Using the following definitions of the Measurable and Named interfaces. public interface Measurable { double getMeasure(); } public interface Named { double getName(); } Assume BankAccount provides the code for the getMeasure() and getName() methods. Which of the following could correctly represent the class header for BankAccount? public class BankAccount extends Measurable implements Named public class BankAccount implements Measurable, Named public interface BankAccount implements Measurable, Named public class BankAccount extends Measurable, Named
public class BankAccount implements Measurable, Named
You are creating a Motorcycle class which is supposed to be a subclass of the Vehicle class. Which of the following class declaration statements will accomplish this? public class Motorcycle extends Vehicle public class Motorcycle implements Vehicle public class Motorcycle interfaces Vehicle public class Motorcycle inherits Vehicle
public class Motorcycle extends Vehicle
Consider the following class: public class ClickListener implements ActionListener { __________________________________________ { System.out.println("button event ..."); } } Which of the following method headers should be used to complete the ClickListener class? public void actionPerformed(ActionEvent event) public void actionPerformed(ClickListener event) public void actionPerformed() public void actionPerformed(ActionListener event)
public void actionPerformed(ActionEvent event)
A collection that allows items to be added only at one end and removed only at the other end is called a ____. set stack queue list
queue
Print jobs submitted to a printer would probably be stored in which type of data structure? linked list queue stack hash table
queue
You need to write a program to manage a waiting list of patrons at a restaurant. Which data structure would be most appropriate to model this situation? queue map stack linked list
queue
Consider the code snippet below: public class RectangleComponent extends JComponent { private Rectangle box; private static final int BOX_X = 100; private static final int BOX_Y = 100; private static final int BOX_WIDTH = 20; private static final int BOX_HEIGHT = 30; public RectangleComponent() { // The rectangle that the paint method draws box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.draw(box); } public void moveTo(int x, int y) { box.setLocation(x, y); repaint(); } } Which statement causes the rectangle to appear at an updated location? g2.draw(box); private Rectangle box; box.setLocation(x, y); repaint();
repaint();
Complete the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n: public static int printSum(int n) { if (n == 0) { return 0; } else { ______________________________ } } return (n + printSum(n - 1)); return (n - printSum(n - 1)); return (n + printSum(n + 1)); return (printSum(n - 1));
return (n + printSum(n - 1));
Consider the method below, which implements the exponentiation operation recursively. Select the statement that should be used to complete the method so that it handles the special case correctly. public static double power(int base, int exponent) { if (exponent == 0) { _______________ } else { return base * power(base, exponent - 1); } } return 0; return 1 * power(base, exponent - 1); return base; return 1;
return 1;
Consider the following class: public class Stock implements Comparable { private String name; private double price; // other methods go here public int compareTo(Object otherObject) { Stock otherStock = (Stock) otherObject; __________________________________; } } Which is the best statement to use to complete the compareTo() method? return (otherStock.price - price) return Integer.compare(price, otherStock.price) return Double.compare(otherStock.price, price) return Double.compare(price, otherStock.price)
return Double.compare(price, otherStock.price)
Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array of double values from index to the end of the array: public static double minVal(double[] elements, int index) { if (index == elements.length - 1) { __________________ } double val = minVal(elements, index + 1); if (elements[index] < val) { return elements[index]; } else { return val; } } return elements[index]; return 0; return 1; return elements[0];
return elements[index];
Complete the code for the recursive method shown below, which is intended to compute the sum of the first n positive integers: public int s(int n) { if (n == 1) { return 1; } else { _________________ } } return n + s(n - 1); return s(n) + n - 1; return n + (n - 1); return n + s(n + 1);
return n + s(n - 1);
Consider the square method shown below that takes a non-negative int argument. Complete the code for the square method so that it correctly calls the squareHelper method to produce the square of n. public int square(int n) { ____________________; } public int squareHelper(int c, int n) { if (c == 1) { return n; } else { return n + squareHelper(c - 1, n); } } return squareHelper(n - 1, n) return squareHelper(n, n - 1) return square(n) return squareHelper(n, n)
return squareHelper(n, n)
Which method can a program use to set the selected choice in a JComboBox? select setChoice setSelectedItem The selection can only be set through the GUI by the user.
select
Another name for linear search is ____ search. random sequential sorted binary
sequential
An Undo feature in a word processor program that allows you to reverse a previously completed command is probably implemented using which structure type? stack queue hash table linked list
stack
You need a data structure in your program for evaluating algebraic expressions. Which data structure would be most appropriate to model this situation? list array queue stack
stack
You need a data structure in your program for finding a path out of a maze using backtracking. Which data structure would be most appropriate to model this situation? array queue list stack
stack
Which of the following conditions can be added to the code below so it will loop until the value of sum is greater than 100? Scanner in = new Scanner (System.in); int sum = 0; do { sum += in.nextInt(); } while (/* put condition here */); sum != 0 sum <= 100 sum > 100 sum == 100
sum <= 100
When using a combo box, the _______ displays the name of the current selection. text field text area menu item submenu item
text field
When an array reading and storing input runs out of space the program could be recompiled with a bigger size for the array. the array could be "grown" using the growArray method. it automatically resizes to accommodate new elements. the array could be "grown" using the new command and the copyOf method.
the array could be "grown" using the new command and the copyOf method.
Insert the missing code in the following code fragment. This code is intended to open a file and handle the situation where the file cannot be found. public void String readFile() _________________ { File inputFile = new File(. . .); try (Scanner in = new Scanner(inputFile)) { while (in.hasNext()) { . . . } } } throws FileNotFound throws IllegalArgumentException throws IOException exception throws IOException
throws IOException
What can a generic class be parameterized for? methods iterators type properties
type
The ______ method of the Scanner class specifies a pattern for word boundaries when reading text. setDelimiter() usePattern() useDelimiter() setPattern()
useDelimiter()
Assume the array of integers values has been created. Which condition must be used in the indicated area so the loop below will assign max the largest value in values? int max = values[0]; for (int current = 1; current < values.length; current++) { if (/* Put condition here */) max = values[current]; } current > max max > current max > values[current] values[current] > max
values[current] > max
The following statement gets an element from position 4 in an array: x = a[4]; What is the equivalent operation using an array list? x = a.get(4); x = a.get(); x = a.get[4]; x = a[4];
x = a.get(4);
Consider the following code snippet: public class MyMouseListener { public void mousePressed(MouseEvent event) { double x; double y; _______ System.out.println("x: " + x + ", y: " + y); } } Which of the following statements should be in the indicated position to print out where the mouse was pressed? x = event.printX(); y = event.printY(); x = (MouseEvent) getX(); y = (MouseEvent) getY(); x = event.getX(); y = event.getY(); x = event.getXposition(); y = event.getYposition();
x = event.getX(); y = event.getY();