Chapter 5 Review Questions Flashcards

1
Q

1.What is output by the following code? (Choose all that apply.)
~~~
1: public class Fish {
2: public static void main(String[] args) {
3: int numFish = 4;
4: String fishType = “tuna”;
5: String anotherFish = numFish + 1;
6: System.out.println(anotherFish + “ “ + fishType);
7: System.out.println(numFish + “ “ + 1);
8: } }
~~~
A. 4 1
B. 5
C. 5 tuna
D. 5tuna
E. 51tuna
F. The code does not compile.

A

F. Line 5 does not compile.

This question is checking to see whether you are paying attention to the types. numFish is an int, and 1 is an int. Therefore, we use numeric addition and get 5. The problem is that we can’t store an int in a String variable. Supposing line 5 said String anotherFish = numFish + 1 + “”;. In that case, the answer would be option A and option C. The variable defined on line 5 would be the string “5”, and both output statements would use concatenation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

2.Which of the following are output by this code? (Choose all that apply.)
~~~
3: var s = “Hello”;
4: var t = new String(s);
5: if (“Hello”.equals(s)) System.out.println(“one”);
6: if (t == s) System.out.println(“two”);
7: if (t.intern() == s) System.out.println(“three”);
8: if (“Hello” == s) System.out.println(“four”);
9: if (“Hello”.intern() == t) System.out.println(“five”);
~~~
A. one
B. two
C. three
D. four
E. five
F. The code does not compile.
G. None of the above

A

A, C, D.
The code compiles fine. Line 3 points to the String in the string pool. Line 4 calls the String constructor explicitly and is therefore a different object than s. Lines 5 checks for object equality, which is true, and so prints one. Line 6 uses object reference equality, which is not true since we have different objects. Line 7 calls intern(), which returns the value from the string pool and is therefore the same reference as s. Line 8 also compares references but is true since both references point to the object from the string pool. Finally, line 9 is a trick. The string Hello is already in the string pool, so calling intern() does not change anything. The reference t is a different object, so the result is still false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

3.Which statements about the following code snippet are correct? (Choose all that apply.)
~~~
List<String> gorillas = new ArrayList<>();
for(var koko : gorillas)
System.out.println(koko);
var monkeys = new ArrayList<>();
for(var albert : monkeys)
System.out.println(albert);
List chimpanzees = new ArrayList<Integer>();
for(var ham : chimpanzees)
System.out.println(ham);
~~~
A. The data type of koko is String.
B. The data type of koko is Object.
C. The data type of albert is Object.
D. The data type of albert is undefined.
E. The data type of ham is Integer.
F. The data type of ham is Object.
G. None of the above, as the code does not compile</Integer></String>

A

A, C, F.
The code does compile, making option G incorrect. In the first for-each loop, gorillas has a type of List<String>, so each element koko has a type of String, making option A correct. In the second for-each loop, you might think that the diamond operator <> cannot be used with var without a compilation error, but it absolutely can. This result is monkeys having a type of ArrayList<Object> with albert having a data type of Object, making option C correct. While var might indicate an ambiguous data type, there is no such thing as an undefined data type in Java, so option D is incorrect. In the last for-each loop, chimpanzee has a data type of List. Since the left side does not define a generic type, the compiler will treat this as List<Object>, and ham will have a data type of Object, making option F correct. Even though the elements of chimpanzees might be Integer as defined, ham would require an explicit cast to call an Integer method, such as ham.intValue().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

4.What is the result of the following code?
~~~
7: StringBuilder sb = new StringBuilder();
8: sb.append(“aaa”).insert(1, “bb”).insert(4, “ccc”);
9: System.out.println(sb);
~~~
A. abbaaccc
B. abbaccca
C. bbaaaccc
D. bbaaccca
E. An empty line
F. The code does not compile.

A

B. This example uses method chaining. After the call to append(), sb contains “aaa”. That result is passed to the first insert() call, which inserts at index 1. At this point sb contains abbaa. That result is passed to the final insert(), which inserts at index 4, resulting in abbaccca.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

5.What is the result of the following code?
~~~
12: int count = 0;
13: String s1 = “java”;
14: String s2 = “java”;
15: StringBuilder s3 = new StringBuilder(“java”);
16: if (s1 == s2) count++;
17: if (s1.equals(s2)) count++;
18: if (s1 == s3) count++;
19: if (s1.equals(s3)) count++;
20: System.out.println(count);
~~~
A. 0
B. 1
C. 2
D. 3
E. 4
F. An exception is thrown.
G. The code does not compile.

A

G. The question is trying to distract you into paying attention to logical equality versus object reference equality. The exam creators are hoping you will miss the fact that line 18 does not compile. Java does not allow you to compare String and StringBuilder using ==.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

6.What is the result of the following code?
~~~
public class Lion {
public void roar(String roar1, StringBuilder roar2) {
roar1.concat(“!!!”);
roar2.append(“!!!”);
}
public static void main(String[] args) {
String roar1 = “roar”;
StringBuilder roar2 = new StringBuilder(“roar”);
new Lion().roar(roar1, roar2);
System.out.println(roar1 + “ “ + roar2);
} }
~~~
A. roar roar
B. roar roar!!!
C. roar!!! roar
D. roar!!! roar!!!
E. An exception is thrown.
F. The code does not compile.

A

B. A String is immutable. Calling concat() returns a new String but does not change the original. A StringBuilder is mutable. Calling append() adds characters to the existing character sequence along with returning a reference to the same object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

7.Which of the following return the number 5 when run independently? (Choose all that apply.)
~~~
var string = “12345”;
var builder = new StringBuilder(“12345”);
~~~
A. builder.charAt(4)
B. builder.replace(2, 4, “6”).charAt(3)
C. builder.replace(2, 5, “6”).charAt(2)
D. string.charAt(5)
E. string.length
F. string.replace(“123”, “1”).charAt(2)
G. None of the above

A

A, B, F. Remember that indexes are zero-based, which means that index 4 corresponds to 5 and option A is correct. For option B, the replace() method starts the replacement at index 2 and ends before index 4. This means two characters are replaced, and charAt(3) is called on the intermediate value of 1265. The character at index 3 is 5, making option B correct. Option C is similar, making the intermediate value 126 and returning 6. Option D results in an exception since there is no character at index 5. Option E is incorrect. It does not compile because the parentheses for the length() method are missing. Finally, option F’s replace results in the intermediate value 145. The character at index 2 is 5, so option F is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

8.What is output by the following code? (Choose all that apply.)
~~~
String numbers = “012345678”;
System.out.println(numbers.substring(1, 3));
System.out.println(numbers.substring(7, 7));
System.out.println(numbers.substring(7));
~~~
A. 12
B. 123
C. 7
D. 78
E. A blank line
F. The code does not compile.
G. An exception is thrown.

A

A, D, E. substring() has two forms. The first takes the index to start with and the index to stop immediately before. The second takes just the index to start with and goes to the end of the String. Remember that indexes are zero-based. The first call starts at index 1 and ends with index 2 since it needs to stop before index 3. The second call starts at index 7 and ends in the same place, resulting in an empty String. This prints out a blank line. The final call starts at index 7 and goes to the end of the String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

9.What is the result of the following code? (Choose all that apply.)
style
~~~
14: String s1 = “purr”;
15: String s2 = “”;
16:
17: s1.toUpperCase();
18: s1.trim();
19: s1.substring(1, 3);
20: s1 += “two”;
21:
22: s2 += 2;
23: s2 += ‘c’;
24: s2 += false;
25:
26: if ( s2 == “2cfalse”) System.out.println(“==”);
27: if ( s2.equals(“2cfalse”)) System.out.println(“equals”);
28: System.out.println(s1.length());
~~~
A. 2
B. 4
C. 7
D. 10
E. ==
F. equals
G. An exception is thrown.
H. The code does not compile.

A

C, F. This question is tricky because it has two parts. The first is trying to see if you know that String objects are immutable. Line 17 returns “PURR”, but the result is ignored and not stored in s1. Line 18 returns “purr” since there is no whitespace present, but the result is again ignored. Line 19 returns “ur” because it starts with index 1 and ends before index 3 using zero-based indexes. The result is ignored again. Finally, on line 20 something happens. We concatenate three new characters to s1 and now have a String of length 7, making option C correct. For the second part, a += 2 expands to a = a + 2. A String concatenated with any other type gives a String. Lines 22, 23, and 24 all append to a, giving a result of “2cfalse”. The if statement on line 27 returns true because the values of the two String objects are the same using object equality. The if statement on line 26 returns false because the two String objects are not the same in memory. One comes directly from the string pool, and the other comes from building using String operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

10.Which of these statements are true? (Choose all that apply.)
var letters = new StringBuilder("abcdefg");
A. letters.substring(1, 2) returns a single character String.
B. letters.substring(2, 2) returns a single character String.
C. letters.substring(6, 5) returns a single character String.
D. letters.substring(6, 6) returns a single character String.
E. letters.substring(1, 2) throws an exception.
F. letters.substring(2, 2) throws an exception.
G. letters.substring(6, 5) throws an exception.
H. letters.substring(6, 6) throws an exception.

A

A, G. The substring() method includes the starting index but not the ending index. When called with 1 and 2, it returns a single character String, making option A correct and option E incorrect. Calling substring() with 2 as both parameters is legal. It returns an empty String, making options B and F incorrect. Java does not allow the indexes to be specified in reverse order. Option G is correct because it throws a StringIndexOutOfBoundsException. Finally, option H is incorrect because it returns an empty String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

11.What is the result of the following code?
~~~
StringBuilder numbers = new StringBuilder(“0123456789”);
numbers.delete(2, 8);
numbers.append(“-“).insert(2, “+”);
System.out.println(numbers);
~~~
A. 01+89–
B. 012+9–
C. 012+–9
D. 0123456789
E. An exception is thrown.
F. The code does not compile.

A

A. First, we delete the characters at index 2 until the character one before index 8. At this point, 0189 is in numbers. The following line uses method chaining. It appends a dash to the end of the characters sequence, resulting in 0189–, and then inserts a plus sign at index 2, resulting in 01+89–.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

12.What is the result of the following code?
~~~
StringBuilder b = “rumble”;
b.append(4).deleteCharAt(3).delete(3, b.length() - 1);
System.out.println(b);
~~~
A. rum
B. rum4
C. rumb4
D. rumble4
E. An exception is thrown.
6. The code does not compile.

A

F. This is a trick question. The first line does not compile because you cannot assign a String to a StringBuilder. If that line were StringBuilder b = new StringBuilder(“rumble”), the code would compile and print rum4. Watch out for this sort of trick on the exam. You could easily spend a minute working out the character positions for no reason at all.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

13.Which of the following can replace line 4 to print “avaJ”? (Choose all that apply.)
~~~
3: var puzzle = new StringBuilder(“Java”);
4: // INSERT CODE HERE
5: System.out.println(puzzle);
~~~
A. puzzle.reverse();
B. puzzle.append(“vaJ$”).substring(0, 4);
C. puzzle.append(“vaJ$”).delete(0, 3).deleteCharAt(puzzle.length() - 1);
D. puzzle.append(“vaJ$”).delete(0,
3).deleteCharAt(puzzle.length());
E. None of the above

A

A, C. The reverse() method is the easiest way of reversing the characters in a StringBuilder; therefore, option A is correct. In option B, substring() returns a String, which is not stored anywhere. Option C uses method chaining. First, it creates the value “JavavaJ$”. Then, it removes the first three characters, resulting in “avaJ$”. Finally, it removes the last character, resulting in “avaJ”. Option D throws an exception because you cannot delete the character after the last index. Remember that deleteCharAt() uses indexes that are zero-based, and length() counts starting with 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

14.Which of these array declarations is not legal? (Choose all that apply.)
A. int[][] scores = new int[5][];
B. Object[][][] cubbies = new Object[3][0][5];
C. String beans[] = new beans[6];
D. java.util.Date[] dates[] = new
java.util.Date[2][];
E. int[][] types = new int[];
F. int[][] java = new int[][];

A

C, E, F. Option C uses the variable name as if it were a type, which is clearly illegal. Options E and F don’t specify any size. Although it is legal to leave out the size for later dimensions of a multidimensional array, the first one is required. Option A declares a legal 2D array. Option B declares a legal 3D array. Option D declares a legal 2D array. Remember that it is normal to see on the exam types you might not have learned. You aren’t expected to know anything about them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

15.Which of the following can fill in the blanks so the code compiles? (Choose
two.)
~~~
6: char[]c = new char[2];
7: ArrayList l = new ArrayList();
8: int length = __________ + _____________;
~~~
A. c.length
B. c.length()
C. c.size
D c.size()
E. l.length
F. l.length()
G. l.size
H. l.size()

A

A, H. Arrays define a property called length. It is not a method, so parentheses are not allowed, making option A correct. The ArrayList class defines a method called size(), making option H the other correct answer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

16.Which of the following are true? (Choose all that apply.)
A. An array has a fixed size.
B. An ArrayList has a fixed size.
C. An array is immutable.
D. An ArrayList is immutable.
E. Calling equals() on two equivalent arrays returns true.
F. Calling equals() on two equivalent ArrayList objects returns true.
G If you call remove(0) using an empty ArrayList object, it will compile successfully.
H. If you call remove(0) using an empty ArrayList object, it will run successfully.

A

A, F, G. An array is not able to change size, making option A correct and option B incorrect. Neither is immutable, making options C and D incorrect. The elements can change in value. An array does not override equals(), so it uses object equality, making option E incorrect. ArrayList does override equals() and defines it as the same elements in the same order, making option F correct. The compiler does not know when an index is out of bounds and thus can’t give you a compiler error, making option G correct. The code will throw an exception at runtime, though, making option H the final incorrect answer.

17
Q

17.What is the result of the following statements?
~~~
6: var list = new ArrayList<String>();
7: list.add("one");
8: list.add("two");
9: list.add(7);
10: for(var s : list) System.out.print(s);
~~~
A. onetwo
B. onetwo7
C. onetwo followed by an exception
D. Compiler error on line 6
E. Compiler error on line 7
F. Compiler error on line 9
G. Compiler error on line 10</String>

A

F. The code does not compile because list is instantiated using generics. Only String objects can be added to list, and 7 is an int.

18
Q

18.Which of the following pairs fill in the blanks to output 6?
~~~
3: var values = new ____________<Integer>();
4: values.add(4);
5: values.add(4);
6: values.\_\_\_\_\_\_\_\_\_\_\_\_;
7: values.remove(0);
8: for (var v : values) System.out.print(v);
~~~
A. ArrayList and put(1, 6)
B. ArrayList and replace(1, 6)
C. ArrayList and set(1, 6)
D. HashSet and put(1, 6)
E. HashSet and replace(1, 6)
F. HashSet and set(1, 6)
G. The code does not compile with any of these options.</Integer>

A

C. The put() method is used on a Map rather than a List or Set, making options A and D incorrect. The replace() method does not exist on either of these interfaces. Finally, the set method is valid on a List rather than a Set because a List has an index. Therefore, option C is correct.

19
Q

19.What is output by the following? (Choose all that apply.)
~~~
8: List<Integer> list = Arrays.asList(10, 4, -1, 5);
9: int[] array = { 6, -4, 12, 0, -10 };
10: Collections.sort(list);
11:
12: Integer converted[] = list.toArray(new Integer[4]);
13: System.out.println(converted[0]);
14: System.out.println(Arrays.binarySearch(array, 12));
~~~
A. -1
B. 2
C. 4
D. 6
E. 10
F. One of the outputs is undefined.
G. An exception is thrown.
H The code does not compile.</Integer>

A

A, F. The code compiles and runs fine. However, an array must be sorted for binarySearch() to return a meaningful result. Option F is correct because line 14 prints a number, but the behavior is undefined. Line 8 creates a list backed by a fixed-size array of 4. Line 10 sorts it. Line 12 converts it back to an array. The brackets aren’t in the traditional place, but they are still legal. Line 13 prints the first element, which is now –1, making option A the other correct answer.

20
Q

20.Which of the lines contain a compiler error? (Choose all that apply.)
~~~
23: double one = Math.pow(1, 2);
24: int two = Math.round(1.0);
25: float three = Math.random();
26: var doubles = new double[] { one, two, three};
27:
28: String [] names = {“Tom”, “Dick”, “Harry”};
29: List<String> list = names.asList();
30: var other = Arrays.asList(names);
31: other.set(0, "Sue");
~~~
A. Line 23
B. Line 24
C. Line 25
D. Line 26
E. Line 29
F. Line 30
G. Line 31</String>

A

B, C, E. Remember to watch return types on math operations. One of the tricks is option B on line 24. The round() method returns an int when called with a float. However, we are calling it with a double so it returns a long. The other trick is option C on line 25. The random() method returns a double. Converting from an array to an ArrayList uses Arrays.asList(names). There is no asList() method on an array instance, and option E is correct.

21
Q

21.What is the result of the following?
~~~
List<String> hex = Arrays.asList("30", "8", "3A", "FF");
Collections.sort(hex);
int x = Collections.binarySearch(hex, "8");
int y = Collections.binarySearch(hex, "3A");
int z = Collections.binarySearch(hex, "4F");
System.out.println(x + " " + y + " " + z);
~~~
A. 0 1 –2
B. 0 1 –3
C. 2 1 –2
D. 2 1 –3
E. None of the above
F. The code doesn’t compile.</String>

A

D. After sorting, hex contains [30, 3A, 8, FF]. Remember that numbers sort before letters, and strings sort alphabetically. This makes 30 come before 8. A binary search correctly finds 8 at index 2 and 3A at index 1. It cannot find 4F but notices it should be at index 2. The rule when an item isn’t found is to negate that index and subtract 1. Therefore, we get –2–1, which is –3.

22
Q

22.Which of the following are true statements about the following code? (Choose all that apply.)
~~~
4: List<Integer> ages = new ArrayList<>();
5: ages.add(Integer.parseInt("5"));
6: ages.add(Integer.valueOf("6"));
7: ages.add(7);
8: ages.add(null);
9: for (int age : ages) System.out.print(age);
~~~
A. The code compiles.
B. The code throws a runtime exception.
C. Exactly one of the add statements uses autoboxing.
D. Exactly two of the add statements use autoboxing.
E. Exactly three of the add statements use autoboxing.</Integer>

A

A, B, D. Lines 5 and 7 use autoboxing to convert an int to an Integer. Line 6 does not because valueOf() returns an Integer. Line 8 does not because null is not an int. The code does compile. However, when the for loop tries to unbox null into an int, it fails and throws a NullPointerException.

23
Q

23.What is the result of the following?
~~~
List<String> one = new ArrayList<String>();
one.add("abc");
List<String> two = new ArrayList<>();
two.add("abc");
if (one == two)
System.out.println("A");
else if (one.equals(two))
System.out.println("B");
else
System.out.println("C");
~~~
A. A
B B
C. C
D. An exception is thrown.
E. The code does not compile.</String></String></String>

A

B. The first if statement is false because the variables do not point to the same object. The second if statement is true because ArrayList implements equality to mean the same elements in the same order.

24
Q

24.Which statements are true about the following code? (Choose all that apply.)
~~~
public void run(Integer[] ints, Double[] doubles) {
List<Integer> intList = Arrays.asList(ints);
List<Double> doubleList = List.of(doubles);
// more code
}
~~~
A. Adding an element to doubleList is allowed.
B. Adding an element to intList is allowed.
C. Changing the first element in doubleList changes the first element in doubles.
D. Changing the first element in intList changes the first
element in ints.
E. doubleList is immutable.
F. intList is immutable.</Double></Integer>

A

D, E. The first line of code in the method creates a fixed size List backed by an array. This means option D is correct, making options B and F incorrect. The second line of code in the method creates an immutable list, which means no changes are allowed. Therefore, option E is correct, making options A and C incorrect.

25
Q

25.Which of the following statements are true of the following code? (Choose all that apply.)
~~~
String[] s1 = { “Camel”, “Peacock”, “Llama”};
String[] s2 = { “Camel”, “Llama”, “Peacock”};
String[] s3 = { “Camel”};
String[] s4 = { “Camel”, null};
~~~
A. Arrays.compare(s1, s2) returns a positive integer.
B. Arrays.mismatch(s1, s2) returns a positive integer.
C. Arrays.compare(s3, s4) returns a positive integer.
D. Arrays.mismatch(s3, s4) returns a positive integer.
E. Arrays.compare(s4, s4) returns a positive integer.
F. Arrays.mismatch(s4, s4) returns a positive integer.

A

A, B, D.
The compare() method returns a positive integer when the arrays are different and s1 is larger. This is the case for option A since the element at index 1 comes first alphabetically. It is not the case for option C because the s4 is longer or option E because the arrays are the same. The mismatch() method returns a positive integer when the arrays are different in a position index 1 or greater. This is the case for option B since the difference is at index 1. It is not the case for option D because the s3 is shorter than the s4 or option F because there is no difference.