Q1. Given the interface:
Public interface Idgenerator {
int getNextId();
}
Which class implements IdGenerator in a thread-safe manner, so that no threads can get a duplicate id valuecurrent access?
A. Public class generator Implements IdGenerator {
Private AtomicInteger id = new AtomicInteger (0);
return id.incrementAndget();
}}
B. Public class Generator Implements idGenerator {
private int id = 0;
return ++id; }}
C. Public class Generator Implements IdGenerator {
private volatile int Id = 0;
return ++Id;
}
D. Public class Generator Implements IdGenerator {
private int id = 0;
public int getNextId() {
synchronized (new Generator()) {
return ++id;
}}}
E. Public class Generator Implements IdGenerator {
private int id = 0;
public int getnextId() {
synchronized (id) {
return ++id;
}}}
Answer: D
Explanation:
Code that is safe to call by multiple threads simultaneously is called thread safe. If a piece of code is threadsafe, then it contains no race conditions. Race condition only occur when multiple threads update sharedresources. Therefore it is important to know what resources Java threads share when executing.
In Java you can mark a method or a block of code as synchronized. Synchronized blocks can be used to avoidrace conditions.
A, B, C : false: wrong Implementation ( missing int getNextId(); )
E: false: synchronized (mutex Object! not Simple Data Type)
Q2. Given the code fragment:
Why is there no output when otherMethod is called?
A. An exception other than IOException is thrown.
B. Standard error is not mapped to the console.
C. There is a compilation error.
D. The exception is suppressed.
Answer: C
Explanation:
C: wenn printStackTrace() ohne Referenz auf das Exception object aufgerufen
A : java.io.FileNotFoundException: wenn e.printStackTrace();
The code compiles fine
The line
FileInputStream fis = new FileInputStream(file))
will fail at runtime since file is an empty string.
Note:
public void printStackTrace()
Prints this throwable and its backtrace to the standard error stream.
Q3. Given the incomplete pseudo-code for a fork/join framework application:
And given the missing methods: Process, submit, and splitInHalf Which three insertions properly complete the pseudo-code?
A. Insert submit at line X.
B. Insert splitInHalf at line X.
C. Insert process at line X.
D. Insert process at line Y.
E. Insert splitInHalf at line Y.
F. Insert process at line Z.
G. Insert submit at line Z.
Answer: C,E,G
Explanation:
C: If data is small enough then process it. Line X
E: If data is not small enough then split it half. Line Y
G: After the data has been split (line Y) then recursively submit the splitted data (Line z).
Q4. A valid reason to declare a class as abstract is to:
A. define methods within a parent class, which may not be overridden in a child class
B. define common method signatures in a class, while forcing child classes to contain unique methodimplementations
C. prevent instance variables from being accessed
D. prevent a class from being extended
E. define a class that prevents variable state from being stored when object Instances are serialized
F. define a class with methods that cannot be concurrently called by multiple threads
Answer: B
Explanation:
Note:An abstract method in Java is something like a pure virtual function in C++ (i.e., a virtualfunction that is declared = 0). In C++, a class that contains a pure virtual function is called an abstract classand cannot be instantiated. The same is true of Java classes that contain abstract methods. Any class with an abstract method is automatically abstract itself and must be declared as such. An abstract class cannot be instantiated. A subclass of an abstract class can be instantiated only if it overrides each of the abstract methods of itssuperclass and provides an implementation (i.e., a method body) for all of them. Such a class is often called aconcrete subclass, to emphasize the fact that it is not abstract. If a subclass of an abstract class does not implement all the abstract methods it inherits, that subclass is itselfabstract.static, private, and final methods cannot be abstract, since these types of methods cannot be overridden by asubclass. Similarly, a final class cannot contain any abstract methods. A class can be declared abstract even if it does not actually have any abstract methods. Declaring such a classabstract indicates that the implementation is somehow incomplete and is meant to serve as a superclass forone or more subclasses that will complete the implementation. Such a class cannot be instantiated.
Q5. Which code fragment correctly appends "Java 7" to the end of the file /tmp/msg.txt?
A. FileWriter w = new FileWriter("/tmp/msg.txt");
append("Java 7");
close();
B. FileWriter w = new FileWriter("/tmp/msg.txt", true);
append("Java 7");
close();
C. FileWriter w = new FileWriter("/tmp/msg.txt", FileWriter.MODE_APPEND);
append("Java 7");
close();
D. FileWriter w = new FileWriter("/tmp/msg.txt", Writer.MODE_APPEND);
append("Java 7");
close();
Answer: B
Explanation:
FileWriter(File file, boolean append)
A: clears the file and append "Java7"
Constructs a FileWriter object given a File object.
If the second argument is true, then bytes will be written to the end of the file rather than
the beginning.Parameters:
file - a File object to write toappend - if true, then bytes will be written to the end of the file
rather than the beginning
Q6. Given: What is the result?
A. 1 1 1 1 1
B. 1 2 3 4 5
C. 0 1 2 3 4
D. 0 1 4 3 4
Answer: A
Explanation:
first for-loop set 0 0 0 0 0 second for-loop increments each to 1 1 1 1 1 if condition is not given
Q7. Given the code fragment:
What change should you make to apply good coding practices to this fragment?
A. Add nested try-with-resources statements for the statement and ResultSet declarations.
B. Add the statement and ResultSet declarations to the try-with-resources statement.
C. Add a finally clause after the catch clause.
D. Rethrow SQLException.
Answer: C
Explanation:
The finally block always executes when the try block exits. This ensures that the finally block is executed evenif an unexpected exception occurs. But finally is useful for more than just exception handling -- it allows theprogrammer to avoid having cleanup code accidentally bypassed by a return, continue, or break.Putting cleanup code in a finally block is always a good practice, even when no exceptions areanticipated.
Q8. Given this error message when running your application:
Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name
MessageBundle, locale
And given that the MessageBundle.properties file has been created, exists on your disk, and is properlyformatted.
What is the cause of the error message?
A. The file is not in the environment path.
B. The file is not in the classpath.
C. The file is not in the javapath.
D. You cannot use a file to store a ResourceBundle.
Answer: D
Explanation:
ResourceBundle.getBundle is using a resource name; it isn't called ResourceBundle for
nothing.
You can create a custom ClassLoader and use that to load the data.
Q9. Given the code fragment:
Which two try statements, when inserted at line ***, enable the code to successfully move the file info.txt to thedestination directory, even if a file by the same name already exists in the destination directory?
A. try (FileChannel in = new FileInputStream (source). getChannel(); FileChannel out =
new FileOutputStream
(dest).getChannel()) { in.transferTo(0, in.size(), out);
B. try ( Files.copy(Paths.get(source),Paths.get(dest));
Files.delete (Paths.get(source));
C. try ( Files.copy(Paths.get(source),
Paths.get(dest),StandardCopyOption.REPLACE_EXISTING); Files.delete
(Paths.get(source));
D. try (Files.move(Paths.get(source),Paths.get(dest));
E. try(BufferedReader br = Files.newBufferedReader(Paths.get(source),
Charset.forName("UTF- 8"));
BufferedWriter bw = Files.newBufferedWriter(Paths.get(dest), Charset.forName("UTF-8"));
String record =
"";
while ((record = br.readLine()) ! = null) {
bw.write(record);
bw.newLine();
}
Files.delete(Paths.get(source));
Answer: C,E
Explanation:
A: copies only, don’t move operation
B,C,D (no try-with-resource !) syntax change to: try { …
B: throws FileAlreadyExistsException
C: correct if syntax change to : StandardCopyOption.REPLACE_EXISTING (before
REPLACE_Existing)
D: throws FileAlreadyExistsException
E: works properly if the sourcefile has the correct format, utf-8 here (else throws
MalformedInputException)
AND syntax is corrected to:
try ( BufferedReader br = Files.newBufferedReader(Paths.get(source),
Charset.forName(“UTF-8));
BufferedWriter bw = Files.newBufferedWriter(Paths.get(dest), Charset.forName(“UTF-8));
){
String record = “”;
…..
Q10. Given the code fragment: Which code fragment inserted at line ***, enables the code to compile?
A. public void process () throws FileNotFoundException, IOException { super.process ();
while ((record = br.readLine()) !=null) {
System.out.println(record);
}}
B. public void process () throws IOException {
super.process ();
while ((record = br.readLine()) != null) {
System.out.println(record);
}}
C. public void process () throws Exception {
super.process ();
while ((record = br.readLine()) !=null) {
System.out.println(record);
}}
D. public void process (){
try {
super.process ();
while ((record = br.readLine()) !=null) {
System.out.println(record);
}
} catch (IOException | FileNotFoundException e) { }
}
E. public void process (){
try {
super.process ();
while ((record = br.readLine()) !=null) {
System.out.println(record);
}
} catch (IOException e) {}
}
Answer: E
Explanation:
A: Compilation fails: Exception IOException is not compatible with throws clause in Base.process()
B: Compilation fails: Exception IOException is not compatible with throws clause in Base.process()
C: Compilation fails: Exception Exception is not compatible with throws clause in Base.process()
D: Compilation fails: Exception FileNotFoundException has already been caught by the alternative IOException Alternatives in a multi-catch statement cannot be related to subclassing Alternative java.io.FileNotFoundException is a subclass of alternative java.io.IOException
E: compiles ...