Java OCA OCP Practice Question 2977

Question

Consider the following snippet:

int ch = 0;
try (FileReader inputFile = new FileReader(file)) {
        // #1
        System.out.print( (char)ch );
    }
}

Which one of the following statements can be replaced with statement #1 so that the contents of the file are correctly printed on the console and the program terminates.

  • a) while( (ch = inputFile.read()) != null) {
  • b) while( (ch = inputFile.read()) != -1) {
  • c) while( (ch = inputFile.read()) != 0) {
  • d) while( (ch = inputFile.read()) != EOF) {


b)

Note

the read() method returns -1 when the file reaches the end.

option a) Since ch is of type int, it cannot be compared with null.

option c) With the check != 0, the program will never terminate since inputFile.read() returns -1 when it reaches end of the file.

option d) Using the identifier EOF will result in a compiler error.




PreviousNext

Related