switch Construct QuizS2C Home « switch Construct

Fundamentals Quiz 12

The quiz below tests your knowledge of the material learnt in Fundamentals - Lesson 13 - switch Construct.

Question 1 : Can we use an enum type with a switch expression?
- We CAN use <code>enum</code> types with <code>switch</code> expression.
Question 2 : What will be output from this code snippet?

long intValue = 1;
switch (intValue) {
case 1:
System.out.print(" 1 matched");
case 2:
System.out.print(" 2 matched");
break;
default:
System.out.println(" Default as no case matches");
}
- The snippet will not compile as <code>long</code> is not a valid type for a <code>switch</code> expression.
Question 3 : We can place a switch construct within another switch construct?
- A <code>switch</code> construct CAN be placed within another <code>switch</code> construct.
Question 4 : What will be output from this code snippet?

int intValue = 3;
// A switch where no case matches.
switch (intValue) {
default:
System.out.print(" Default as no case matches");
case 1:
System.out.print(" 1 matched");
case 2:
System.out.print(" 2 matched");
}
- The <code>default</code> statement can appear anywhere. In this case it appears first and as no <code>break</code> the rest of the <code>switch</code> is processed and so the result is <code> Default as no case matches 1 matched 2 matched</code>.
Question 5 : The default statement is mandatory when using the switch construct
- The <code>default</code> statement is OPTIONAL when using the <code>switch</code> construct.
Question 6 : What will be output from this code snippet?

char charValue = 'C';
switch (charValue) {
case A:
System.out.print(" A matched");
case B:
System.out.print(" B matched");
break;
default:
System.out.print(" Default as no case matches");
}
- This will not compile as the <code>case</code> checks need to be integers or enclosed in single quotes to compare against the <code>char</code> type.
Question 7 : The default statement must be the last entry in a switch construct?
- The <code>default</code> statement can appear anywhere within a <code>switch</code> construct although its normally placed at the end.
Quiz Progress Bar Please select an answer


What's Next?

The next quiz on Java is all about the for Construct.