Java OCA OCP Practice Question 1904

Question

What is the output of the following application?

Assume the System.console() is available and the user enters badxbad and presses Enter.

package mypkg; //from  w  ww  . jav  a 2 s  .  com
import java.io.*; 
public class Main { 
   public static void main(String... argv) throws Exception { 
      Console c = System.console(); 
      if(c != null) { 
         c.writer().write('P'); 
         c.writer().write('a'); 
         c.writer().write('s'); 
         c.writer().write('s'); 
         c.writer().flush();  // t1 
         int i; 
         StringBuilder sb = new StringBuilder(); 
         while((i = c.reader().read()) != 'x') {  // t2 
            sb.append((char)i); 
         } 
         c.writer().format("Result: %s",sb.toString()); 
      } 
   } 
} 
  • A. Result: bad
  • B. Line t1 does not compile or triggers an exception at runtime.
  • C. Line t2 does not compile or triggers an exception at runtime.
  • D. None of the above


A.

Note

The class compiles without issue.

Although there are built-in methods to print a String and read a line of input, the developer has chosen not to use them for most of the application.

The application first prints Pass, one character at a time.

The flush() method does not throw an exception at runtime.

In fact, it helps make sure the message is presented to the user.

Next, the user enters badxbad and presses Enter.

The stream stops reading on the x, so the value stored in the StringBuilder is bad.

This value is printed to the user, using the format() method along with Result: as a prefix.

Option A is the correct answer.




PreviousNext

Related