Java SE 8 Programmer II Exam Question Answer - Result and Explanation

Java SE 8 Programmer II Exam Question Answer

Question

Given that course.txt is accessible and contains: Course : : Java - and given the code fragment: public static void main (String[ ] args) { int i; char c; try (FileInputStream fis = new FileInputStream ("course.txt"); InputStreamReader isr = new InputStreamReader(fis);) { while (isr.ready()){//line n1 isr.skip(2); i = isr.read (); c = (char) i; System.out.print(c); } } catch (Exception e){ e.printStackTrace(); } } What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The code reads data from a file named "course.txt" and prints out some characters to the console.

Let's step through the code fragment:

java
try (FileInputStream fis = new FileInputStream("course.txt"); InputStreamReader isr = new InputStreamReader(fis);)

The code creates a try-with-resources block that opens a FileInputStream for the file named "course.txt" and an InputStreamReader to read data from the FileInputStream. The try-with-resources block ensures that the FileInputStream and InputStreamReader are properly closed when the block is exited, whether normally or by an exception.

java
while (isr.ready()) { //line n1 isr.skip(2); i = isr.read(); c = (char) i; System.out.print(c); }

The code then enters a loop that reads from the InputStreamReader until it is no longer "ready", meaning that there is no more data to be read. Inside the loop, the code calls the skip() method on the InputStreamReader to skip the first two characters. It then reads a single byte of data from the InputStreamReader using the read() method, which returns an integer representing the byte read, or -1 if the end of the stream has been reached. The code then casts the integer to a character and prints it to the console.

Assuming that the file "course.txt" contains the string "Course : : Java", the output of the program would be "urse : : ava", since the first two characters "Co" are skipped and the remaining characters are read and printed.

Therefore, the correct answer is A. ur :: va. Option B is incorrect because the program skips the first two characters, "Co", before reading and printing any data. Option C is incorrect because the program does print data to the console. Option D is incorrect because there are no compilation errors in the code fragment.