Comp Sci AP

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

How many comparisons will the selection sort algorithm make on an array of 8 elements?

28

Which of the following statements will create a Person object that represents an adult person?

Person p = new Person ("Homer", 23);

What happens when the following code snippet runs?

2

What is printed when the code segment is executed?

9

When would you use a for-each loop instead of a for loop?

If you want to access every element of an array and want to refer to elements through a variable name instead of an array index.

Which Java Data Type would be the best suited to represent whether or not a student has completed their homework?

boolean

Consider the following methods. When the call test ( ) is executed, what are the values of s and n at the point indicated by / * End of method * / ?

. s / n world / 6

Assuming that x is initialized to the same positive integer value as the original, which of the following code segments will produce the same output as the original code segment?

I and II only

What value is returned by the following method call?

6

What is printed when num has the value 14 ?

16 17

What will the following code segment output?

3

True or False: Because ArrayLists can only store object values, int and double values cannot be added to an ArrayList.

False

int[] numbers = {1, 2, 3, 3, 4, 5}; boolean mysteryBoolean = false; for (int i = 0; i < numbers.length - 1; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] == numbers[j]) { mysteryBoolean = true; } } }

Finds duplicate values in an array

What value will be printed in the console after this series of commands? Assume that the ArrayList package has been imported.

2

What, if anything, is printed as a result of executing the code segment?

3 2 1

What is the output of the following code snippet?

x is 100 The size of numArray is 25

Consider the following method. Assume that a List<Integer> values initially contains the following Integer values. What will values contain as a result of executing mystery(values) ?

[0, 4, 2, 5, 3]

The following array is to be sorted biggest to smallest using insertion sort. [10, 40, 50, 30, 20, 60] What will the array look like after the third pass of the for loop?

[50, 40, 30, 10, 20, 60]

Which of the following statements assigns a random integer between 1 and 10, inclusive, to rn ?

int rn = (int) (Math.random() * 10) + 1;

Which of the following code segments, if located in a method in the same class as changeIt, will cause the array myArray to contain {0, 5, 0, 0} ?

int[] myArray = new int[4]; changeIt(myArray, 1, 5);

Classes' access specifier is generally set to

public so that any user can create and use objects of the class.

What is the output after this code snippet runs?

7991906787

Which of the following changes to the sort method would correctly sort the integers in elements into descending order?

I and III only

How does Selection Sort work to sort an array?

. Selection Sort iterates through each index and swaps the current index with the minimum value that exists in the indices greater than the current index.

int[ ] values = {17, 34, 56, 2, 19, 100}; for (int value : values) { if (value % 2 == 0) System.out.println(value + " is even"); }

34 is even 56 is even 2 is even 100 is even

Static methods can access Selected:

Only other static instance variables and class methods

How many times does the following loop iterate?// x has been initialized with a positive int valuefor (int count = 0; count <= x; count++){ System.out.print("*");}

x + 1 times

What is printed as a result of executing the code segment?

4 10 16

What will be the output of the following code snippet?public class Casting{ public static void main(String[] args) { int total = 100; int numPeople = 40; double average; average = total / (double) numPeople;System.out.println("Average: " + average);}}

Average: 2.5

What does it mean to be a client of a class?

Being a client of a class means that we can use its methods and functionality without necessarily understanding how it works.

Which of the code segments could be used to replace /* missing code */ so that compareTo can be used to order TemperatureReading objects by increasing temperature value? a. II only

I and III only

Consider the following code segment, which is intended to declare and initialize the two-dimensional (2D) String array things. /* missing code */ = {{"spices", "garlic", "onion", "pepper"}, {"clothing", "hat", "scarf", "gloves"}, {"plants", "tree", "bush", "flower"}, {"vehicles", "car", "boat", "airplane"}}; Which of the following could replace /* missing code */ so that things is properly declared?

String[][] things

What is the value of x after the statement has been executed?

false

Which of the following variable declarations are most appropriate to replace /* missing declarations */ in this code segment?

final double pi = 3.14159; double d = 1.5; double c;

public void changeIt(int[] arr, int index, int newValue) { arr[index] += newValue; } Which of the following code segments, if located in a method in the same class as changeIt, will cause the array myArray to contain {0, 5, 0, 0} ?

int[] myArray = new int[4]; changeIt(myArray, 1, 5);

Which of the following constructors for the Glasses class correctly sets the script instance variable correctly? Assume any method calls are valid.

public Glasses(Prescription thePrescription){ script = new Prescription(thePrescription.getLeft(),thePrescription.getRight());}

In the code segment below, assume that the ArrayList object numbers has been properly declared and initialized to contain [0, 2, 4, 5]. for (int k = numbers.size() - 1; k >= 0; k--) { if (numbers.get(k) > k) { System.out.print(k + " "); } } What, if anything, is printed as a result of executing the code segment?

3 2 1

True or False: You can modify the elements of an array when you traverse it with a for-each loop.

False

The creator of this 2D array would like to look at the height of the city park along the longitude 100.0 - which traversal method would make the most sense in order to do so?

Column-Major Order

Which of the following best describes the error, if any, in the code segment?

In the expression (double) (sum / 2), the cast to double is applied too late, so the average will be less than the expected result for odd values of sum.

public void remove3s(ArrayList<Integer> array) { int counter = 0; while(counter < array.size()) { if(array.get(counter) %3 == 0) { array.remove(counter); counter++ } else { counter++; } } }

No, this method is not written correctly, as the counter in the if statement will skip the next value, as the values will shift down in the ArrayList.

Which of these methods will properly traverse two ArrayLists and print any index that have the same value in both ArrayLists?

public void printSharedValues(ArrayList<Integer> array1, ArrayList<E> array2) { int index = 0; int size; if(array1.size() > array2.size()) { size = array2.size(); } else { size = array1.size(); } while(index < size) { if(array1.get(index) == array2.get(index)) { System.out.println(index); } index++; } }

double[][] something = { {2.5, 6.8, 8.3, 2.3, 0.0}, {6.1, 10.2, 1.3, -2.5, -9.9}, {1.1, 2.3, 5.8, 13.21, 34.55} };

something[2][3] = 8.8;

What does the following code snippet output? int[] numbers = {1, 2, 3, 4, 5}; int[] temp = new int[numbers.length]; for (int i = 0; i < numbers.length - 1; i++) { temp[i + 1] = numbers[i]; } temp[0] = numbers[numbers.length - 1]; numbers = temp; for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); }

5 1 2 3 4

What is the result of array[0][1] + array[2][0]?

9

Consider the following code segment. String str = "CompSci"; System.out.println(str.substring(0, 3)); int num = str.length(); What is the value of num when the code segment is executed?

7

Which of the following logical statements is equivalent to!(A && B)Where A and B are boolean values

c. !A || !B

Consider the following code segment in which the int variable x has been properly declared and initialized. if (x % 2 == 1) { System.out.println("YES"); } else { System.out.println("NO"); } Assuming that x is initialized to the same positive integer value as the original, which of the following code segments will produce the same output as the original code segment?

I and II only

What would be printed the first time printPhrases was called from main? public class PrintQuestion { private static String phrase = "Hello World!"; public static void printPhrases() { String phrase = "hi"; System.out.println(phrase); phrase = "hello"; } }

hi

Which of the following is NOT part of the constructor signature?

Which instance variables are initialized

Consider the following code segment. System.out.print("*"); System.out.println("**"); System.out.println("***"); System.out.print("****"); What is printed as a result of executing the code segment?

*** *** ****

double[][] something = { {2.5, 6.8, 8.3, 2.3, 0.0}, {6.1, 10.2, 1.3, -2.5, -9.9}, {1.1, 2.3, 5.8, 13.21, 34.55} };

1.3

Which choice can replace /* missing code */ so that the statement compiles without error?

ArrayList<Student>()

Which of the following best describes the behavior of the code segment?

Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.

Consider the following code segment. System.out.print("One"); // Line 1 System.out.print("Two"); // Line 2 System.out.print("Three"); // Line 3 System.out.print("Four"); // Line 4 The code segment is intended to produce the following output, but does not work as intended. OneTwo ThreeFour Which of the following changes can be made so that the code segment produces the intended output?

Changing print to println in line 2 only

Consider the following class definition. public class WordClass { private final String word; private static String max_word = ""; public WordClass (String s) { word = s; if (word.length() > max_word.length()) { max_word = word; } } } Which of the following is a true statement about the behavior of WordClass objects?

Every time a WordClass object is created, the max_word variable is referenced.

Which of the following code segments will assign the correct string to gradefor a given integer score ?

I and III only

Assume that sum1D works correctly. Which of the following can replace / * missing code * / so that the sum2D method works correctly?

I, II, and III

Consider the following class definition. public class Student { private int studentID; private int gradeLevel; private boolean honorRoll; public Student(int s, int g) { studentID = s; gradeLevel = g; honorRoll = false; } public Student(int s) { studentID = s; gradeLevel = 9; honorRoll = false; } }

I, II, and III

Consider the following code segment, which appears in a method in a class other than Password. The code segment does not compile. Password p = new Password("password"); System.out.println("The new password is " + p.reset("password")); Which of the following best identifies the reason the code segment does not compile?

The reset method does not return a value that can be printed.

Consider the following code segment. for (int j = 0; j < 3; j++) { for (int k = 0; k < 4; k++) { System.out.println("Fun"); } } Which of the following best explains how changing the outer for loop header to for (int j = 0; j <= 3; j++) affects the output of the code segment?

The string "Fun" will be printed more times because the outer loop will execute more times.

A code segment (not shown) is intended to determine the number of players whose average score in a game exceeds 0.5. A player's average score is stored in avgScore, and the number of players who meet the criterion is stored in the variable count. Which of the following pairs of declarations is most appropriate for the code segment described?

double avgScore; int count;

Consider the following statement. boolean x = (5 < 8) == (5 == 8); What is the value of x after the statement has been executed?

false

Consider the following code segment, where nums is a two-dimensional (2D) array of integers. The code segment is intended to print "test1234". System.out.print("test" + nums[0][0] + nums[1][0] + nums[1][1] + nums[0][1]); Which of the following code segments properly declares and initializes nums so that the code segment works as intended?

int[][] nums = {{1, 4}, {2, 3}};

What would be a correct way to instantiate this 2D array?

int[][] table = { {1, 0, 10, 0}, {3, 8, 38, 0} };

Consider the following method, which is intended to return the product of 3 and the nonnegative difference between its two int parameters. public int threeTimesDiff (int num1, int num2) { return 3 * (num1 - num2); } Which, if any, precondition is required so that the method works as intended for all values of the parameters that satisfy the precondition?

num1 >= num2

Which of these method implementations would correctly insert an element into an ArrayList before every even index?

public void addEven(ArrayList<E> array, E element) { for(int index = 1; index < array.size(); index++) { if(index %2 == 0) { array.add(index, element); index++; } } }

Suppose there is a local variable declared in the method of a particular class. The local variable's scope is

the method in which is it declared

The Glasses class represents a pair of eyeglasses. One of its instance variables is a Prescription object called script. The Prescription object has instance variables that stores the prescription for the left and right eye. Which of the following constructors for the Glasses class correctly sets the script instance variable correctly? Assume any method calls are valid.

public Glasses(Prescription thePrescription){ script = new Prescription(thePrescription.getLeft(),thePrescription.getRight());}

Consider the following code segment. int[] arr = {3, 1, 0, 4, 2}; for(int j = 0; j < arr.length; j++) { System.out.print(arr[j] + j + " "); } What, if anything, is printed as a result of executing the code segment?

3 2 2 7 6

Which statement could be added in place of /*missing code*/ in the while loop below so that it doesn't run indefinitely?public static void main(String[] args){ int x = 7; while (x > 0) { System.out.println(x);/* missing code */ }}

I and II

Which of the following can be used to replace /* missing implementation */ so that removeName will work as intended?

III only

How does Linear Search work?

Linear Search traverses an array until the desired value is found, or until the end of the array

Static methods can access

Only other static instance variables and class methods

How does Selection Sort work to sort an array?

Selection Sort iterates through each index and swaps the current index with the minimum value that exists in the indices greater than the current index.

Which of the following best describes the behavior of the code segment?

The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1.

Which of the following best explains how the output changes from code segment I to code segment II?

The code segments print the same values but in a different order, because code segment I iterates from 1 to 5 and code segment II iterates from 5 to 1.

What is the name of the Power object contained in the ImaginaryFriend class after the following code snippet runs? The object friend is an ImaginaryFriend object. One instance variable of friend is a Power object. The method getPower is the Power object's accessor. Power ability = friend.getPower(); ability.setName("X-Ray Vision");

X-Ray Vision

How many times is the println method called when the code segment is executed?

5

What is printed as a result of executing this code segment?

5

What value will be printed in the console after this series of commands? Assume that the ArrayList package has been imported. ArrayList<Integer> array = new ArrayList<Integer>(); array.add(3); array.add(9); array.add(10); array.remove(1); array.set(0, 3); int num = array.get(1); System.out.println(num);

10

Consider the following code segment. int[] arr = {1, 2, 4, 0, 3}; for (int i : arr) { System.out.print(i); } Which of the following code segments will produce the same output as the code segment above?

III only

onsider the following code segment. System.out.print(I do not fear computers. ); // Line 1 System.out.println(I fear the lack of them.); // Line 2 System.out.println(--Isaac Asimov); // Line 3 The code segment is intended to produce the following output but may not work as intended. I do not fear computers. I fear the lack of them. --Isaac Asimov Which change, if any, can be made so that the code segment produces the intended output?

In lines 1, 2, and 3, the text that appears in parentheses should be enclosed in quotation marks.

Consider the following method. public String wordPlay(String word) { String str = ""; for (int k = 0; k < word.length(); k++) { if (k % 3 == 0) { str = word.substring(k, k + 1) + str; } } return str; } The following code segment appears in another method in the same class as wordPlay. System.out.println(wordPlay("Computer Science")); What is printed as a result of executing the code segment?

eeSepC

The code segment below is intended to calculate the circumference c of a circle with the diameter d of 1.5. The circumference of a circle is equal to its diameter times pi. /* missing declarations */ c = pi * d; Which of the following variable declarations are most appropriate to replace /* missing declarations */ in this code segment?

final double pi = 3.14159; double d = 1.5; double c;

Question 15 Consider the following code snippet. What would the output be?String school = "Rydell High School";System.out.println(school.substring(8));System.out.println(school);

igh SchoolRydell High School

Consider the following code segment. int count = 0; for (int k = 0; k < 10; k++) { count++; } System.out.println(count); Which of the following code segments will produce the same output as the code segment above?

int count = 0; for (int k = 9; k >= 0; k--) { count++; } System.out.println(count); This is the correct answer. e. int count = 0; for (int k = 1; k < 10; k++) { count++; } System.out.println(count);

Which of the following is a proper way to declare and initialize a variable in Java?

int myNumber = 10;

Which of the following methods is implemented correctly with respect to the method's return type?

public String getColor(){ return "Red";}

Consider the following code segment, which is intended to simulate a random process. The code is intended to set the value of the variable event to exactly one of the values 1, 2, or 3, depending on the probability of an event occurring. The value of event should be set to 1 if the probability is 70 percent or less. The value of event should be set to 2 if the probability is greater than 70 percent but no more than 80 percent. The value of event should be set to 3 if the probability is greater than 80 percent. The variable randomNumber is used to simulate the probability of the event occurring.

randomNumber = 0.70;

Logical equality compares the data of the objects.

true

Consider the following method. public static String changeStr(String str) { String result = ""; for (int i = str.length() - 1; i >= str.length() / 2; i -= 2) { result += str.substring(i, i + 1); } return result; } What value is returned as a result of the method call changeStr("12345") ?

"53"

What, if anything, is printed as a result of executing the code segment?

3 2 2 7 6

Which of the following best describes the contents of numbers after the following statement has been executed? int m = mystery(n);

All values in positions m+1 through numbers.length-1 are greater than or equal to n.

Accessors and mutators are used to

Allow private data to be accessed outside of the class and be safely modified.

Assume that a two-dimensional (2D) array arr of String objects with 3 rows and 4 columns has been properly declared and initialized. Which of the following can be used to print the elements in the four corner elements of arr ?

System.out.print(arr[0][0] + arr[0][3] + arr[2][0] + arr[2][3]);

Why do we use for loops in Java?

To repeat something for a fixed number of times

What is printed when the code segment is executed?

comp omp mp p

The twoInARow method below is intended to return true if any two consecutive elements of the parameter arr are equal in value and return false otherwise. public boolean twoInARow(int[] arr) { /* missing loop header */ { if (arr[k] == arr[k + 1]) { return true; } } return false; } Which of the following can be used to replace /* missing loop header */ so that the method will work as intended?

for (int k = 0; k < arr.length - 1; k++)

A student has created a Song class. The class contains the following variables. A String variable called artist to represent the artist name A String variable called title to represent the song title A String variable called album to represent the album title The object happyBirthday will be declared as type Song. Which of the following statements is true?

happyBirthday is an instance of the Song class.

Which of the following correctly uses the this keyword?

public boolean isSame(Bird other) { return this.name.equals(other.name); }

Consider the following class definition. public class Something { private static int count = 0; public Something() { count += 5; } public static void increment() { count++; } } The following code segment appears in a method in a class other than Something. Something s = new Something(); Something.increment(); Which of the following best describes the behavior of the code segment?

The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1.

Consider the following loop, where n is some positive integer.for (int i = 0; i < n; i += 2){ if (/* condition to test */) { /* perform some action */ }}In terms of n, which Java expression represents the maximum number of times that/* perform some action */ could be executed? Selected:

(n + 1) / 2

What is the output after this code snippet runs? int[] scores = {80, 92, 91, 68, 88}; int i = 0; while (i < scores.length - 1) { System.out.println(scores[i] * 2); i ++; }

160 184 182 136

Consider the following code segment. String str = "a black cat sat on a table"; int counter = 0; for (int i = 0; i < str.length() - 1; i++) { if (str.substring(i, i + 1).equals("a") && !str.substring(i + 1, i + 2).equals("b")) { counter++; } } System.out.println(counter); What is printed as a result of executing this code segment?

5

Which of the following is the best postcondition for checkArray ?

Returns the index of the largest value in array array

The class Worker is defined below. The class includes the method getEarnings, which is intended to return the total amount earned by the worker. public class Worker { private double hourlyRate; private double hoursWorked; private double earnings; public Worker(double rate, double hours) { hourlyRate = rate; hoursWorked = hours; } private void calculateEarnings() { double earnings = 0.0; earnings += hourlyRate * hoursWorked; } public double getEarnings() { calculateEarnings(); return earnings; } } The following code segment appears in a method in a class other than Worker. The code segment is intended to print the value 800.0, but instead prints a different value because of an error in the Worker class. Worker bob = new Worker(20.0, 40.0); System.out.println(bob.getEarnings()); Which of the following best explains why an incorrect value is printed?

The variable earnings in the calculateEarnings method is a local variable.

Consider the following declaration that appears in a class other than TimeRecord. TimeRecord [ ] timeCards = new TimeRecord [100] ;Assume that timeCards has been initialized with TimeRecord objects. Consider the following code segment that is intended to compute the total of all the times stored in timeCards. Which of the following can be used to replace / * missing expression * / so that the code segment will work as intended?

Total.advance(timeCards[k].getHours(), timeCards[k].getMinutes())

Consider the following method. public boolean checkIndexes(double[][] data, int row, int col) { int numRows = data.length; if (row < numRows) { int numCols = data[0].length; return col < numCols; } else { return false; } } Consider the following variable declaration and initialization, which appears in a method in the same class as checkIndexes. double[][] table = new double[5][6]; Which of the following method calls returns a value of true ?

checkIndexes(table, 4, 5)

Consider the following code segment. int x = 7; if (x < 7) { x = 2 * x; } if (x % 3 == 1) { x = x + 2; } System.out.print(3 * x); What is printed as a result of executing the code segment?

27

What will the following code segment output? String[] grades = {"A","C","B","A","B", "A"}; int mystery = 0; for (int i = 0; i < grades.length; i++) { if (grades[i].equals("A")) { mystery ++; } } System.out.println(mystery);

3

Consider the following method. public int getTheResult(int n) { int product = 1; for (int number = 1; number < n; number++) { if (number % 2 == 0) product *= number; } return product; } What value is returned as a result of the call getTheResult(8) ?

48

Given the following: double[][] something = { {2.5, 6.8, 8.3, 2.3, 0.0}, {6.1, 10.2, 1.3, -2.5, -9.9}, {1.1, 2.3, 5.8, 13.21, 34.55} }; What is the value of something[2].length?

5

Consider the following code segment. int[][] arr = {{6, 2, 5, 7}, {7, 6, 1, 2}}; for (int j = 0; j < arr.length; j++) { for (int k = 0; k < arr[0].length; k++) { if (arr[j][k] > j + k) { System.out.println("!"); } } } How many times will "!" be printed when the code segment is executed?

6 times

Consider the following code segment. double regularPrice = 100; boolean onClearance = true; boolean hasCoupon = false; double finalPrice = regularPrice; if(onClearance) { finalPrice -= finalPrice * 0.25; } if(hasCoupon) { finalPrice -= 5.0; } System.out.println(finalPrice); What is printed as a result of executing the code segment?

75.0

Consider the following code segment. int[][] array2D = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; for (int[] i : array2D) { for (int x : i) { System.out.print(x + " "); } System.out.println(" "); } How many times will the statement System.out.print(x + " ") be executed?

16 times

Which of the following changes, if any, can be made to line 4 so that the method will work as intended?

Changing j <= arr.length; to j < arr.length;

A 2D double array terrainMap is declared and initialized to track the terrain of a city park. Each value in the 2D array represents the height of a particular latitude and longitude above sea level. Longitude is represented by the columns in the 2D array and latitude is represented by each row in the 2D array. Which of the following would be the correct way to print out all the indices that are more than 5 feet above sea level?

public static void above5(double[][] array) { for(int row = array.length-1; row > 0; row--) { for(int column = 0; column < array[row].length; column++) { if(array[row][column] > 5.0) { System.out.println(row +"," + column); } } } }

Why can't this be used in static methods?

Static methods are not called using an object. Thus, this would be null.

Question 3 Consider the following code segment. What is printed as a result of executing the code segment?

[dog, fish, cat]

We want to create a 2D double array with 6 rows and 7 columns and assign it to connectFour. Which of these is correct? Selected:

double[][] connectFour = new double[6][7];

Which index is the last element in an array called highTemps at?

highTemps.length - 1

On Sunday night, a meteorologist records predicted daily high temperatures, in degrees Fahrenheit, for the next seven days. At the end of each day, the meteorologist records the actual daily high temperature, in degrees Fahrenheit. At the end of the seven-day period, the meteorologist would like to find the greatest absolute difference between a predicted temperature and a corresponding actual temperature. Consider the following method, which is intended to return the greatest absolute difference between any pair of corresponding elements in the int arrays pred and act. /** Precondition: pred and act have the same non-zero length. */ public static int diff(int[] pred, int[] act) { int num = Integer.MIN_VALUE; for (int i = 0; i < pred.length; i++) { /* missing code */ } return num; } Which of the following code segments can be used to replace /* missing code */ so that diff will work as intended?

if (Math.abs(pred[i] - act[i]) > num) { num = Math.abs(pred[i] - act[i]); }

If a new variable Rectangle shape = new Rectangle(10, 20); was initialized, what is the correct syntax for retrieving the area of shape?

int area = shape.getArea();

Which is the correct way to construct and assign a 2D array, with 8 rows and 10 columns, to the variable popcorn?

int[][] popcorn = new int[8][10];

What does the keyword final do?

It prevents variables from being altered.

What is the output of this program?int numTreeRings = 50;System.out.println("How old is the tree?");if(numTreeRings > 10){ System.out.println("Still young!");}if(numTreeRings > 40){ System.out.println("Pretty old!");}if(numTreeRings > 150){ System.out.println("Very old!");}

How old is the tree? Still young! Pretty old!

Will this method correctly traverse an ArrayList and remove all multiples of 3?

No, this method is not written correctly, as the counter in the if statement will skip the next value, as the values will shift down in the ArrayList.

Consider the following method countNegatives, which searches an ArrayList of Integer objects and returns the number of elements in the list that are less than 0. public static int countNegatives(ArrayList<Integer> arr) { int count = 0; for (int j = 0; j < arr.size(); j++) // Line 4 { if (arr.get(j) < 0) { count++; } } return count; } Which of the following best explains the impact to the countNegatives method when, in line 4, j < arr.size() is replaced with j <= arr.size() - 1 ?

It has no impact on the behavior of the method.

Given the following: double[][] something = { {2.5, 6.8, 8.3, 2.3, 0.0}, {6.1, 10.2, 1.3, -2.5, -9.9}, {1.1, 2.3, 5.8, 13.21, 34.55} }; What is the value of something[1][2]?

1.3

Consider the following code segment. double d1 = 10.0; Double d2 = 20.0; Double d3 = new Double(30.0); double d4 = new Double(40.0); System.out.println(d1 + d2 + d3.doubleValue() + d4); What, if anything, is printed when the code segment is executed?

100.0

Consider the following code segment. double num = 9 / 4; System.out.print(num); System.out.print(" "); System.out.print((int) num); What is printed as a result of executing the code segment?

2.0 2

Given the following: double[][] something = { {2.5, 6.8, 8.3, 2.3, 0.0}, {6.1, 10.2, 1.3, -2.5, -9.9}, {1.1, 2.3, 5.8, 13.21, 34.55} }; What is the value of something[2][1]?

2.3

What would the value of the static variable phrase be after the first time printPhrases was called from main? public class PrintQuestion { private static String phrase = "Hello World!"; public static void printPhrases() { String phrase = "hi"; System.out.println(phrase); phrase = "hello"; } }

Hello World!

What value will be printed in the console after this series of commands? Assume that the ArrayList package has been imported

Names: Lebron and Serena

Question 4 The removeElement method is intended to remove all instances of target from the ArrayList object data passed as a parameter. The method does not work as intended for all inputs. public void removeElement(ArrayList<Integer> data, int target) { for (int j = 0; j < data.size(); j++) { if (data.get(j).equals(target)) { data.remove(j); } } } Assume that the ArrayList object scores and the int variable low_score have been properly declared and initialized. In which of the following cases will the method call removeElement(scores, low_score) fail to produce the intended result?

When scores is [8, 8, 4, 3, 3, 6] and low_score is 3

Given the following: String[][] poem = { {"I", "am", "the", "cookie", "monster."}, {"Would", "you", "like", "a", "cookie?"}, {"COOOOKIE", "OM", "NOM", "NOM", "NOM"} }; Which of the following code fragments would produce the following output? I am the cookie monster. Would you like a cookie? COOOOKIE OM NOM NOM NOM.

for (int line = 0; line < poem.length; line++) { for (int word = 0; word < poem[line].length; word++) { System.out.print(poem[line][word] + " "); } System.out.println(); }

A 2D double array terrainMap is declared and initialized to track the terrain of a city park. Each value in the 2D array represents the height of a particular latitude and longitude above sea level. Longitude is represented by the columns in the 2D array and latitude is represented by each row in the 2D array. Which of the following would be a correct way to write the traversal for this 2D array?

for(double[] row: terrainMap) { for(double num: row) { System.out.print(num + " "); } System.out.println(); }

Which of the following code snippet gets the THIRD element in the scores array and assigns it to an int called myScore , then sets the FOURTH element in the scores array (previously declared) to 72?

int myScore = scores[2]; scores[3] = 72;

The return type of an accessor method

must match the type of of the instance variable being accessed

Assume that object references one, two, and three have been declared and instantiated to be of the same type. Assume also that one == two evaluates to true and that two.equals(three) evaluates to false. Consider the following code segment. if (one.equals(two)) { System.out.println("one dot equals two"); } if (one.equals(three)) { System.out.println("one dot equals three"); } if (two == three) { System.out.println("two equals equals three"); } What, if anything, is printed as a result of executing the code segment?

one dot equals two


Ensembles d'études connexes

Leadership In Organizations Exam 3- Lion King Articles, Chapters 12, 13, 14, and 15

View Set

Chapter 24: Fetal Head and Brain - pathology

View Set

FAR 4 M1 (Financial Instruments)

View Set

Unit 13: Microbial Diseases; Lesson 1: Microbial Diseases of the Skin and Eyes

View Set