Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 29
Question ID: UKOCP87305
Given code:
- import java.io.*;
- public class Test {
- public static void main(String[] args) throws IOException {
- var console = System.console();
- var name = console.readLine("What's your name? ");
- System.out.printf("You entered: %s", name);
- }
- }
Which of the following statements are correct regarding above program, if it is executed from the command line?
Choose 2 options.
- A It causes compilation failure
- B It compiles fine but can cause NullPointerException at runtime
- C It compiles fine and will never cause NullPointerException at runtime
- D It waits indefinitely for the user input after displaying the text: What's your name?
- E It waits for 1 min for the user input and then terminates
Reveal correct answers
Correct answers: B, D
Explanation
UKOCP87305:
This code compiles successfully.
Variable 'console' infers to Console type and variable 'name' infers to String type.
Code inside main method doesn't throw IOException or its subtype but main method is free to declare any exception in its throws clause.
Even though program is executed from command line but System.console() may return null, in case no console is available for the underlying OS.
In that case, console.readLine(...) will cause NullPointerException at runtime.
readLine method is a blocking method, it waits for the user action. It waits until user presses Enter key or terminates the program.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
