Switch in Java Quiz #1

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

Topic: Controlling Program Flow

Create and use loops, if/else, and switch statements

Q1. What is the result of compiling and running this?
		var size = 7;
		switch (size) {
		case 2:
			System.out.println("Small");
			break;
		case 4:
			System.out.println("Medium");
			break;
		default:
			System.out.println("Invalid");
		case 6:
			System.out.println("Large");
			break;
		}	

Choices

A. Does not compile
B. Only prints “Large”
C. Only prints “Invalid”
D. Prints “Invalid” and then “Large”
E. Prints nothing

Answer

D is correct. The type of the switch variable is allowed to be defined using var if the type can be inferred as int. Also, the default statement need not be at the end, the order of statements does not matter. As there is no case with value 7, the control jumps to the default statement, printing “Invalid”. As there is no break statement there, the flow moves to the following case statement, printing “Large”.

Reference

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Leave a Reply

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