Unit 5 - Practice Quiz
1 In Java I/O, what is a "stream"?
2
Which class is commonly used to read input from the console (System.in) in Java?
3 To write raw binary data to a file, which of the following streams should be used?
4 Which class is designed for reading character files?
5 What is the primary purpose of serialization in Java?
.java file into a .class file
6 To make a class's objects eligible for serialization, which interface must the class implement?
7 What is the main benefit of using Generics in Java?
ClassCastException.
8
Which syntax is correct for declaring a generic class named Container?
class Container<T> { }
class Container { <T> }
generic class Container { }
class <T> Container { }
9
What is the purpose of the diamond operator (<>) in Java?
10
In Java generics, what does the wildcard character ? represent in a declaration like List<?>?
Object type
11
What does the generic syntax <T extends Number> mean?
T can be Number or any of its superclasses.
T can be Number or any of its subclasses.
T can be any type except Number.
12 Which of the following is a valid state in the Java thread lifecycle?
13
What method call transitions a thread from the NEW state to the RUNNABLE state?
init()
execute()
start()
run()
14 One way to create a thread in Java is by creating a class that extends which built-in class?
15
If you create a thread by implementing the Runnable interface, which method from the interface must you override?
run()
execute()
stop()
start()
16
Why is implementing the Runnable interface often preferred over extending the Thread class?
Thread class is marked as deprecated.
Runnable threads run faster than Thread subclasses.
Runnable is an older, more stable API.
17
In Java, what is the value of Thread.NORM_PRIORITY?
18 Which Java keyword is used to ensure that a method or block of code can only be accessed by one thread at a time?
19 Synchronization in Java is used to prevent which common multithreading problem?
20
Which method causes the current thread to pause execution and release the object's lock until another thread calls notify() or notifyAll()?
wait()
join()
sleep()
yield()
21
What is the primary advantage of wrapping a FileInputStream with a BufferedInputStream?
int and double directly.
22
Consider the following class. If an object of Employee is serialized and then deserialized, what will be the value of the tempPassword field in the new object?
java
class Employee implements java.io.Serializable {
public String name;
public transient String tempPassword;
private static final long serialVersionUID = 1L;
public Employee(String name, String password) {
this.name = name;
this.tempPassword = password;
}
}
null.
NotSerializableException during deserialization.
23
Given the method signature public void processElements(List<? extends Number> list), which of the following method calls is invalid?
processElements(new ArrayList<Integer>());
processElements(new ArrayList<Double>());
processElements(new ArrayList<Number>());
processElements(new ArrayList<Object>());
24
Examine this code. What is a potential issue when multiple threads call the increment() method concurrently on the same Counter instance?
java
class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
count variable will not be visible to other threads due to instruction reordering.
NullPointerException will be thrown if two threads call it at the same time.
count value due to lost updates.
25
What is the primary advantage of implementing the Runnable interface over extending the Thread class to create a thread in Java?
Runnable provides access to more thread control methods like suspend() and resume().
Runnable always have a higher default priority than those created by extending Thread.
Runnable instances can be started using the run() method directly to create a new thread.
26
In Java's inter-thread communication mechanism, why must wait() and notify() be called from within a synchronized block or method?
StackOverflowError from recursive calls.
IllegalMonitorStateException.
27
What is the output of the following Java code snippet?
java
class Box<T> {
private T item;
public void set(T item) { this.item = item; }
public T get() { return item; }
}
public class Main {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<>();
integerBox.set(10);
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
System.out.printf("%s : %d", stringBox.get(), integerBox.get());
}
}
ClassCastException is thrown at runtime.
28
A thread is currently in the RUNNABLE state. What could cause it to transition to the BLOCKED state?
run() method completes its execution.
wait() method on an object.
Thread.sleep(500).
synchronized block that is currently locked by another thread.
29
Which code snippet correctly demonstrates the modern, preferred way to ensure a FileWriter is closed automatically, even if an exception occurs?
try (FileWriter fw = new FileWriter("out.txt")) {
fw.write("data");
} catch (IOException e) {
e.printStackTrace();
}
FileWriter fw = new FileWriter("out.txt");
fw.write("data");
fw.close();
FileWriter fw = new FileWriter("out.txt");
try {
fw.write("data");
} catch (IOException e) {
fw.close();
}
FileWriter fw = new FileWriter("out.txt");
try {
fw.write("data");
} finally {
fw.close();
}
30
What is the fundamental difference between invoking t.start() versus t.run() on a Thread object t?
t.start() creates a new thread of execution and calls the run() method within it, while t.run() executes the run() method on the current calling thread.
t.start() must be called on a Thread subclass, whereas t.run() is called when using the Runnable interface.
t.run() is used to initialize the thread, and t.start() actually executes it.
start() simply calls run() internally.
31
A class implements Serializable but does not declare a private static final long serialVersionUID. What is a potential risk of this omission?
InvalidClassException if the class is modified after the object was serialized.
NotSerializableException at runtime.
32
You have a method with the signature void addNumbers(List<? super Integer> list). Which of the following lines of code would cause a compilation error if placed inside this method?
Integer myInt = list.get(0);
list.add(100);
list.add(null);
Object obj = list.get(0);
33
When is it more appropriate to use a synchronized block on a private lock object (private final Object lock = new Object();) instead of synchronizing the entire method or using this?
synchronized methods are always safer and clearer.
34
What is the most accurate description of how thread priorities, set via Thread.setPriority(), work in Java?
Thread.MAX_PRIORITY is guaranteed to execute to completion before any thread with Thread.MIN_PRIORITY begins.
35
What happens if a thread calls notify() on an object's monitor, but no other threads are in a wait() state on that same monitor?
IllegalMonitorStateException is thrown because there is no thread to notify.
notify() signal is simply discarded and has no effect.
notify() enters a WAITING state until another thread calls wait().
36
Which of the following snippets correctly creates and starts a new thread using a lambda expression to define the Runnable task?
Runnable r = () -> System.out.println("Running");
r.start();
new Runnable(() -> System.out.println("Running")).start();
new Thread(() -> System.out.println("Running")).run();
Thread t = new Thread(() -> System.out.println("Running"));
t.start();
37
Under which scenario would you choose to use a class from the Reader/Writer hierarchy over one from the InputStream/OutputStream hierarchy?
int and boolean in a platform-independent way.
38 Which of the following lines of code is a direct example of using the type inference diamond operator introduced in Java 7?
Map<String, Integer> map = new HashMap<>();
Map map = new HashMap();
Map<String, Integer> map = new HashMap<String, Integer>();
var map = new HashMap<String, Integer>();
39
Given the following generic class, which option correctly instantiates it to create a pair of a String and an Integer?
java
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
// ... getters
}
Pair<K, V> p = new Pair<String, Integer>("Age", 25);
Pair p = new Pair<String, 25>();
Pair<String, Integer> p = new Pair<>("Age", 25);
Pair<String, Integer> p = new Pair<>("Age", "25");
40
What is the primary purpose of calling the flush() method on a BufferedWriter or FileOutputStream?
41
Consider the following code snippet designed to read a text file encoded in UTF-8. Which statement best analyzes its performance and correctness implications?
java
void readFile(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
// Line A
int data;
while ((data = isr.read()) != -1) {
System.out.print((char) data);
}
isr.close();
}
FileInputStream in a BufferedInputStream would be the most effective optimization.
InputStreamReader in a BufferedReader would be the most effective optimization.
InputStreamReader.read() makes a separate system call for each character read from the file.
FileInputStream, InputStreamReader might fail to decode it correctly.
42
Examine the following class structure. A Manager object is serialized and then deserialized. What will be the value of companyName and accessLevel in the deserialized object?
java
class Employee {
String name = "Default";
public Employee() {
System.out.println("Employee Constructor");
}
}
class Manager extends Employee implements Serializable {
private static final long serialVersionUID = 1L;
static String companyName = "ABC Corp";
transient int accessLevel = 10;
public Manager() {
System.out.println("Manager Constructor");
this.name = "Manager";
this.accessLevel = 20;
}
}
// Main execution logic:
// Manager m = new Manager();
// companyName is changed to "XYZ Corp"
// m is serialized.
// companyName is changed to "FINAL Corp"
// m is deserialized into m2.
companyName will be "FINAL Corp" and accessLevel will be 20.
companyName will be "ABC Corp" and accessLevel will be 10.
companyName will be "XYZ Corp" and accessLevel will be 20.
companyName will be "FINAL Corp" and accessLevel will be 0.
43
Given the following method signature, which of the provided code snippets will compile successfully inside the process method?
java
public <T> void process(List<? super T> list1, List<? extends T> list2) {
// Method body
}
T item = list2.get(0); list1.add(item);
Object item = list1.get(0); list2.add(item);
T item = list1.get(0); list2.add(item);
Object item = list2.get(0); list1.add(item);
44
Analyze the following DoubleCheckedLocking singleton implementation. Under which condition could this implementation fail, and why?
java
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) { // Check 1
synchronized (Singleton.class) {
if (instance == null) { // Check 2
instance = new Singleton(); // Assignment
}
}
}
return instance;
}
}
instance.
instance variable is not marked final, allowing its reference to be changed after initialization.
45
Consider a producer-consumer implementation using wait() and notifyAll(). What is the primary purpose of checking the condition (e.g., while (queue.isEmpty())) in a while loop instead of an if statement before calling wait()?
notifyAll() is called before wait().
wait() without having been notified.
wait() was called.
46
A thread t is in the TIMED_WAITING state because it has called someLock.tryLock(10, TimeUnit.SECONDS). Which of the following events will NOT cause the thread t to transition out of the TIMED_WAITING state?
t.suspend().
t.interrupt().
someLock becomes available for thread t to acquire.
47
Analyze the following generic class. Why does the line marked // COMPILATION ERROR fail to compile?
java
class Node<T> {
private T data;
private static int count;
public Node(T data) {
this.data = data;
}
public static void updateCount() {
// count++; // This is fine
}
public boolean isInstance(Object obj) {
// return obj instanceof T; // COMPILATION ERROR
return false;
}
}
isInstance method should be declared as static.
obj must be cast to T before the instanceof check.
instanceof can only be used with non-generic, reifiable types.
T is a private type parameter and cannot be accessed inside a public method.
48
On a single-core CPU running a modern preemptive multitasking OS like Linux or Windows, you create three CPU-bound threads t_min, t_norm, and t_max and set their priorities to Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, and Thread.MAX_PRIORITY respectively. All three threads are started simultaneously. Which statement most accurately describes the expected execution behavior?
t_max will run to completion first, followed by t_norm, and then t_min, in a strict sequence.
t_max than t_norm, and more to t_norm than t_min, but all three will appear to run concurrently.
49
Consider the following two ways to create and start a thread. What is a key design advantage of Approach B (implementing Runnable) over Approach A (extending Thread)?
java
// Approach A
class MyThread extends Thread {
public void run() { / task / }
}
Thread t1 = new MyThread();
// Approach B
class MyTask implements Runnable {
public void run() { / task / }
}
Thread t2 = new Thread(new MyTask());
Runnable object is lighter than a Thread object.
MyTask) to be executed by different thread management services, like an ExecutorService.
50
A class Data implements Externalizable. During deserialization via ObjectInputStream.readObject(), what is the exact sequence of events that occurs to create and initialize the new Data object?
Data class to create an instance, and then calls the readExternal() method on this newly created instance.
Data object, then calls the readExternal() method on the blank object, which is responsible for populating all its fields.
Data without calling any constructor, and then calls readExternal().
Data object, and finally calls readExternal().
51
What is the primary difference in locking behavior between a java.util.concurrent.locks.ReentrantLock created with new ReentrantLock(true) and a standard synchronized block?
ReentrantLock(true) allows interruption while waiting for the lock (lockInterruptibly), while a thread waiting on a synchronized block cannot be interrupted.
ReentrantLock(true) is significantly faster under high contention than a synchronized block.
ReentrantLock(true) is reentrant, while a synchronized block is not.
ReentrantLock(true) provides a fairness policy, attempting to grant access to the longest-waiting thread, whereas synchronized blocks make no such guarantee.
52 A task requires five worker threads to perform a computation and then a single master thread to aggregate the results. All five workers must complete their work before the master can begin aggregation. Which concurrency utility is most suitable for this specific coordination problem?
Semaphore initialized with 5 permits.
CyclicBarrier initialized with a count of 6.
CountDownLatch initialized with a count of 5.
Future objects obtained from an ExecutorService.
53
Consider the following method signatures. Which statement correctly identifies a valid and an invalid use case?
java
// Method 1
<T> void copy(List<T> dest, List<T> src);
// Method 2
<T> void copy(List<? super T> dest, List<? extends T> src);
List<String> into a List<Object>, but Method 1 can also do this if T is inferred as Object.
List<Integer> into a List<Number>, but Method 1 cannot.
List<Number> into a List<Integer>, but Method 2 cannot.
54
A thread is executing a long-running computation. Another thread calls the stop() method on this thread object. Which of the following is the most severe and direct consequence of using Thread.stop()?
stop() call if it is in the middle of a synchronized block.
ThreadDeath error, which can be caught, allowing the thread to perform cleanup before terminating.
55
You need to perform a transactional file write operation: write data to a temporary file, and only if the entire write is successful, replace the original file with the temporary one. Which java.nio.file.Files method and StandardCopyOption is best suited for this task?
Files.move(tempPath, originalPath, StandardCopyOption.REPLACE_EXISTING)
Files.write(originalPath, bytes, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.SYNC)
Files.copy(tempPath, originalPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
Files.move(tempPath, originalPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
56
What is the state of a thread t immediately after new Thread(runnable) is executed but before t.start() is called, and what is the state of the thread that called t.start() immediately after the call returns?
t is in STARTING (a conceptual, not actual, state); the calling thread's state is RUNNABLE.
t is in NEW state; the calling thread's state is RUNNABLE.
t is in NEW state; the calling thread's state is WAITING.
t is in RUNNABLE state; the calling thread's state is BLOCKED.
57
Consider a deadlock scenario involving two threads, T1 and T2, and two locks, L1 and T2. T1 acquires L1 then tries to acquire L2. T2 acquires L2 then tries to acquire L1. According to the Coffman conditions for deadlock, which specific condition is most directly broken by establishing a global, fixed order for acquiring locks (e.g., always acquire L1 before L2)?
58
Given the following generic class and its usage, what can be inferred about the diamond operator (<>) and anonymous inner classes?
java
import java.util.Comparator;
class Pair<T> {
T first, second;
Pair(T f, T s) { this.first = f; this.second = s; }
}
// Usage:
Pair<String> p = new Pair<>("a", "b") {
// anonymous inner class body
};
59
What happens if you attempt to serialize an object of a class that implements Serializable, but one of its instance fields is an object of a class that does not implement Serializable?
transient field, and will be null upon deserialization.
ClassNotFoundException is thrown at compile time.
SecurityException is thrown at runtime, as this is considered an insecure operation.
java.io.NotSerializableException is thrown at runtime when the serialization is attempted.
60
A java.util.concurrent.Exchanger is used by two threads, T1 and T2. T1 calls exchanger.exchange(data1). T2 is delayed and has not yet called exchange(). What is the state of T1?
RUNNABLE, as the exchange method is non-blocking.
TERMINATED, as the operation fails without a partner thread.
BLOCKED, because it is waiting for a lock held by another thread.
WAITING or TIMED_WAITING, as it is parked by the Exchanger until the other thread arrives.