nerdexam
Oracle

1Z0-805 · Question #24

Given the code fragment: public class TestString { public static void main(String[] args) { String str=null; switch(str) { case "": System.out.println("blank"); break; case "null"…

The correct answer is D. An exception is thrown at runtime. A java.lang.NullPointerException will be thrown at runtime at line: Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.

Java Class Design

Question

Given the code fragment:

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; } } } What is the result?

Options

  • ACompilation fails
  • BBlank
  • CNULL
  • DAn exception is thrown at runtime
  • EInvalid

How the community answered

(41 responses)
  • A
    2% (1)
  • B
    2% (1)
  • C
    5% (2)
  • D
    80% (33)
  • E
    10% (4)

Explanation

A java.lang.NullPointerException will be thrown at runtime at line: Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.

Topics

#switch on null#NullPointerException#String switch#null handling

Community Discussion

No community discussion yet for this question.

Full 1Z0-805 Practice