Java OCA OCP Practice Question 2151

Question

Given the following code:

public class Main {

  public static void main(String[] args) throws FileNotFoundException {
    // (1) INSERT CODE HERE
  }
}

Which code, when inserted at (1), will print the following to the file named "output.txt":

Formatted output: 1234.04

Select the one correct answer.

(a) PrintWriter pw = new PrintWriter("output.txt");
    pw.format("Formatted output: %.2f%n", 1234.0354);
    pw.flush();//from   w  w w .  j  ava  2 s .  c o  m
    pw.close();

(b) PrintStream ps = new PrintStream("output.txt");
    ps.format("Formatted output: %.2f%n", 1234.0354);
    ps.flush();
    ps.close();

(c) Formatter fmt1 = new Formatter(new FileOutputStream("output.txt"));
    fmt1.format("Formatted output: %.2f%n", 1234.0354);
    fmt1.flush();
    fmt1.close();

(d) Formatter fmt2 = new Formatter("output.txt");
    fmt2.format("Formatted output: %.2f%n", 1234.0354);
    fmt2.flush();
    fmt2.close();

(e) All of the above


(e)

Note

All the three classes PrintStream, PrintWriter, and Formatter have the format() method that writes to the underlying output stream, which is created or provided depending on the constructor argument.




PreviousNext

Related