Unit 6 - Practice Quiz
1
What is the primary advantage of using generics (e.g., ArrayList<String>) in Java Collections?
int directly.
ClassCastException.
2
Which of the following is the correct syntax to create an ArrayList that can only hold Integer objects?
ArrayList(Integer) list = new ArrayList();
ArrayList<int> list = new ArrayList<int>();
ArrayList list = new ArrayList<Integer>();
ArrayList<Integer> list = new ArrayList<>();
3
Which method is used to retrieve an element from an ArrayList at a specific index?
get(int index)
fetch(int index)
retrieve(int index)
element(int index)
4
Which statement about ArrayList is true?
5
What is the defining characteristic of a TreeSet?
null elements.
6
To enable natural sorting for a custom object in a TreeSet, which interface should the object's class implement?
Orderable
Comparator
Sortable
Comparable
7
When would you use a Comparator instead of Comparable with a TreeSet?
8
A HashMap in Java is used to store data as:
9
Which method is used to add or update an entry in a HashMap?
add(K key, V value)
set(K key, V value)
put(K key, V value)
insert(K key, V value)
10 What does 'Deque' stand for?
11
Which of the following methods can be used to add an element to the end of a Deque?
addFirst()
addLast()
peek()
push()
12 What does JDBC stand for?
13
What is the primary role of the java.sql.Connection interface in JDBC?
14 What is the function of a JDBC Driver?
15 Which class is commonly used to load a JDBC driver and establish a connection to a database?
SQLConnector
DriverLoader
ConnectionManager
DriverManager
16 In database terminology, what does the 'R' in CRUD stand for?
17 Which SQL statement corresponds to the 'Create' operation in CRUD?
UPDATE
INSERT
SELECT
CREATE TABLE
18
After executing a SELECT query in JDBC, which object is used to iterate through the returned rows?
ResultSet
RowSet
Statement
Connection
19 Which of the following is an example of a non-conventional or NoSQL database?
20 How do Java applications typically connect to a NoSQL database like Redis or MongoDB?
21
Consider the following method. Which of the following method calls will result in a compile-time error?
java
public static void processElements(List<? extends Number> list) {
// method body
}
22
What is the primary issue with the following code snippet?
java
List<String> stringList = new ArrayList<>();
List<Object> objectList = stringList; // Line 2
objectList.add(123);
String s = stringList.get(0);
ClassCastException when stringList.get(0) is called.
s will hold the string "123".
ArrayStoreException at runtime.
23
What will be the output of the following code snippet?
java
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add(1, "D");
list.remove("B");
System.out.println(list);
}
}
IndexOutOfBoundsException is thrown.
24
Which statement best describes the performance characteristics of adding an element to the beginning of a large ArrayList versus a large LinkedList?
ArrayList is faster because it uses a contiguous block of memory.
LinkedList is faster because it only requires updating a few node references.
ArrayList is faster because it avoids the overhead of node object creation.
25
Given the Employee class below, what is the result of executing the main method? The Employee class does not implement Comparable.
java
class Employee {
private int id;
public Employee(int id) { this.id = id; }
}
public class TestSet {
public static void main(String[] args) {
Set<Employee> employees = new TreeSet<>();
employees.add(new Employee(101));
employees.add(new Employee(102));
System.out.println(employees.size());
}
}
2.
ClassCastException at runtime.
Employee is not Comparable.
0.
26
What is the output of the following code?
java
import java.util.*;
class Product {
String name;
double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() { return name; }
}
public class TestSort {
public static void main(String[] args) {
Comparator<Product> priceComparator = (p1, p2) -> Double.compare(p2.price, p1.price);
Set<Product> products = new TreeSet<>(priceComparator);
products.add(new Product("Laptop", 1200.0));
products.add(new Product("Mouse", 25.0));
products.add(new Product("Keyboard", 75.0));
System.out.println(products);
}
}
ClassCastException.
27
Consider a Person class that implements Comparable by comparing ages. What happens if you add two different Person objects with the same age to a TreeSet<Person>?
java
// Assume Person class with name and age fields
// and compareTo implemented as:
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}
// In main method:
Set<Person> personSet = new TreeSet<>();
personSet.add(new Person("Alice", 30));
personSet.add(new Person("Bob", 30));
RuntimeException is thrown because of the duplicate age.
28
What will be printed to the console when the following code is executed?
java
import java.util.HashMap;
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
Integer oldValue = map.put("A", 3);
map.put(null, 4);
map.put("C", null);
System.out.println(oldValue + "," + map.size());
}
}
29
You have a custom class Student that you want to use as a key in a HashMap. If you only override the equals() method but not the hashCode() method, what is the most likely consequence?
java
// Assume Student class has id and name
// and equals() is correctly overridden based on id.
// hashCode() is NOT overridden.
Map<Student, String> grades = new HashMap<>();
Student s1 = new Student(1, "Alice");
Student s2 = new Student(1, "Alice"); // s1.equals(s2) is true
grades.put(s1, "A");
System.out.println(grades.get(s2));
RuntimeException.
null.
30
What is the output of this code snippet?
java
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "One");
map.compute(1, (k, v) -> v.concat("Plus"));
map.computeIfAbsent(4, k -> "Four");
map.computeIfPresent(2, (k, v) -> null);
System.out.println(map);
}
}
NullPointerException is thrown.
31
What is the final content of the deque and what is printed after executing the following code?
java
import java.util.ArrayDeque;
import java.util.Deque;
public class DequeTest {
public static void main(String[] args) {
Deque<Integer> deque = new ArrayDeque<>();
deque.push(10);
deque.offerLast(20);
deque.push(30);
deque.offerFirst(40);
System.out.print(deque.pollFirst() + ",");
System.out.print(deque.pop());
}
}
32
You need to implement a Last-In-First-Out (LIFO) stack data structure with a fixed capacity. If you use an ArrayDeque, which pair of methods should you use to add and remove elements to ensure that an exception is thrown if the operation cannot be completed (e.g., adding to a full stack)?
addFirst() and removeFirst()
add() and remove()
offer() and poll()
offerFirst() and pollFirst()
33 A Java application deployed on a client machine needs to connect to a corporate database. The client machine does not have any vendor-specific database libraries installed. A middle-tier application server is used to proxy database requests. Which type of JDBC driver is being described?
34 What is the primary advantage of using a Type 4 JDBC driver over a Type 2 driver for a standalone Java application that needs to be easily deployable on different operating systems?
35
What does the integer value returned by the executeUpdate() method of a PreparedStatement typically represent when executing an UPDATE or DELETE statement?
36
Examine the following JDBC code snippet intended to prevent SQL injection. Which statement is most accurate?
java
String userInput = "' OR '1'='1";
String query = "SELECT * FROM users WHERE username = '" + userInput + "' AND status = 'active'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
executeQuery method automatically sanitizes input.
PreparedStatement instead.
Statement and is safe from SQL injection.
SQLException because of the special characters in userInput.
37
Consider the following JDBC transaction management code. Assuming the DELETE statement is valid and affects 5 rows, what will be the state of the employees table after this code executes?
java
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
try {
conn.setAutoCommit(false); // Start transaction
Statement stmt = conn.createStatement();
stmt.executeUpdate("DELETE FROM employees WHERE department = 'Sales'");
conn.rollback(); // Roll back the transaction
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
employees table will be in its original state, as if the DELETE never happened.
SQLException will be thrown when commit() is called after rollback().
38
When retrieving data from a ResultSet, what is the consequence of calling rs.getString("column_name") for a column that has a SQL NULL value?
SQLException indicating no data is available.
NullPointerException.
null reference.
"".
39 Which of the following is a critical difference when establishing a JDBC connection to a NoSQL database (like Apache Cassandra) versus a traditional RDBMS (like PostgreSQL)?
PreparedStatement cannot be used with NoSQL databases due to the lack of a structured query language.
java.sql.Connection interface is completely replaced by a vendor-specific interface.
connection.setAutoCommit(false) will always fail.
40
What is the primary role of the java.sql.DriverManager class in the JDBC API?
ResultSet.
41
Consider a custom class Employee used as a key in a HashMap. The hashCode() method is correctly implemented, but the equals() method is mistakenly left as the default implementation from Object (i.e., this == obj). What is the primary consequence of this flawed implementation when two distinct Employee objects with identical content (and thus identical hash codes) are used?
put() operation will add a new entry, and the map will contain two separate entries for logically equivalent keys, potentially in the same bucket.
RuntimeException will be thrown during the second put() operation due to the violation of the hashCode-equals contract.
HashMap in the same bucket, likely in a linked list or tree node, and get() will retrieve the first one inserted.
put() operation with a logically equivalent but distinct key object will overwrite the first entry.
42
A TreeSet is created for a custom Product class. The Product class implements Comparable<Product> such that compareTo() only considers the product's price. What is the result of adding two different Product objects with the same price but different names to this TreeSet?
add() call for the second product returns false.
ClassCastException is thrown because compareTo() is inconsistent with equals().
43
You are executing a batch update using PreparedStatement.executeBatch(). The batch contains 100 SQL statements. The 50th statement fails due to a unique constraint violation. Assuming the JDBC driver supports batch update exceptions and there's no explicit transaction management (autoCommit is true), what is the state of the database and the return value of the method?
BatchUpdateException is thrown. The first 49 statements are successfully committed, and the rest are not executed.
Statement.EXECUTE_FAILED, and all other successful statements are committed.
SQLException is thrown, and the transaction is automatically rolled back, leaving the database unchanged.
BatchUpdateException is thrown, and none of the 100 statements are committed to the database.
44
Analyze the following Java code. Why does the last line fail to compile?
java
List<String> ls = new ArrayList<>();
List<? extends Object> lo = ls;
// lo.add("Hello"); // This line fails to compile
lo is immutable and cannot be modified.
String is type-safe.
? extends Object makes the list a producer (readable), but not a consumer (writable), except for null.
List<? extends Object> is equivalent to List<Object>, and a List<String> cannot be assigned to it without an explicit cast.
45 In a cloud-native microservices architecture where services are deployed in Docker containers, which JDBC driver type is almost universally preferred and why?
46
An ArrayList is created with an initial capacity of 10. You then add 10 elements. What happens internally when you attempt to add the 11th element, and what is the amortized time complexity of adding N elements one by one to an initially empty ArrayList?
ArrayList is converted to a LinkedList to accommodate the new element. The amortized time complexity is .
47
You need a data structure that can function as a LIFO stack but must also provide capacity-restriction without throwing an exception upon failure. Which Deque implementation and method should you use to add elements?
LinkedBlockingDeque and the offerFirst() method.
ArrayDeque and the addFirst() method.
LinkedList and the addFirst() method.
ArrayDeque and the push() method.
48
Consider a JDBC transaction set to TRANSACTION_SERIALIZABLE isolation level. A long-running transaction (T1) reads all employees in the 'sales' department. While T1 is still active, another transaction (T2) attempts to insert a new employee into the 'sales' department and commit. What is the most likely outcome?
SQLException because its result set has been invalidated by T2's insert.
49
What is the key difference between the state of an ArrayList after calling trimToSize() versus clear()?
trimToSize() removes all elements and sets capacity to 0; clear() only sets the size to 0 but keeps the internal array.
trimToSize() deallocates the internal array while clear() fills it with null values.
trimToSize() has no effect if capacity equals size; clear() replaces the internal array with a new empty array.
trimToSize() sets the capacity to the current size; clear() sets the size to 0 but leaves the capacity unchanged.
50 When using a JDBC driver for a key-value store like Redis, which JDBC concept is the most difficult to map meaningfully and is often implemented with significant limitations?
ResultSet).
PreparedStatement with WHERE key = ?).
DriverManager, DataSource).
51
Given the following code, what is the output?
java
class Person {
int id;
public Person(int id) { this.id = id; }
@Override public int hashCode() { return id; }
// equals() is NOT overridden
}
Set<Person> set = new HashSet<>();
set.add(new Person(1));
set.add(new Person(1));
TreeSet<Person> treeSet = new TreeSet<>(Comparator.comparingInt(p -> p.id));
treeSet.addAll(set);
System.out.println(treeSet.size());
RuntimeException is thrown.
52
In Java 8, HashMap buckets convert from a linked list to a balanced tree (specifically, a red-black tree) when the number of nodes in a bucket reaches a certain threshold. What is the primary reason for this change and under what condition does it occur?
null keys more efficiently; this occurs when a bucket containing a null key exceeds TREEIFY_THRESHOLD (default 8).
TREEIFY_THRESHOLD (default 8) is reached and map capacity is at least 64.
TREEIFY_THRESHOLD (default 8) is reached AND the map's total capacity is at least MIN_TREEIFY_CAPACITY (default 64).
TREEIFY_THRESHOLD (default 8).
53
You create a PreparedStatement from a Connection object and then execute it 1000 times with different parameters in a loop. Separately, you create a Statement object and execute 1000 different SQL queries by concatenating strings in a loop. Why is the PreparedStatement approach significantly more performant, especially in a client-server database model?
PreparedStatement uses a more optimized network protocol than Statement.
PreparedStatement is faster because it prevents SQL injection, which has a high-performance overhead.
PreparedStatement sends the query to the database only once; subsequent executions only send the new parameter values.
PreparedStatement automatically batches the requests, sending all 1000 at once.
54
Consider an ArrayDeque<Integer>. What is the fundamental difference in behavior and outcome between calling remove() on an empty deque versus calling poll() on an empty deque?
NoSuchElementException.
remove() returns null, while poll() throws a NoSuchElementException.
remove() throws a NoSuchElementException, while poll() returns null.
null.
55
Given the following two method signatures in a class, what is the outcome?
java
public void process(List<String> list) { / ... / }
public void process(List<Integer> list) { / ... / }
ClassCastException will be thrown when either method is called.
static.
56
In a modern, high-concurrency enterprise application, why is obtaining database connections via a DataSource object overwhelmingly preferred over using the traditional DriverManager.getConnection() method?
DataSource implementations typically provide connection pooling, which is crucial for performance and scalability by reusing existing connections.
DataSource allows for connecting to non-conventional databases, which DriverManager does not support.
DataSource is part of the newer JDBC 4.0 specification, while DriverManager is deprecated.
DataSource provides a standardized way to handle different JDBC driver types, whereas DriverManager requires manual driver loading.
57
What happens if you obtain a subList from an ArrayList and then add an element to the original list?
ConcurrentModificationException will be thrown immediately upon modifying the original list.
subList (e.g., get(), size(), iterator()) will result in a ConcurrentModificationException.
subList is unaffected as it is a copy of the original elements.
subList view is updated to reflect the new element if it falls within its range.
58
A HashMap is created with the default load factor (0.75) and default initial capacity (16). At what point will the map first trigger a resize operation?
59
When creating a Statement, you can specify ResultSet.TYPE_SCROLL_SENSITIVE. What does this constant primarily enable and what is its major performance trade-off?
ResultSet and makes it sensitive to changes (updates, deletes, inserts) made by other transactions after the ResultSet was created. It can be very resource-intensive for the database and driver.
ResultSet to see updates and deletes made by others but not inserts (preventing phantom reads). It has moderate performance overhead.
ResultSet to be updated, but it is not sensitive to changes made by other transactions. It has high performance.
60
A class Point has a compareTo method that is not transitive. Specifically, p1.compareTo(p2) > 0, p2.compareTo(p3) > 0, but p1.compareTo(p3) < 0. What is the likely result of adding these three points to a TreeSet?
TreeSet will be corrupted, leading to undefined behavior on subsequent operations like contains() or remove().
add method for p3 will return false as it will be considered a duplicate of p1.
TreeSet will contain all three points in a stable, predictable order.
IllegalArgumentException or ClassCastException might be thrown during one of the insertions.