THE OCP EXAM TOPICS COVERED IN THIS PRACTICE TEST INCLUDE THE FOLLOWING:
Fill in the blanks: Writer is__________ that related stream classes__________ .
Which of the following methods is defined in java.io.File?
Which method in InputStream can be used in place of calling skip(1)?
Which methods are classes that implement java.io.Serializable required to implement?
Fill in the blanks: Given a valid Console instance, reader() returns a__________ , while writer() returns a __________.
Assuming the file path referenced in the following class is accessible and able to be written, what is the output of the following program?
package alarm;
import java.io.*;
public class Smoke {
public void sendAlert(File fn) {
try(BufferedWriter w = new BufferedWriter(new FileOutputStream(fn))) {
w.write("ALERT!");
w.flush();
w.write('!');
System.out.print("1");
} catch (IOException e) {
System.out.print("2");
} finally {
System.out.print("3");
}
}
public static void main(String[] testSignal) {
new Smoke().sendAlert(new File("alarm.txt"));
}
}
Which class is used to read information about a directory within the file system?
Which of the following is a high-level stream class that can only be used to wrap a low-level stream?
Assume the file prime6.txt exists and contains the first six prime numbers as bytes: 2, 3, 5, 7, 11, 13. What is the output of the following application?
package numbers;
import java.io.*;
public class PrimeReader {
public static void main(String[] real) throws Exception {
try (InputStream is = new FileInputStream("prime6.txt")) {
is.skip(1);
is.read();
is.skip(1);
is.read();
is.mark(4);
is.skip(1);
is.reset();
System.out.print(is.read());
}
}
}
Fill in the blanks: For a given file, the absolute is the path from the __________to the file, while the relative path is the path from the __________to the file.
Which statement best describes the following two methods?
public void writeSecret1() throws IOException {
final Writer w = new BufferedWriter(
new FileWriter("dont.open"));
w.write("Secret passcode");
w.close();
}
public void writeSecret2() throws IOException {
try(final Writer w = new BufferedWriter(
new FileWriter("dont.open"))) {
w.write("Secret passcode");
}
}
What is the result of compiling and executing the following program?
package vacation;
import java.io.*;
import java.util.*;
public class Itinerary {
private List<String> activities = new ArrayList<>();
private static Itinerary getItinerary(String name) {
return null;
}
public static void printItinerary() throws Exception {
Console c = new Console();
final String name = c.readLine("What is your name?");
final Itinerary stuff = getItinerary(name);
stuff.activities.forEach(s -> c.printf(s));
}
public static void main(String[] holidays) throws Exception {
printItinerary();
}
}
Given the following diagram, which two classes can be placed in the blank boxes?
Let’s say we want to write an instance of Cereal to disk, having a name value of CornLoops. What is the value of name after this object has been read using the ObjectInputStream’s readObject() method?
package breakfast;
public class Cereal {
private String name = "CocoaCookies";
private transient int sugar;
public Cereal() {
super();
this.name = "CaptainPebbles";
}
{
name = "SugarPops";
}
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
public int getSugar() { return sugar; }
public void setSugar(int sugar) {
this.sugar = sugar;
}
}
Which statement best describes the difference between a Writer and an OutputStream class?
What is the output of the following application? It is safe to assume the directories referenced in the class do not exist prior to the execution of the program and that the file system is available and able to be written.
package job;
import java.io.*;
public class Resume {
public void resetWorkingDirectory() throws Exception {
File f1 = new File("/templates/proofs");
f1.mkdirs();
File f2 = new File("/templates");
f2.mkdir(); // k1
new File(f2,"draft.doc").createNewFile();
f1.delete();
f2.delete(); // k2
}
public static void main(String... leads) {
try {
new Resume().resetWorkingDirectory();
} catch (Exception e) {
new RuntimeException(e);
}
}
}
Given the following class, three of the values ensure it runs properly on various different systems. Which value does not?
package magic;
import java.io.*;
public class Store {
private final String directory;
public Store(String directory) {
this.directory = directory;
}
public File getDatabaseFolder(String file) {
return new File(directory + __________ + file);
}
}
How many compilation errors does the following class contain?
package hero;
import java.io.*;
public class Guitar {
public void readMusic(File f) {
try (BufferedReader r = new BufferedReader(FileReader(f))) {
final String music = null;
try {
while((music = r.readLine()) != null)
System.out.println(music);
} catch (IOException e) {}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {}
}}
What is the difference between the two Console methods, format() and printf()?
Let’s say you want to write a lot of text data to a file in an efficient manner. Which two java.io stream classes are best to use?
Assume the file referenced in the StudentManager class exists and contains data. Which statement about the following class is correct?
package school;
import java.io.*;
class Student implements Serializable {}
public class StudentManager {
public static void main(String[] grades) {
try(ObjectInputStream ios = new ObjectInputStream(
new FileInputStream(new File("C://students.data")))) {
Student record;
while((record = (Student)ios.readObject()) != null) {
System.out.print(record);
}
} catch (EOFException e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Which java.io class does not have a complementary input stream?
Assuming the path /Earth does not exist within the file system, what is the output of the following program?
package center;
import java.io.*;
public class Journey {
public static void main(String[] dig) {
File file = new File("/Earth");
System.out.print(file.getParent()
+" - "
+file.getParent().getParent()); } }
Which statements about executing the following program are true?
package test;
import java.io.*;
public class Turing {
public static void main(String... robots) {
Console c = System.console();
final String response = c.readLine("Are you human?");
System.err.print(response);
}
}
Which of the following statements about the deleteTree() method is correct?
public void deleteTree(File f) {
if(!f.isDirectory())
f.delete();
else {
Stream.of(f.list())
.forEach(s -> deleteTree(s));
f.deleteDirectory();
}
}
Which of the following is not a built-in stream in Java?
Assuming the file path referenced in the following class is accessible and able to be written, what is the output of the following program?
package store;
import java.io.*;
public class Furniture {
public final static void main(String... inventory) throws Exception {
Writer w = new FileWriter("couch.txt");
try (BufferedWriter bw = new BufferedWriter(w)) {
bw.write("Blue coach on Sale!");
} finally {
w.flush();
w.close();
}
System.out.print("Done!");
}
}
Given an instance of Console c, which of the following method calls is not a way to read input from the user?
The copyPidgin() method is used to copy the contents of one file to another. Which statement about the implementation is correct?
package birds;
import java.io.*;
public class Pidgin {
public void copyPidgin(File s, File t) throws Exception {
try(InputStream is = new FileInputStream(s);
OutputStream os = new FileOutputStream(t)) {
byte[] data = new byte[123];
int chirps;
while((chirps = is.read(data))>0) {
os.write(data);
}}
}}
Using what you know about java.io stream class names, what would a nonexistent class named BufferedFileReader most likely be used for?
What is the output of the following application?
package factory;
import java.io.*;
public class WidgetProcessor {
public int getWidgetNumber(byte[] data) throws Exception {
try (InputStream is = new ByteArrayInputStream(data)) {
is.read(new byte[2]);
if(!is.markSupported()) return -1;
is.mark(5);
is.read();is.read();
is.skip(3);
is.reset();
return is.read();
}
}
public static void main(String... sprockets) throws Exception {
final WidgetProcessor p = new WidgetProcessor();
System.out.print(p.getWidgetNumber(new byte[] {1,2,3,4,5,6,7}));
}
}
Assuming the working directory is accessible, empty, and able to be written, how many file system objects does the following class create?
1: package kitchen;
2: import java.io.*;
3: public class Bakers {
4: public static void main(String... tooMany) throws IOException {
5: File cake = new File("cake.txt");
6: Writer pie = new FileWriter("pie.txt");
7: pie.flush();
8: new File("fudge.txt").mkdirs();
9: } }
Let’s say you wanted to read data from a file stored on disk that consists of String, long, and Object values? Given that the file is quite large, you intend to use three classes to achieve this result. Which of the following is not one of the three classes you should use?
Which statement best describes the following two methods?
public String getNameQuick() throws IOException {
final BufferedReader r = new BufferedReader(
new FileReader("saved.name"));
final String name = r.readLine();
r.flush();
return name;
}
public String getNameSafely() throws IOException {
try(final BufferedReader r = new BufferedReader(
new FileReader("saved.name"))) {
final String name = r.readLine();
r.flush();
return name;
}}
What is the output of the following application? Assume the System.console() is available and the user enters badxbad and presses Enter.
package hardway;
import java.io.*;
public class InconvenientImplementation {
public static void main(String... dontDoThis) throws Exception {
Console c = System.console();
if(c != null) {
c.writer().write('P');
c.writer().write('a');
c.writer().write('s');
c.writer().write('s');
c.writer().flush(); // t1
int i;
StringBuilder sb = new StringBuilder();
while((i = c.reader().read()) != 'x') { // t2
sb.append((char)i);
}
c.writer().format("Result: %s",sb.toString());
}
}
}
Why does Console readPassword() return a char array rather than a String?
Which statement about the following program is true?
package mystical;
import java.io.*;
public class Unicorn {
public void findUnicorns() {
try(InputStream o = new ObjectInputStream(readBook())) {
while(o.read() != -1) {
System.out.println(o.read());
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private InputStream readBook() throws IOException {
return new BufferedInputStream(new FileReader("magic.book"));
}
public static void main(String... horn) {
new Unicorn().findUnicorns();
}
}
Choose the class that is least likely to be marked Serializable.
What is the output of the following application?
package cell;
import java.io.*;
public class TextMessage {
public String receiveText() throws Exception {
try (Reader r = new FileReader("messages.txt")) {
StringBuilder s = new StringBuilder();
int c;
while((c = r.read()) != -1) {
s.append((char)c);
if(r.markSupported()) {
r.mark(100);
r.skip(10);
r.reset();
}
}
return s.toString();
}
}
public void sendText(String message) throws Exception {
try (Writer w = new FileWriter("messages.txt")) {
for(int i=0; i<message.length(); i++) {
w.write(message.charAt(i));
w.skip(1);
}
}
}
public static void main(String[] minutes) throws Exception {
final TextMessage m = new TextMessage();
m.sendText("You up?");
System.out.println(m.receiveText());
} }
What is the output of the following program? Assume the file paths referenced in the class exist and are able to be written to and read from.
package heart;
import java.io.*;
public class Valve implements Serializable {
private int chambers = -1;
private transient Double size = null;
private static String color;
public Valve() {
this.chambers = 3;
color = "BLUE";
}
public static void main(String[] love) throws Throwable {
try (ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("scan.txt"))) {
final Valve v = new Valve();
v.chambers = 2;
v.size = 10.0;
v.color = "RED";
o.writeObject(v);
}
new Valve();
try (ObjectInputStream o = new ObjectInputStream(
new FileInputStream("scan.txt"))) {
Valve v = (Valve)o.readObject();
System.out.print(v.chambers+","+v.size+","+v.color);
}
}
{ chambers = 4; }
}