Chapter 5 Review Questions Flashcards
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.
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.
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, 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.
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, 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().
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.
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.
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.
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 ==.
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.
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.
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, 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.
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, 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.
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.
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.
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, 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.
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. 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–.
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.
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.
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, 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.
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[][];
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.
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, 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.