Programmer I Chapter 5: Core Java APIs Flashcards

1
Q

what will this print?

int three = 3;
String four = “4”;
System.out.println(1 + 2 + three + four);

A

64

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

what will this print?

String s1 = “1”;
String s2 = s1.concat(“2”);
s2.concat(“3”);
System.out.println(s2);

A

12

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

what will this print?

String string = “animals”;
System.out.println(string.charAt(0));
System.out.println(string.charAt(6));
System.out.println(string.charAt(7));

A

a
s
3rd line throws an exception

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

what will this print?

String string = “animals”;
System.out.println(string.indexOf(‘a’));
System.out.println(string.indexOf(“al”));
System.out.println(string.indexOf(‘a’, 4));
System.out.println(string.indexOf(“al”, 5)); // -1

A

0
4
4
-1

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

what will this print?

4: StringBuilder a = new StringBuilder(“abc”);
5: StringBuilder b = a.append(“de”);
6: b = b.append(“f”).append(“g”);
7: System.out.println(“a=” + a);
8: System.out.println(“b=” + b);

A

abcdefg

abcdefg

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

what will this print?

3: StringBuilder sb = new StringBuilder(“animals”);
4: sb.insert(7, “-“);
5: sb.insert(0, “-“);
6: sb.insert(4, “-“);
7: System.out.println(sb);

A

-ani-mals-

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

what is the value of sb?

StringBuilder sb = new StringBuilder("abcdef");
sb.delete(1, 100);
A

a

The delete() method is more flexible than some others when it comesto array indexes. If you specify a second parameter that is past the endof the StringBuilder, Java will just assume you meant the end

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

what will this print?

1: public class Tiger {
2: String name;
3: public static void main(String[] args) {
4: Tiger t1 = new Tiger();
5: Tiger t2 = new Tiger();
6: Tiger t3 = t1;
7: System.out.println(t1 == t3);
8: System.out.println(t1 == t2);
9: System.out.println(t1.equals(t2));
10: } }

A

true
false
false

3rd is false because Tiger does not implement equals()

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

what will this print?

String string = "a";
StringBuilder builder = new StringBuilder("a");
System.out.println(string == builder);
A

won’t compile.

Remember that == is checking for object reference equality. Thecompiler is smart enough to know that two references can’t possiblypoint to the same object when they are completely different types.

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

What is the string pool?

A

The string pool contains literal values and constants that appear inyour program. For example, “name” is a literal and therefore goes intothe string pool. myObject.toString() is a string but not a literal, so itdoes not go into the string pool.

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

What will this print?

String x = “Hello World”;
String y = “Hello World”;
System.out.println(x == y);

A

true

the string literal comes from the string pool

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

What will this print?

String x = “Hello World”;
String z = “ Hello World”.trim();
System.out.println(x == z);

A

false

In this example, we don’t have two of the same String literal. Althoughx and z happen to evaluate to the same string, one is computed atruntime.

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

What will this print?

String name = "Hello World";
String name2 = new String("Hello World").intern();
System.out.println(name == name2);
A

true

First we tell Java to use the string pool normally for name. Then forname2, we tell Java to create a new object using the constructor but tointern it and use the string pool anyway. Since both variables point tothe same reference in the string pool, we can use the == operator.

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

what will this print?

15: String first = “rat” + 1;
16: String second = “r” + “a” + “t” + “1”;
17: String third = “r” + “a” + “t” + new String(“1”);
18: System.out.println(first == second);
19: System.out.println(first == second.intern());
20: System.out.println(first == third);
21: System.out.println(first == third.intern());

A

true true false true

On line 15, we have a compile-time constant that automatically gets placed in the string pool as “rat1”. On line 16, we have a more complicated expression that is also a compile-time constant. Therefore, first and second share the same string pool reference. This makes line 18 and 19 print true. On line 17, we have a String constructor. This means we no longer have a compile-time constant, and third does not point to a reference in the string pool. Therefore, line 20 prints false. On line 21, the intern() call looks in the string pool. Java notices that first points to the same String and prints true.

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

what is the result of this code?

int[] ids, types;

A

two variables of type int[] are declared

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

what is the result of this code?

int ids[], types;

A

two variables are declared. ids has type int[] and types has type int.

All we did was move the brackets, but it changed the behavior. Thistime we get one variable of type int[] and one variable of type int.Java sees this line of code and thinks something like this: “Theywant two variables of type int. The first one is called ids[]. Thisone is an int[] called ids. The second one is just called types. Nobrackets, so it is a regular integer.”

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

what this array points to?

class Names {
   String names[];
}
A

names is null, b.c. instance variable is initialized with the default value and arrays are objects.

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

what this array points to?

class Names {
   String names[] = new String[2];
}
A

It is an array because it has brackets. It is an array of type String since that is the type mentioned in the declaration. It has two elements because the length is 2. Each of those two slots currently is null but has the potential to point to a String object.

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

what happens at lines ?

3: String[] strings = { “stringValue” };
4: Object[] objects = strings;
5: String[] againStrings = (String[]) objects;
6: againStrings[0] = new StringBuilder();
7: objects[0] = new StringBuilder();

A

line 6 contains a compilation error;
line 7 throws an exception at runtime

Line 3 creates an array of type String. Line 4 doesn’t require a castbecause Object is a broader type than String. On line 5, a cast isneeded because we are moving to a more specific type. Line 6 doesn’tcompile because a String[] only allows String objects andStringBuilder is not a String.

Line 7 is where this gets interesting. From the point of view of thecompiler, this is just fine. A StringBuilder object can clearly go in anObject[]. The problem is that we don’t actually have an Object[]. Wehave a String[] referred to from an Object[] variable. At runtime, thecode throws an ArrayStoreException. You don’t need to memorize thename of this exception, but you do need to know that the code willthrow an exception.

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

How does Arrays.compare(arr1, arr2) work?

  1. meaning of return value
  2. how are arrays of different langht compared
  3. how are each values compared
A

First you need to learn what the return value means. You do not need to know the exact return values, but you do need to know the following:

  • A negative number means the first array is smaller than the second.
  • A zero means the arrays are equal.
  • A positive number means the first array is larger than the second.

Now let’s look at how to compare arrays of different lengths:

  • If both arrays are the same length and have the same values in each spot in the same order, return zero.
  • If all the elements are the same but the second array has extra elements at the end, return a negative number.
  • If all the elements are the same but the first array has extra elements at the end, return a positive number.
  • If the first element that differs is smaller in the first array, return a negative number.
  • If the first element that differs is larger in the first array, return a positive number.

Finally, what does smaller mean? Here are some more rules that apply here and to compareTo():

  • null is smaller than any other value.
  • For numbers, normal numeric order applies.
  • For strings, one is smaller if it is a prefix of another.
  • For strings/characters, numbers are smaller than letters.
  • For strings/characters, uppercase is smaller than lowercase
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

what will this print?

System.out.println(Arrays.mismatch(new int[] {1}, new int[]{1}));
System.out.println(Arrays.mismatch(new String[] {“a”}, new String[] {“A”}));
System.out.println(Arrays.mismatch(new int[] {1, 2}, new int[]{1}));

A

-1 0 1

In the first example, the arrays are the same, so the result is -1. In the second example, the entries at element 0 are not equal, so the result is0. In the third example, the entries at element 0 are equal, so we keep looking. The element at index 1 is not equal. Or more specifically, one array has an element at index 1, and the other does not. Therefore, theresult is 1.

22
Q

what is the type of the list?

var list = new ArrayList<>();

A

ArrayList

The type of the var isArrayList. Since there isn’t a type specified for the generic,Java has to assume the ultimate superclass

23
Q

what will this print?

4: List birds = new ArrayList<>();
5: birds.add(“hawk”);
6: birds.add(1, “robin”);
7: birds.add(0, “blue jay”);
8: birds.add(1, “cardinal”); hawk,robin]9: System.out.println(birds);

A

[blue jay, cardinal, hawk, robin]

24
Q

what is the result of running this code?

3: List heights = new ArrayList<>();
4: heights.add(null);
5: int h = heights.get(0);

A

line 5 throws NPE

25
Q

what will this print?

List numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.remove(1);
System.out.println(numbers);
A

[1]

After adding the two values, the List contains[1, 2]. We then request the element with index 1 be removed. That’sright: index 1. Because there’s already a remove() method that takes anint parameter, Java calls that method rather than autoboxing. If youwant to remove the 1, you can write numbers.remove(new Integer(1))to force wrapper class use.

26
Q

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. Theproblem 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. Thevariable defined on line 5 would be the string “5”, and both outputstatements would use concatenation

27
Q

Which of the following are output by this code? (Choose all thatapply.)

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 istherefore a different object than s. Lines 5 checks for objectequality, which is true, and so prints one. Line 6 uses objectreference equality, which is not true since we have differentobjects. Line 7 calls intern(), which returns the value from thestring pool and is therefore the same reference as s. Line 8 alsocompares references but is true since both references point to theobject from the string pool. Finally, line 9 is a trick. The stringHello is already in the string pool, so calling intern() does notchange anything. The reference t is a different object, so the resultis still false

28
Q

Which statements about the following code snippet are correct?(Choose all that apply.)

List 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();
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

A

A, C, F. The code does compile, making option G incorrect. In thefirst for-each loop, gorillas has a type of List, so eachelement koko has a type of String, making option A correct. In thesecond for-each loop, you might think that the diamond operator<> cannot be used with var without a compilation error, but itabsolutely can. This result is monkeys having a type ofArrayList with albert having a data type of Object,making option C correct. While var might indicate an ambiguousdata type, there is no such thing as an undefined data type inJava, so option D is incorrect. In the last for-each loop, chimpanzeehas a data type of List. Since the left side does not define ageneric type, the compiler will treat this as List, and hamwill 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, suchas ham.intValue()

29
Q

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. Thatresult is passed to the final insert(), which inserts at index 4,resulting in abbaccca

30
Q

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 notcompile. Java does not allow you to compare String andStringBuilder using ==

31
Q

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 compil
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.

32
Q

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, andcharAt(3) is called on the intermediate value of 1265. The character at index 3 is 5, making option B correct. Option C issimilar, making the intermediate value 126 and returning 6.Option D results in an exception since there is no character atindex 5. Option E is incorrect. It does not compile because theparentheses for the length() method are missing. Finally, optionF’s replace results in the intermediate value 145. The character atindex 2 is 5, so option F is correct.

33
Q

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 secondtakes just the index to start with and goes to the end of the String.Remember that indexes are zero-based. The first call starts atindex 1 and ends with index 2 since it needs to stop before index3. 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

34
Q

What is the result of the following code? (Choose all that apply.)

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. Line17 returns “PURR”, but the result is ignored and not stored in s1.Line 18 returns “purr” since there is no white space present, butte 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 somethinghappens. We concatenate three new characters to s1 and nowhave a String of length 7, making option C correct. For the secondpart, a += 2 expands to a = a + 2. A String concatenated withany 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 returnstrue because the values of the two String objects are the sameusing object equality. The if statement on line 26 returns falsebecause the two String objects are not the same in memory. Onecomes directly from the string pool, and the other comes frombuilding using String operations

35
Q

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 singlecharacter String, making option A correct and option E incorrect.Calling substring() with 2 as both parameters is legal. It returnsan 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.

36
Q

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 thecharacters sequence, resulting in 0189–, and then inserts a plussign at index 2, resulting in 01+89–

37
Q

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.
F. 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 theexam. You could easily spend a minute working out the character positions for no reason at all
38
Q

Which of the following can replace line 4 to print “avaJ”? (Chooseall 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. Inoption B, substring() returns a String, which is not stored anywhere. Option C uses method chaining. First, it creates thevalue “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 youcannot delete the character after the last index. Remember thatdeleteCharAt() uses indexes that are zero-based, and length()counts starting with 1.

39
Q

Which of these array declarations is not legal? (Choose all thatapply.)

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. Althoughit is legal to leave out the size for later dimensions of amultidimensional array, the first one is required. Option Adeclares a legal 2D array. Option B declares a legal 3D array.Option D declares a legal 2D array. Remember that it is normal tosee on the exam types you might not have learned. You aren’texpected to know anything about them

40
Q

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. TheArrayList class defines a method called size(), making option Hthe other correct answer.

41
Q

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 arrays returns true.
F. Calling equals() on two ArrayList objects returns true.
G. If you call remove(0) using an empty ArrayList object, it willcompile successfully.
H. If you call remove(0) using an empty ArrayList object, it willrun successfully.

A

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

42
Q

What is the result of the following statements?

6: var list = new ArrayList();
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
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

43
Q

Which of the following pairs fill in the blanks to output 6?

3: var values = new ___________();
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
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
44
Q

What is output by the following? (Choose all that apply.)

8: List 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
A

A, F. The code compiles and runs fine. However, an array must be sorted for binarySearch() to return a meaningful result. Option Fis correct because line 14 prints a number, but the behavior isundefined. 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 bracketsaren’t in the traditional place, but they are still legal. Line 13prints the first element, which is now –1, making option A theother correct answer

45
Q

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 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
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

46
Q

What is the result of the following?

List 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
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 index2 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

47
Q

Which of the following are true statements about the following code? (Choose all that apply.)

4: List 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

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

48
Q

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
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

49
Q

Which statements are true about the following code? (Choose all that apply.)

public void run(Integer[] ints, Double[] doubles) {
List intList = Arrays.asList(ints);
List 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.

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

50
Q

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