What is the result?

Given the code fragment:
<code>
public class TestString {
public static void main(String[] args) {
String str=null;
switch(str) {
case “”:
System.out.println(“blank”); break;
case “null”:
System.out.println(“NULL”); break;
default:
System.out.println(“invalid”); break;
}
}
}
</code>

What is the result?

Given the code fragment:
<code>
public class TestString {
public static void main(String[] args) {
String str=null;
switch(str) {
case “”:
System.out.println(“blank”); break;
case “null”:
System.out.println(“NULL”); break;
default:
System.out.println(“invalid”); break;
}
}
}
</code>

What is the result?

A.
Compilation fails

B.
Blank

C.
NULL

D.
An exception is thrown at runtime

E.
Invalid

Explanation:
A java.lang.NullPointerException will be thrown at runtime at line:
switch(str) {
Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.
Reference: The Java Tutorials, The switch Statement



Leave a Reply 0

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