Q1. Which statement creates a low overhead, low-contention random number generator that is isolated to thread togenerate a random number between 1 and 100?
A. int i = ThreadLocalRandom.current().nextInt(1, 101);
B. int i = ThreadSafeRandom.current().nextInt(1, 101);
C. int i = (int) Math.random()*100+1;
D. int i = (int) Math.random(1, 101);
E. int i = new random().nextInt(100)+1;
Answer: A
Explanation:
public class ThreadLocalRandom extends Random A random number generator isolated to the current thread. Like the global Random generator used by the Mathclass, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise bemodified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrentprograms will typically encounter much less overhead and contention. Use of ThreadLocalRandom isparticularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers inparallel in thread pools. Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.
This class also provides additional commonly used bounded random generation methods. Reference:Class ThreadLocalRandom
Q2. Which two properly implement a Singleton pattern?
A. class Singleton {
private static Singleton instance;
private Singleton () {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton ();
}
return instance;
}
}
B. class Singleton {
private static Singleton instance = new Singleton();
protected Singleton () {}
public static Singleton getInstance () {
return instance;
}
}
C. class Singleton {
Singleton () {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton ();
}
public static Singleton getInstance () {
return SingletonHolder.INSTANCE;
}
}
D. enum Singleton {
INSTANCE;
}
Answer: A,D
Explanation:
A: Here the method for getting the reference to the SingleTon object is correct.
B: The constructor should be private
C: The constructor should be private
Note: Java has several design patterns Singleton Pattern being the most commonly used.
Java Singletonpattern belongs to the family of design patterns, that govern the instantiation process. This design patternproposes that at any time there can only be one instance of a singleton (object) created by the JVM.
The class's default constructor is made private, which prevents the direct instantiation of the object by others(Other Classes). A static modifier is applied to the instance method that returns the object as it then makes thismethod a class level method that can be accessed without creating an object. OPTION A == SHOW THE LAZY initialization WITHOUT DOUBLE CHECKED LOCKING TECHNIQUE ,BUT ITS CORRECT OPTION D == Serialzation and thraead-safety guaranteed and with couple of line of code enum Singletonpattern is best way to create Singleton in Java 5 world. AND THERE ARE 5 WAY TO CREATE SINGLETON CLASS IN JAVA 1>>LAZY LOADING (initialization) USING SYCHRONIZATION 2>>CLASS LOADING (initialization) USINGprivate static final Singleton instance = new Singleton(); 3>>USING ENUM 4>>USING STATIC NESTED CLASS 5>>USING STATIC BLOCK AND MAKE CONSTRUCTOR PRIVATE IN ALL 5 WAY.
Q3. Given the following code fragment:
What is the result?
A. Three
B. One
C. Compilation fails
D. The program runs, but prints no outout
Answer: B
Explanation:
add boolean add(E e) Inserts the specified element into the queue represented by this deque (in other words, at the tail of thisdeque) if it is possible to do so immediately without violating capacity restrictions, returning true uponsuccess and throwing an IllegalStateException if no space is currently available. When using acapacity-restricted deque, it is generally preferable to use offer. This method is equivalent to addLast(E). remove E remove() Retrieves and removes the head of the queue represented by this deque (in other words, the first element ofThisdeque). This method differs from poll only in that it throws an exception if this deque is empty. This method is equivalent to removeFirst(). Returns: Thehead of the queue represented by this deque Class ArrayDeque
Q4. Given: What is the result?
A. tolting cantering tolting
B. cantering cantering cantering
C. compilation fails
D. an exception is thrown at runtime
Answer: C
Explanation:
Compiler says: Cannot reduce the visibility of the inherited method from Rideable. müssen
PUBLIC sein
public String ride() { return "cantering "; }
public String ride() { return "tolting "; }
if this is given then the result would be:
A : tolting cantering tolting
Q5. Which two are true about Singletons?
A. A Singleton must implement serializable.
B. A Singleton has only the default constructor.
C. A Singleton implements a factory method.
D. A Singleton improves a class's cohesion.
E. Singletons can be designed to be thread-safe.
Answer: C,E
Q6. Given three resources bundles with these values set for menu1: (the default resource bundle in US English.)
English US Resource Bundle Menu1 = small French Resource Bundle Menu1 = petit Chinese Resource Bundle Menu1 = And given the code fragment: Locale.setDefault(new Locale("es", "ES")); // Set default to Spanish and Spain
Locale loc1 = Locale.getDefault();
ResourceBundle message = ResourceBundle.getBundle("MessageBundle", loc1);
System.out.println(message.getString("menu1"));
What is the result?
A. No message is printed
B. petit
C. small
D. A runtime error is produced
Answer: D
Explanation: Compiles fine, but runtime error when trying to access the Spanish Resource bundle (which doesnot exist): Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name messageBundle, locale es_ES
Q7. 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)
Q8. Give: What is the likely result?
A. The program produces the correct result, with similar performance to the original.
B. The program produces the correct result, with performance degraded to the equivalent of being singlethreaded.
C. The program produces an incorrect result.
D. The program goes into an infinite loop.
E. An exception is thrown at runtime.
F. The program produces the correct result, with better performance than the original.
Answer: D
Explanation:
join() does not proceed until the task's result has been computed. Here we start to wait beforedoing the computing. The code will not finish.
Q9. Given the code fragment: What is the result?
A. Null B D
B. Null B null D
C. B D
D. D
E. An exception is thrown at runtime
Answer: C
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 ...