Ch4 Making Decision Flashcards

1
Q

Which of the following data types can be used in a switch statement?

A) enum
B) int
C) Byte
D) long
E) String
F) char
G) var
H) double

A

All primitive numeric data types that can be promoted to an int + their wrapper class representatives can be used in a switch statement. Enums, Strings and var can also be used.

A, B, C, E, F, G

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

Which of the following cases are valid and which arent?

private void test(String firstName, final String lastName) {
String middleName = “Jose”;
final String suffix = “W”;

switch(firstName) {
    case "Test":
    case middleName:
        break;
    case suffix:
        break;
    case lastName:
        break;
    case 5:
        break;
    case 'J':
        break;
    case java.time.DayOfWeek.SUNDAY:
        break;
} }
A
  • “Test” compiles without issue since it’s a String literal.
  • middleName does not compile because it is not a constant value (final missing).
  • suffix compiles without issue because it is a final constant variable.
  • lastName does not compile because it is not a constant as it is passed to the function.
  • The last thee cases do not compile because they are not of type String.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which of the following cases are valid and which arent?

short size = 4;
final int small = 15;
final int big = 1_000_000;

switch (size) {
case small:
case 1+2:
case big:
}

A

Switch statements support numeric promotion that does not require an explicit cast. The compiler can easily cast the variable small from int to short at compile time because the value 15 is small enough to fit inside a short and it is a constant variable.

1+2 can also be converted to a short because it is small enough.

1_000_000 on the other hand is too large to fit inside a short without an explicit cast, so this case does not compile.

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

What is the output of the following code?

int x = 0;
for (int x = 4; x < 5; x++) {
System.out.println(x + “ “);
}

A

x has already been declared and therefore this code does not compile.

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

What is the output of the following code?

int x = 0;
for (long y = 0, int z = 4; x < 5; x++) {
System.out.println(y + “ “);
}

A

The variables in the initialization block must all be of the same type. y is a long while z is an int, which are not compatible. This code will not compile.

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

What is the output of the following code?

String instrument = “violin”;
final String CELLO = “cello”;
String viola = “viola”;
int p = -1;
switch(instrument) {
case “bass” : break;
case CELLO: p++;
default: p++;
case “VIOLIN”: p++;
case “viola”: ++p; break;
}
A. -1
B. 0
C. 1
D. 2
E. 3
F. This code does not compile.

A

D.

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