Java I/O and NIO.2 practice questions

From OCP Java SE 8 (1Z0-809) · 22 questions on this topic

Java I/O and NIO.2 practice questions from OCP Java SE 8 (1Z0-809). This pack has 22 questions tagged Java I/O and NIO.2, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Java I/O and NIO.2

  1. Question 1

    What is the output of the following program? ```java import java.io.BufferedReader; import java.io.StringReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new StringReader("one\ntwo")); System.out.println(br.readLine() + br.readLine() + br.readLine()); } } ```

    1. A. one two null

      readLine strips the line terminator and returns the bare content, so no spaces are introduced between the concatenated results.

    2. B. onetwo

      Stops after two reads, but a third readLine is called and returns null at end of stream, which is appended.

    3. C. onetwonullCorrect answer

      The first two calls return one and two (terminators stripped) and the third returns null at end of stream; concatenation yields onetwonull.

    4. D. An EOFException is thrown by the third readLine

      readLine signals end of stream by returning null, not by throwing; EOFException comes from data/object input streams, not BufferedReader.

    Explanation

    BufferedReader.readLine strips the line terminator and returns null once the end of the stream is reached, rather than throwing. Reading one, then two, then null and concatenating those three results produces onetwonull.

  2. Question 2

    What is the output of the following program? ```java import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) { Path p = Paths.get("a", "b", "..", "c", ".", "d"); Path n = p.normalize(); System.out.println(n.getNameCount() + " " + n.getFileName()); } } ```

    1. A. An exception is thrown because the path does not exist

      normalize is a purely textual operation that never touches the file system, so whether the path exists on disk is irrelevant and no exception occurs.

    2. B. 6 d

      Counts the raw, un-normalized elements (a, b, .., c, ., d) without collapsing the redundant . and .. entries.

    3. C. 4 d

      Only partially normalizes - for example dropping the . but not letting the .. cancel the preceding b.

    4. D. 3 dCorrect answer

      After normalization the .. cancels the preceding b and the . is removed, leaving a/c/d - three elements ending in d.

    Explanation

    normalize performs a purely syntactic cleanup with no disk access, so the path need not exist. Each .. removes the name element immediately before it and each . is dropped entirely, so a/b/../c/./d collapses to a/c/d, which has three elements whose last name is d.

  3. Question 3

    What is the output of the following program? ```java import java.io.ByteArrayOutputStream; import java.io.NotSerializableException; import java.io.ObjectOutputStream; public class Main { static class Plain { int v = 1; } public static void main(String[] args) throws Exception { try (ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream())) { oos.writeObject(new Plain()); System.out.println("written"); } catch (NotSerializableException e) { System.out.println("nope"); } } } ```

    1. A. nopeCorrect answer

      Correct: the object's class is not serializable, so writeObject throws at runtime and the handler prints this.

    2. B. written

      Writing a non-serializable object fails rather than succeeding.

    3. C. An empty object is silently written

      Nothing partial is written silently; the write throws instead.

    4. D. Compilation fails because Plain does not implement Serializable

      The serializability check is at runtime, so the code compiles.

    Explanation

    Serializability is checked at runtime, not compile time, so writing a non-serializable object throws NotSerializableException. The exception is caught and reported.

  4. Question 4

    What is the result of compiling the following program? ```java import java.io.BufferedReader; import java.io.FileInputStream; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileInputStream("data.txt")); System.out.println(br.readLine()); } } ```

    1. A. A FileNotFoundException is thrown

      No runtime file error arises because the code does not compile; the type mismatch is caught at compile time.

    2. B. Compilation failsCorrect answer

      BufferedReader's constructor expects a Reader (character stream), but FileInputStream is an InputStream (byte stream), so the argument type does not match and compilation fails.

    3. C. The first line of data.txt

      The program cannot run at all because it fails to compile, so it never reads any line.

    4. D. It compiles; the stream is converted automatically

      There is no automatic conversion between the byte-stream and character-stream hierarchies; a bridge such as InputStreamReader is required.

    Explanation

    BufferedReader wraps a Reader from the character-stream hierarchy, whereas FileInputStream belongs to the byte-stream (InputStream) hierarchy. The two families do not convert implicitly, so passing a FileInputStream where a Reader is expected is a compile-time type error. Bridging with InputStreamReader (or using FileReader) is required.

  5. Question 5

    Which pair of classes is designed for writing and reading entire Java object graphs to and from a stream?

    1. A. ObjectOutputStream and ObjectInputStreamCorrect answer

      Correct: these streams write and read whole object graphs, following references automatically.

    2. B. PrintStream and Scanner

      PrintStream and Scanner handle formatted text I/O, not object serialization.

    3. C. BufferedWriter and BufferedReader

      The buffered pair handles character text, not object graphs.

    4. D. DataOutputStream and DataInputStream

      The data streams handle primitive values individually, not whole object graphs.

    Explanation

    The object streams serialize entire object graphs, automatically following references. The other pairs handle primitives, character text, or formatted text rather than object graphs.

  6. Question 6

    What is the output of the following program? ```java import java.nio.file.Files; import java.nio.file.Path; public class Main { public static void main(String[] args) throws Exception { Path tmp = Files.createTempFile("qg", ".txt"); System.out.print(Files.exists(tmp) + " "); Files.delete(tmp); System.out.println(Files.exists(tmp)); } } ```

    1. A. false false

      Assumes the temp file is never actually created, but createTempFile does create a real file, so the first exists check is true.

    2. B. A NoSuchFileException is thrown by delete

      delete throws NoSuchFileException only when the target is already missing; here the file exists at delete time, so it is removed cleanly. deleteIfExists is the quiet variant for a possibly-absent file.

    3. C. true falseCorrect answer

      createTempFile creates the file so the first exists check is true, and after delete removes it the second check is false.

    4. D. true true

      Correctly sees the file created but overlooks that delete actually removes it, so the second exists check would still report true.

    Explanation

    Files.createTempFile creates an actual file on disk, so the first existence check reports true. Files.delete then removes it, so the second check reports false. delete raises NoSuchFileException only when the target is already absent, which is not the case here.

  7. Question 7

    What is the output of the following program? ```java import java.io.PrintWriter; import java.io.StringWriter; public class Main { public static void main(String[] args) { PrintWriter pw = new PrintWriter(new StringWriter()); pw.println("x"); System.out.println(pw.checkError()); } } ```

    1. A. true

      A true flag would mean a write failure occurred, but the write to the in-memory writer succeeded.

    2. B. Compilation fails because println on a PrintWriter must handle IOException

      PrintWriter's print methods do not throw IOException, so no handling is required and it compiles.

    3. C. x is printed to the console followed by false

      The text is written into the in-memory writer, not to the console.

    4. D. falseCorrect answer

      Correct: the write succeeded, so checkError reports false.

    Explanation

    PrintWriter never throws IOException from its print methods; it records failures internally and exposes them through checkError. The underlying write succeeded, so the error flag is false.

  8. Question 8

    What is the output of the following program? ```java import java.nio.file.Files; import java.nio.file.Path; public class Main { public static void main(String[] args) throws Exception { Path tmp = Files.createTempFile("qg-size", ".txt"); Files.write(tmp, "12345".getBytes()); System.out.println(Files.size(tmp)); Files.delete(tmp); } } ```

    1. A. 0

      The write stores the bytes, so the size is not zero.

    2. B. 6

      No trailing newline is added, so the size is exactly the byte count, not one more.

    3. C. 5Correct answer

      Correct: the file holds exactly the written bytes, so its size is their count.

    4. D. Compilation fails because write does not accept a byte array

      write accepts a byte array via a standard overload, so it compiles.

    Explanation

    Files.write replaces the file's content with exactly the given bytes, appending no newline. The file's size then equals the number of bytes written.

Practise all 22 Java I/O and NIO.2 questions

OCP Java SE 8 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCP Java SE 8

Other topics in this pack