Chapter 3 Making Decisions Flashcards
Review Questions
1. Which of the following data types can be used in a switch expression? (Choose all that apply.)
A. enum
B. int
C. Byte
D. long
E. String
F. char
G. var
H. double
A, B, C, E, F
A, B, C, E, F, G.
- A switch expression supports only the primitives int, byte, short, and char, along with their associated wrapper classes Integer, Byte, Short, and Character, respectively, making options B, C, and F correct and ruling out options D and H.
- It also supports enum and String, making options A and E correct.
- Finally, switch supports var if the type can be resolved to a supported switch data type, making option G correct.
2. What is the output of the following code snippet? (Choose all that apply.)
3: int temperature = 4; 4: long humidity = -temperature + temperature * 3; 5: if (temperature>=4) 6: if (humidity < 6) System.out.println("Too Low"); 7: else System.out.println("Just Right"); 8: else System.out.println("Too High");
A. Too Low
B. Just Right
C. Too High
D. A NullPointerException is thrown at runtime.
E. The code will not compile because of line 7.
F. The code will not compile because of line 8.
B
B.
- The code compiles and runs without issue, so options D, E, and F are incorrect.
- Even though two consecutive else statements on lines 7 and 8 look a little odd, they are associated with separate if statements on lines 5 and 6, respectively.
- The value of humidity on line 4 is equal to -4 + 12, which is 8.
- The first if statement evaluates to true on line 5, so line 6 is executed and evaluates to false.
- This causes the else statement on line 7 to run, printing Just Right and making option B the correct answer.
3. Which of the following data types are permitted on the right side of a for-each expression? (Choose all that apply.)
A. Double[][]
B. Object
C. Map
D. List
E. String
F. char[]
G. Exception
H. Set
A, D, F, H
A, D, F, H.
- A for-each loop supports arrays, making options A and F correct.
- For Double[][], each element of the for-each loop would be a Double[].
- A for-each loop also supports classes that implement java.lang.Iterable.
- Although this includes many of the Collections Framework classes, not all of them implement java.lang.Iterable.
- For this reason, option C is incorrect, and options D and H are correct.
- Options B, E, and G are incorrect, as they do not implement java.lang.Iterable.
- Although a String is a list of ordered characters, the class does not implement the required interface for a for-each loop.
4. What is the output of calling printReptile(6)?
void printReptile(int category) { var type = switch(category) { case 1,2 -> "Snake"; case 3,4 -> "Lizard"; case 5,6 -> "Turtle"; case 7,8 -> "Alligator"; }; System.out.print(type); }
A. Snake
B. Lizard
C. Turtle
D. Alligator
E. TurtleAlligator
F. None of the above
F
F.
- The code does not compile because the switch expression requires all possible case values to be handled, making option F correct.
- If a valid default statement was added, then the code would compile and print Turtle at runtime.
- Unlike traditional switch statements, switch expressions execute exactly one branch and do not use break statements between case statements.
5. What is the output of the following code snippet?
List<Integer> myFavoriteNumbers = new ArrayList<>(); myFavoriteNumbers.add(10); myFavoriteNumbers.add(14); for (var a : myFavoriteNumbers) { System.out.print(a + ", "); break; } for (int b : myFavoriteNumbers) { continue; System.out.print(b + ", "); } for (Object c : myFavoriteNumbers) System.out.print(c + ", ");
A. It compiles and runs without issue but does not produce any output.
B. 10, 14,
C. 10, 10, 14,
D. 10, 10, 14, 10, 14,
E. Exactly one line of code does not compile.
F. Exactly two lines of code do not compile.
G. Three or more lines of code do not compile.
H. The code contains an infinite loop and does not terminate.
E
E.
- The second for-each loop contains a continue followed by a print() statement.
- Because the continue is not conditional and always included as part of the body of the for-each loop, the print() statement is not reachable. For this reason, the print() statement does not compile. As this is the only compilation error, option E is correct. The other lines of code compile without issue.
6. Which statements about decision structures are true? (Choose all that apply.)
A. A for-each loop can be executed on any Collections Framework object.
B. The body of a while loop is guaranteed to be executed at least once.
C. The conditional expression of a for loop is evaluated before the first execution of the loop body.
D. A switch expression that takes a String and assigns the result to a variable requires a default branch.
E. The body of a do/while loop is guaranteed to be executed at least once.
F. An if statement can have multiple corresponding else statements.
C, D, E
C, D, E.
- A for-each loop can be executed on any Collections object that implements java.lang.Iterable, such as List or Set, but not all Collections classes, such as Map, so option A is incorrect.
- The body of a do/while loop is executed one or more times, while the body of a while loop is executed zero or more times, making option E correct and option B incorrect.
- The conditional expression of for loops is evaluated at the start of the loop execution, meaning the for loop may execute zero or more times, making option C correct.
- A switch expression that takes a String requires a default branch if the result is assigned to a variable,making option D correct.
- Finally, each if statement has at most one matching else statement, making option F incorrect.
7. Assuming weather is a well-formed nonempty array, which code snippet, when inserted independently into the blank in the following code, prints all of the elements of weather? (Choose all that apply.)
private void print(int[] weather) { for(\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_) { System.out.println(weather[i]); } }
A. int i=weather.length; i>0; i--
B. int i=0; i<=weather.length-1; ++i
C. var w : weather
D. int i=weather.length-1; i>=0; i--
E. int i=0, int j=3; i<weather.length; ++i
F. int i=0; ++i<10 && i<weather.length;
G. None of the above
B, D
B, D.
- Option A is incorrect because on the first iteration, it attempts to access weather[weather.length] of the nonempty array, which causes an ArrayIndexOutOfBoundsException to be thrown.
- Option B is correct and will print the elements in order.
- Option C doesn’t compile as i is undefined in weather[i]. For this to work, the body of the for-each loop would have to be updated as well.
- Option D is also correct and is a common way to print the elements of an array in reverse order.
- Option E does not compile and is therefore incorrect. You can declare multiple elements in a for loop, but the data type must be listed only once, such as in for(int i=0, j=3; …).
- Finally, option F is incorrect because the first element of the array is skipped. Since the conditional expression is checked before the loop is executed the first time, the first value of i used inside the body of the loop will be 1.
8. What is the output of calling printType(11)?
31: void printType(Object o) { 32: if(o instanceof Integer bat) { 33: System.out.print("int"); 34: } else if(o instanceof Integer bat && bat < 10) { 35: System.out.print("small int"); 36: } else if(o instanceof Long bat || bat <= 20) { 37: System.out.print("long"); 38: } default { 39: System.out.print("unknown"); 40: } 41: }
A. int
B. small int
C. long
D. unknown
E. Nothing is printed.
F. The code contains one line that does not compile.
G. The code contains two lines that do not compile.
H. None of the above
F
G.
- The first two pattern matching statements compile without issue.
- The variable bat is allowed to be used again, provided it is no longer in scope.
- Line 36 does not compile, though. Due to flow scoping, if s is not a Long, then bat is not in scope in the expression bat <= 20.
- Line 38 also does not compile as default cannot be used as part of an if/else statement. For these two reasons, option G is correct.
9. Which statements, when inserted independently into the following blank, will cause the code to print 2 at runtime? (Choose all that apply.)
int count = 0; BUNNY: for(int row = 1; row <=3; row++) RABBIT: for(int col = 0; col <3 ; col++) { if((col + row) % 2 == 0) \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_; count++; } System.out.println(count);
A. break BUNNY
B. break RABBIT
C. continue BUNNY
D. continue RABBIT
E. break
F. continue
G. None of the above, as the code contains a compiler error.
B, C, E.
The code contains a nested loop and a conditional expression that is
executed if the sum of col + row is an even number; otherwise, count is
incremented. Note that options E and F are equivalent to options B and D,
respectively, since unlabeled statements apply to the most inner loop. Studying the
loops, the first time the condition is true is in the second iteration of the inner loop,
when row is 1 and col is 1. Option A is incorrect because this causes the loop to
exit immediately with count only being set to 1. Options B, C, and E follow the
same pathway. First, count is incremented to 1 on the first inner loop, and then the
inner loop is exited. On the next iteration of the outer loop, row is 2 and col is 0, so
execution exits the inner loop immediately. On the third iteration of the outer loop,
row is 3 and col is 0, so count is incremented to 2. In the next iteration of the
inner loop, the sum is even, so we exit, and our program is complete, making options
B, C, and E each correct. Options D and F are both incorrect, as they cause the inner
and outer loops to execute multiple times, with count having a value of 5 when
done. You don’t need to trace through all the iterations; just stop when the value of
count exceeds 2.
10. Given the following method, how many lines contain compilation errors? (Choose all that apply.)
10: private DayOfWeek getWeekDay(int day, final int thursday) { 11: int otherDay = day; 12: int Sunday = 0; 13: switch(otherDay) { 14: default: 15: case 1: continue; 16: case thursday: return DayOfWeek.THURSDAY; 17: case 2,10: break; 18: case Sunday: return DayOfWeek.SUNDAY; 19: case DayOfWeek.MONDAY: return DayOfWeek.MONDAY; 20: } 21: return DayOfWeek.FRIDAY; 22: }
A. None, the code compiles without issue.
B. 1
C. 2
D. 3
E. 4
F. 5
G. 6
H. The code compiles but may produce an error at runtime.
G
E.
- This code contains numerous compilation errors, making options A and H incorrect.
- Line 15 does not compile, as continue cannot be used inside a switch statement like this.
- Line 16 is not a compile-time constant since any int value can be passed as a parameter. Marking it final does not change this, so it doesn’t compile.
- Line 18 does not compile because Sunday is not marked as final. Being effectively final is insufficient.
- Finally, line 19 does not compile because DayOfWeek.MONDAY is not an int value. While switch statements do support enum values, each case statement must have the same data type as the switch variable otherDay, which is int.
- The rest of the lines do compile. Since exactly four lines do not compile, option E is the correct answer.
11. What is the output of calling printLocation(Animal.MAMMAL)?
10: class Zoo { 11: enum Animal {BIRD, FISH, MAMMAL} 12: void printLocation(Animal a) { 13: long type = switch(a) { 14: case BIRD -> 1; 15: case FISH -> 2; 16: case MAMMAL -> 3; 17: default -> 4; 18: }; 19: System.out.print(type); 20: } }
A. 3
B. 4
C. 34
D. The code does not compile because of line 13.
E. The code does not compile because of line 17.
F. None of the above
A
A.
- The code compiles and runs without issue, printing 3 at runtime and making option A correct.
- The default statement on line 17 is optional since all the enum values are accounted for and can be removed without changing the output.
12. What is the result of the following code snippet?
3: int sing = 8, squawk = 2, notes = 0; 4: while(sing > squawk) { 5: sing--; 6: squawk += 2; 7: notes += sing + squawk; 8: } 9: System.out.println(notes);
A. 11
B. 13
C. 23
D. 33
E. 50
F. The code will not compile because of line 7.
C
C.
- Prior to the first iteration, sing = 8, squawk = 2, and notes = 0.
- After the iteration of the first loop, sing is updated to 7, squawk to 4, and notes to the sum of the new values for sing + squawk, 7 + 4 = 11.
- After the iteration of the second loop, sing is updated to 6, squawk to 6, and notes to the sum of itself plus the new values for sing + squawk, 11 + 6 + 6 = 23.
- On the third iteration of the loop, sing > squawk evaluates to false, as 6 > 6 is false.
- The loop ends and the most recent value of sing, 23, is output, so the correct answer is option C.
13. What is the output of the following code snippet?
2: boolean keepGoing = true; 3: int result = 15, meters = 10; 4: do { 5: meters--; 6: if(meters==8) keepGoing = false; 7: result -= 2; 8: } while keepGoing; 9: System.out.println(result);
A. 7
B. 9
C. 10
D. 11
E. 15
F. The code will not compile because of line 6.
G. The code does not compile for a different reason.
G
G.
- This example may look complicated, but the code does not compile.
- Line 8 is missing the required parentheses around the boolean conditional expression. Since the code does not compile and it is not because of line 6, option G is the correct answer.
- If line 8 was corrected with parentheses, then the loop would be executed twice, and the output would be 11.
14. Which statements about the following code snippet are correct? (Choose all that apply.)
for(var penguin : new int[2]) System.out.println(penguin); var ostrich = new Character[3]; for(var emu : ostrich) System.out.println(emu); List<Integer> parrots = new ArrayList<Integer>(); for(var macaw : parrots) System.out.println(macaw);
A. The data type of penguin is Integer.
B. The data type of penguin is int.
C. The data type of emu is undefined.
D. The data type of emu is Character.
E. The data type of macaw is List.
F. The data type of macaw is Integer.
G. None of the above, as the code does not compile.
B, D, F
B, D, F.
- The code does compile, making option G incorrect.
- In the first for-each loop, the right side of the for-each loop has a type of int[], so each element penguin has a type of int, making option B correct.
- In the second for-each loop, ostrich has a type of Character[], so emu has a data type of Character, making option D correct.
- In the last for-each loop, parrots has a data type of List
<Integer>
. Since the generic type of Integer is used in the List, macaw will have a data type of Integer, making option F correct.
15. What is the result of the following code snippet?
final char a = 'A', e = 'E'; char grade = 'B'; switch (grade) { default: case a: case 'B': 'C': System.out.print("great "); case 'D': System.out.print("good "); break; case e: case 'F': System.out.print("not good "); }
A. great
B. great good
C. good
D. not good
E. The code does not compile because the data type of one or more case statements does not match the data type of the switch variable.
F. None of the above
B
F.
- The code does not compile, although not for the reason specified in option E.
- The second case statement contains invalid syntax.
-
Each case statement must have the keyword
case
—in other words, you cannot chain them with a colon (:). For this reason, option F is the correct answer. - This line could have been fixed to say case ‘B’, ‘C’ or by adding the case keyword before ‘C’; then the rest of the code would have compiled and printed great good at runtime.