1. What is the main purpose of the switch statement in Java?
Answer:
Explanation:
The switch statement is used to select one of many code blocks to be executed based on the evaluation of an expression.
2. How is the expression in a switch statement evaluated?
Answer:
Explanation:
The expression in a switch statement is evaluated once, and its value is compared against the values of each case.
3. What is the role of the 'break' keyword in a switch statement?
Answer:
Explanation:
The 'break' keyword is used to break out of the switch block, stopping the execution of more code and case testing inside the block.
4. What does the 'default' keyword do in a switch statement?
Answer:
Explanation:
The 'default' keyword specifies some code to run if there is no case match in the switch statement.
5. How does a switch statement compare the switch expression with case values?
Answer:
Explanation:
In a switch statement, the value of the switch expression is compared using equality comparison with the values of each case.
6. What happens if the 'break' keyword is omitted in a case of a switch statement?
Answer:
Explanation:
If the 'break' keyword is omitted, the switch statement continues to execute the following cases until a break is encountered or the switch block ends.
7. Is the 'default' case mandatory in a switch statement?
Answer:
Explanation:
The 'default' case in a switch statement is not mandatory and can be omitted if all possible cases are explicitly handled.
8. What is the correct syntax for a switch statement in Java?
Answer:
Explanation:
The correct syntax for a switch statement includes the keyword 'switch', followed by the expression in parentheses, and the case labels with the code blocks.
9. In a switch statement, what type of values can the cases have?
Answer:
Explanation:
In a switch statement, each case label must be a constant expression, typically literals or final variables.
10. Which of the following is a valid case label in a switch statement for an integer variable?
Answer:
Explanation:
In a switch statement for an integer variable, the case label must be a constant expression of an integer value, such as 'case 5:.
11. Can a switch statement in Java be used with String variables?
Answer:
Explanation:
Starting from Java 8, switch statements can be used with String variables, allowing case labels to be String literals.
12. What is the output of the following Java code?
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
}
Answer:
Explanation:
The switch statement evaluates the 'day' variable, and since its value is 2, it matches the case labeled 2, printing "Tuesday".