OCP Question 48, Explanation

Given the code fragment:

public void erase(String dirName) throws IOException {
    File[] listOfFiles = new File(dirName).listFiles();
    if ( listOfFiles != null && listOfFiles.length > 0 ) {
        for (File aFile : listOfFiles) {
            if (aFile.isDirectory()) {
          } else {
                if (aFile.getName().endsWith(".txt"))

Assume that the MyProg directory contains subdirectories that contain .txt files and is passed as an argument to the recDelete() method when it is invoked.

What is the result?

A. The method deletes all the .txt files in the MyProg directory and its subdirectories.
B. The method deletes the .txt files of the MyProg directory only.
C. The method executes and does not make any changes to the MyProg directory.
D. The method throws an IOException.


The correct answer is A.


The solution is self-evident as the erase() method gets called recursively. To test our conclusion we create MyProg dir with a couple of .txt files in it, add a subfolder that contains more .txt files, and then write a main() method with the following invocation:

new Test().erase(“./MyProg”);

This call’s arg is tailored to the scenario where MyProg is located inside the source code directory. Naturally, an absolute path to any place within the file system will work, as well.

Fine; let’s talk a little about option D. What a strange animal… To see what I mean go ahead and remove the throws clause from erase(). Well, how do you like it? No comperr! Which means that none of the File class’s methods that are being used here throws a ChE, even delete()… In fact, after Java 1.7 introduced the NIO package, delete()’s javadoc helpfully reminds us that

…the Files class (located in java.nioIS.) defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

In short, File is probably too old to be used nowadays.

Leave Comment

Your email address will not be published. Required fields are marked *