Switch in Java Quiz #2

Java Certification Practice Questions (For the complete list, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)

About the topic

Switch expressions evaluate to a single value. The case statements within the switch expressions provide different ways of deriving this value.
The switch expression supports the “arrow” syntax. The syntax is as follows.
case label_1, label_2, …, label_n -> expression;|throw-statement;|block When arrow operator is used, there is no implicit fall through (in the earlier switch, it was necessary to use break statements to prevent fall through.

Q1. What is the result of compiling and running this?
public class Q23_PT1_Concepts {
		public static void main(String[] args) {
			String vehicle = "Car";
			Integer wheelCount = switch (vehicle) {
				case "car" -> 4;
				case "bicycle" -> 2;
				default -> null;


A. Prints null
B. Prints 4
C. Prints 2
D. Does not compile
E. Throws NullPointerException


The String passed is “Car” and it does not match (case sensitive comparison) with any of the cases, as “Car” is not the same as “car”. Hence, the default clause is executed and wheelCount becomes null. This is then printed.

To learn more about switch expressions, refer https://docs.oracle.com/en/java/javase/17/language/switch-expressions.html

Leave a Reply

Your email address will not be published. Required fields are marked *