SCJP : Flow Control
Mock questions for this chapter: at bottom of this page
Develop code that implements an if or switch statement; and identify legal argument types for these statements.
The syntax of the switch statement is extended ever-so-slightly. The type of the
Expression is now permitted to be an enum class.
(Note that java.util.Enum is not an enum class.) A new
production is added for SwitchLabel:
SwitchLabel:
case EnumConst :
EnumConst:
Identifier
The Identifier must correspond to one of UNQUALIFIED enumeration constants.
Here is a slightly more complex enum declaration for an enum type with
an explicit instance field and an accessor for this field. Each member has a different value in the
field, and the values are passed in via a constructor. In this example, the field represents the
value, in cents, of an American coin.
public enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
Coin(int value) {
this.value = value;
}
private final int value;
public int getValue() { return value; }
}
Switch statements are useful for simulating the addition of a method to an enum type from
outside the type. This example "adds" a color method to the Coin class, and prints a table
of coins, their values, and their colors.
import static java.lang.System.out;
public class CoinTest {
public static void main(String[] args) {
for (Coin c : Coin.values()) {
out.println(c + ": \t" + c.getValue() + "c \t" + color(c));
}
}
private enum CoinColor {
COPPER, NICKEL, SILVER
}
private static CoinColor color(Coin c) {
if (c == null) {
throw new NullPointerException();
}
switch (c) {
// case Coin.PENNY: {} // Compile error! Must be UNQUALIFIED !!!
case PENNY:
return CoinColor.COPPER;
case NICKEL:
return CoinColor.NICKEL;
case DIME:
return CoinColor.SILVER;
case QUARTER:
return CoinColor.SILVER;
// case 2: {} // Compile error !!!
// Type mismatch: cannot convert from int to Coin
}
throw new AssertionError("Unknown coin: " + c);
}
}
Running the program prints:
PENNY: 1c COPPER
NICKEL: 5c NICKEL
DIME: 10c SILVER
QUARTER: 25c SILVER
SCJP 1.5 SCJP 1.6 Flow Control Mock Exam Practice Questions
Questions no -1
What is the output for the below code ?
public static void main(String[] args) {
int i1=1;
switch(i1){
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
}
}
}
options
A)one two three
B)one
C)one two
D)Compile error.
Correct answer is : A
Explanations : There is no break statement in case 1 so it causes the below case statements to execute regardless of their values.
|