Programmer I Chapter 4: Making decisions Flashcards
what data types are permitted as targets for switch?
- int, short, byte, char + their wrapper classes
- enums
- String
- a var variable if its actual type is one of the above
boolean, long, float, and double are excluded from switch statements, as are their associated Boolean, Long,Float, and Double classes
what will this print?
int dayOfWeek = 5; switch(dayOfWeek) { default: System.out.println("Weekday"); break; case 0: System.out.println("Sunday"); break; case 6: System.out.println("Saturday"); break; }
Weekday
what will this print?
var dayOfWeek = 5; switch(dayOfWeek) { case 0: System.out.println("Sunday"); default: System.out.println("Weekday"); case 6: System.out.println("Saturday"); break; }
Weekday
Saturday
what will this print?
var dayOfWeek = 6; switch(dayOfWeek) { case 0: System.out.println("Sunday"); default: System.out.println("Weekday"); case 6: System.out.println("Saturday"); break; }
Saturday
what case statements compile?
private int getSortOrder(String firstName, final String lastName){ String middleName = "Patricia"; final String suffix = "JR"; int id = 0; switch(firstName) { case "Test": // 1 return 52; case middleName: // 2 id = 5; break; case suffix: // 3 id = 0; break; case lastName: // 4 id = 8; break; case 5: // 5 id = 7; break; case 'J': // 6 id = 10; break; case java.time.DayOfWeek.SUNDAY: // 7 id=15; break; } return id; }
1, 3
what case statements compile?
short size = 4; final int aa = 15; final int bb = 1_000_000; switch(size) { case aa: // 1 case 1+2 : // 2 case bb: // 3 }
1, 2
As you may recall from our discussion of numeric promotion and casting in Chapter 3, the compiler can easily cast small from int to short at compile-time because the value 15 is small enough to fit inside a short. This would not be permitted if small was not a compile-time constant. Likewise, it can convert the expression 1+2 from int to short at compile-time. On the other hand, 1_000_000 is too large to fit inside of short without an explicit cast, so the last case statement does not compile.
what will this print?
int x = 0;
for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) { System.out.print(y + “ “); }
System.out.print(x + “ “);
0 1 2 3 4 5
what will this print?
int x = 0;
for(int x = 4; x < 5; x++) {
System.out.print(x + “ “);
}
it does not compilebecause of the initialization block
what will this print?
int x = 0;
for(long y = 0, int z = 4; x < 5; x++) {
System.out.print(y + “ “);
}
wont compile
The variables in the initialization block must allbe of the same type. In the multiple terms example, y and z were bothlong, so the code compiled without issue, but in this example they havediffering types, so the code will not compile.
what will be the values of i, j, k after running the snippets? 1: for(int i=0; i<10; i++) i = 0; 2: for(int j=1; j<10; j++) j--; 3: for(int k=0; k<10; ) k++;
1 and 2 are infinite loops,
3: k = 10
all snippets compile as Java allows to modify loop variables
what will this code output?
final String[] names = new String[3];
names[0] = "Lisa"; names[1] = "Kevin"; names[2] = "Roger";
for(String name : names) {
System.out.print(name + “, “);
}
Lisa, Kevin, Roger,
what will be the value of chackDate?
int checkDate = 0; while(checkDate<10) { checkDate++; if(checkDate>100) { break; checkDate++; } }
code wont compile because checkDate++ is unreachable
Which of the following data types can be used in a switchstatement? (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, G. A switch statement supports 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. 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 Gcorrect. Options D and H are incorrect as long, float, double, andtheir associated wrapped classes Long, Float, and Double,respectively, are not supported in switch statements.
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. The code compiles and runs without issue, so options D, E, andF are incorrect. Even though the two consecutive else statementson lines 7 and 8 look a little odd, they are associated with separateif statements on lines 5 and 6, respectively. The value of humidityon line 4 is equal to -4 + 12, which is 8. The first if statementevaluates to true on line 5, so line 6 is executed and its associatedelse statement on line 8 is not. The if statement on line 6evaluates to false, causing the else statement on line 7 toactivate. The result is the code prints Just Right, making option Bthe correct answer.
What is the output of the following code snippet?
List 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. The second for-each loop contains a continue followed by aprint() statement. Because the continue is not conditional andalways included as part of the body of the for-each loop, theprint() 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.In particular, because the data type for the elements ofmyFavoriteNumbers is Integer, they can be easily unboxed to int orreferenced as Object. For this reason, the lines containing the for-each expressions each compile
Which statements about decision structures are true? (Choose allthat apply.)
A. A for-each loop can be executed on any CollectionsFramework object.
B. The body of a while loop is guaranteed to be executed at leastonce.
C. The conditional expression of a for loop is evaluated beforethe first execution of the loop body.
D. A switch statement with no matching case statement requiresa default statement.
E. The body of a do/while loop is guaranteed to be executed atleast once.
F. An if statement can have multiple corresponding elsestatements.
C, E. A for-each loop can be executed on any Collections objectthat implements java.lang.Iterable, such as List or Set, but notall Collections classes, such as Map, so option A is incorrect. Thebody of a do/while loop is executed one or more times, while the
body of a while loop is executed zero or more times, makingoption E correct and option B incorrect. The conditionalexpression of for loops is evaluated at the start of the loopexecution, meaning the for loop may execute zero or more times,making option C correct. Option D is incorrect, as a defaultstatement is not required in a switch statement. If no casestatements match and there is no default statement, then theapplication will exit the switch statement without executing anybranches. Finally, each if statement has at most one matchingelse statement, making option F incorrect. You can chainmultiple if and else statements together, but each else statementrequires a new if statement
Assuming weather is a well-formed nonempty array, which codesnippet, when inserted independently into the blank in thefollowing code, prints all of the elements of weather? (Choose allthat 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
B, D. Option A is incorrect because on the first iteration itattempts to access weather[weather.length] of the nonemptyarray, which causes an ArrayIndexOutOfBoundsException to bethrown. Option B is correct and will print the elements in order. Itis only a slight modification of a common for loop, withi
Which statements, when inserted independently into the
following blank, will cause the code to print 2 at runtime? (Chooseall 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 conditionalexpression that is executed if the sum of col + row is an evennumber, else count is incremented. Note that options E and F areequivalent to options B and D, respectively, since unlabeled
statements apply to the most inner loop. Studying the loops, thefirst time the condition is true is in the second iteration of theinner loop, when row is 1 and col is 1. Option A is incorrect,because this causes the loop to exit immediately with count onlybeing 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 theinner loop is exited. On the next iteration of the outer loop, row is2 and col is 0, so execution exits the inner loop immediately. Onthe third iteration of the outer loop, row is 3 and col is 0, so countis incremented to 2. In the next iteration of the inner loop, thesum is even, so we exit, and our program is complete, makingoptions B, C, and E each correct. Options D and F are bothincorrect, as they cause the outer loops to execute multiple times,with count having a value of 5 when done. You don’t need to tracethrough all the iterations; just stop when the value of countexceeds 2.
Given the following method, how many lines contain compilation errors? (Choose all that apply.)
private DayOfWeek getWeekDay(int day, final int thursday) { int otherDay = day; int Sunday = 0; switch(otherDay) { default: case 1: continue; case thursday: return DayOfWeek.THURSDAY; case 2: break; case Sunday: return DayOfWeek.SUNDAY; case DayOfWeek.MONDAY: return DayOfWeek.MONDAY; } return DayOfWeek.FRIDAY; }
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
E. This code contains numerous compilation errors, makingoptions A and H incorrect. All of the compilation errors arecontained within the switch statement. The default statement isfine and does not cause any issues. The first case statement doesnot compile, as continue cannot be used inside a switchstatement. The second case statement also does not compile.While the thursday variable is marked final, it is not a compile-time constant required for a switch statement, as any int valuecan be passed in at runtime. The third case statement is valid anddoes compile, as break is compatible with switch statements. Thefourth case statement does not compile. Even though Sunday iseffectively final, it is not a compile-time constant. If it wereexplicitly marked final, then this case statement would compile.Finally, the last case statement does not compile becauseDayOfWeek.MONDAY is not an int value. While switch statements dosupport enum values, each case statement must have the same datatype as the switch variable otherDay, which is int. Since exactlyfour lines do not compile, option E is the correct answer.
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. 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 forsing + squawk, 11 + 6 + 6 = 23. On the third iteration of the loop,sing > squawk evaluates to false, as 6 > 6 is false. The loop endsand the most recent value of sing, 23, is output, so the correct answer is option C
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. This example may look complicated, but the code does notcompile. Line 8 is missing the required parentheses around theboolean conditional expression. Since the code does not compileand it is not because of line 6, option G is the correct answer. Ifline 8 was corrected with parentheses, then the loop would beexecuted twice, and the output would be 11
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 parrots = new ArrayList(); 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 undefined. F. The data type of macaw is Object. G. None of the above, as the code does not compile
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 ofint[], so each element penguin has a type of int, making option Bcorrect. In the second for-each loop, ostrich has a type ofCharacter[], so emu has a data type of Character, making option Dcorrect. In the last for-each loop, parrots has a data type of List.Since no generic type is used, the default type is a List of Objectvalues, and macaw will have a data type of Object, making option Fcorrect.
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
F. The code does not compile, although not for the reasonspecified in option E. The second case statement contains invalidsyntax. Each case statement must have the keyword case—inother words, you cannot chain them with a colon (:) as shown incase ‘B’ : ‘C’ :. For this reason, option F is the correct answer.If this line were fixed to add the keyword case before ‘C’, then therest of the code would have compiled and printed great good atruntime.
Given the following array, which code snippets print the elementsin reverse order from how they are declared? (Choose all thatapply.)
char[] wolf = {‘W’, ‘e’, ‘b’, ‘b’, ‘y’};
A. int q = wolf.length; for( ; ; ) { System.out.print(wolf[--q]); if(q==0) break; }
B.
for(int m=wolf.length-1; m>=0; –m)
System.out.print(wolf[m]);
C.
for(int z=0; z=0 && j==0; x–)
System.out.print(wolf[x]);
E.
final int r = wolf.length;
for(int w = r-1; r>-1; w = r-1)
System.out.print(wolf[w]);
F.
for(int i=wolf.length; i>0; –i)
System.out.print(wolf[i]);
G. None of the above
A, B, D. To print items in the wolf array in reverse order, the codeneeds to start with wolf[wolf.length-1] and end with wolf[0].Option A accomplishes this and is the first correct answer, albeitnot using any of for loop structures, and ends when the index is 0.Option B is also correct and is one of the most common ways a
reverse loop is written. The termination condition is often m>=0 orm>-1, and both are correct. Options C and F each cause anArrayIndexOutOfBoundsException at runtime since both read fromwolf[wolf.length] first, with an index that is passed the length ofthe 0-based array wolf. The form of option C would be successfulif the value was changed to wolf[wolf.length-z-1]. Option D isalso correct, as the j is extraneous and can be ignored in thisexample. Finally, option E is incorrect and produces an infiniteloop at runtime, as w is repeatedly set to r-1, in this case 4, onevery loop iteration. Since the update statement has no effect afterthe first iteration, the condition is never met, and the loop neverterminates.