Consider the following Java code snippet:class Animal { void makeSound() { System.out.println("Generic animal sound"); } }class Dog extends Animal { void makeSound() { System.out.println("Woof"); } }class Cat extends Animal { void makeSound() { System.out.println("Meow"); } }Animal myAnimal = new Dog();myAnimal.makeSound();What will be the output of this code?
"Woof"
✓
"Generic animal sound"
A compile-time error
"Meow"
Correct Answer
"Woof"
This demonstrates runtime polymorphism. Although myAnimal is declared as type Animal, it refers to an object of type Dog. When makeSound() is called, the JVM invokes the overridden method in the actual object's class, which is Dog. The option "Meow" is incorrect because the object is a Dog, not a Cat. "Generic animal sound" would be printed only if the object were an Animal directly or if Dog did not override the method. A "compile-time error" would not occur because the method signature matches and Dog correctly extends Animal.
Question 2
A Java application frequently adds elements to the middle of a list and removes elements from the middle of the list. Which collection implementation is generally more efficient for these operations?
HashMap
ArrayList
LinkedList
✓
HashSet
Correct Answer
LinkedList
LinkedList is generally more efficient for insertions and deletions in the middle of the list because it only requires updating a few pointers. ArrayList requires shifting all subsequent elements, which can be computationally expensive for large lists. HashSet and HashMap are not list implementations and are primarily designed for fast lookups based on hash codes or keys, respectively, not for ordered insertion/deletion in the middle of a sequence.
Question 3
Which statement best describes the difference between checked and unchecked exceptions in Java?
Checked exceptions can be caught at runtime, but unchecked exceptions cannot be caught.
Checked exceptions extend RuntimeException, while unchecked exceptions extend Exception.
Checked exceptions must be declared in a method's throws clause or handled, while unchecked exceptions do not.
✓
Correct Answer
Checked exceptions must be declared in a method's throws clause or handled, while unchecked exceptions do not.
Checked exceptions are those that the compiler forces you to handle (either with a try-catch block or by declaring them in the method's throws clause). Unchecked exceptions, which are typically subclasses of RuntimeException or Error, do not require this explicit handling. The statement that "Unchecked exceptions always indicate programmer errors" is largely true but not the defining difference, and checked exceptions can also indicate programmer errors. The inheritance hierarchy is reversed in "Checked exceptions extend RuntimeException, while unchecked exceptions extend Exception". Both types of exceptions "can be caught at runtime", making that statement incorrect for unchecked exceptions.
Question 4
Given a method signature public void processList(List<? extends Number> list), which of the following lists can be passed to this method without a compile-time error?
List<String>
List<Comparable>
List<Integer>
✓
List<Object>
Correct Answer
List<Integer>
The <? extends Number> wildcard means the list can hold any type that is a subclass of Number, including Number itself. Integer is a subclass of Number, so List<Integer> is a valid argument. List<Object> is too broad because Object is a superclass of Number, not a subclass. List<String> is incorrect because String does not extend Number. List<Comparable> is also incorrect as Comparable is an interface and not necessarily a subclass of Number.
Question 5
A shared resource in a multi-threaded Java application needs to be accessed by multiple threads, but only one thread should modify it at any given time to prevent data corruption. Which mechanism is most appropriate for ensuring this?
Declaring the shared resource as volatile.
Making the shared resource immutable.
Using a ThreadLocal variable for the resource.
Using the synchronized keyword on the method or block accessing the resource.
✓
Correct Answer
Using the synchronized keyword on the method or block accessing the resource.
The synchronized keyword ensures that only one thread can execute a critical section of code at a time, providing mutual exclusion and preventing data corruption in shared mutable resources. Declaring a resource as "volatile" ensures visibility of changes across threads but does not provide atomicity or mutual exclusion for compound operations. Using a "ThreadLocal variable" creates a separate copy of the variable for each thread, effectively making it not shared. Making the "shared resource immutable" is a good strategy to avoid concurrency issues, but the question implies modification is necessary ("only one thread should modify it"), so synchronization is needed if mutation occurs.
Question 6
Which statement accurately describes a key characteristic of Java interfaces?
A class can implement at most one interface.
Interfaces can contain concrete methods with implementation details since Java 8.
✓
All fields in an interface must be declared as private.
Interfaces can have constructors.
Correct Answer
Interfaces can contain concrete methods with implementation details since Java 8.
Since Java 8, interfaces can contain default and static methods, which have concrete implementations. Before Java 8, interfaces could only declare abstract methods. Interfaces "can have constructors" is false; interfaces cannot be instantiated directly and thus have no constructors. A class "can implement at most one interface" is false; a class can implement multiple interfaces. "All fields in an interface must be declared as private" is false; all fields in an interface are implicitly public static final.
Question 7
You need to store key-value pairs where the order of insertion must be preserved when iterating through the entries. Which Map implementation should you use?
LinkedHashMap
✓
HashMap
ConcurrentHashMap
TreeMap
Correct Answer
LinkedHashMap
LinkedHashMap preserves the insertion order of elements, or the order of access if configured for access order. HashMap does not guarantee any order. TreeMap stores elements in natural order of keys or by a specified Comparator, not insertion order. ConcurrentHashMap is designed for high-performance concurrent access and does not guarantee insertion order.
Question 8
What is the primary benefit of using a try-with-resources statement in Java?
It guarantees that a finally block will always execute, even if an exception occurs.
It automatically closes resources that implement the AutoCloseable interface.
✓
It allows catching multiple types of exceptions in a single catch block.
It prevents checked exceptions from needing to be declared or caught.
Correct Answer
It automatically closes resources that implement the AutoCloseable interface.
The try-with-resources statement ensures that any resource declared within its parentheses, which implements the AutoCloseable interface, will be automatically closed when the try block exits, whether normally or due to an exception. While try-with-resources often includes a catch block, its primary benefit is not "catching multiple types of exceptions in a single catch block" (that's multi-catch). The "finally block will always execute" is a general characteristic of finally, not specific to try-with-resources. It "prevents checked exceptions" is incorrect; it handles resource closing, not exception declaration requirements.
Question 9
Due to type erasure in Java generics, what happens to type parameters like <T> at runtime?
They cause a ClassCastException if not handled correctly.
They are preserved for reflection purposes.
They are replaced with their upper bound (or Object if unbounded).
✓
They are converted into primitive types.
Correct Answer
They are replaced with their upper bound (or Object if unbounded).
At runtime, Java's type erasure replaces generic type parameters with their upper bound or with Object if no explicit bound is specified. This means that at runtime, List<String> and List<Integer> become just List. Type parameters are "preserved for reflection purposes" only for certain contexts, but not generally for method signatures or field types in bytecode. They are "converted into primitive types" is incorrect; generics work with reference types. Type erasure itself does not directly "cause a ClassCastException" but rather it means the compiler inserts casts, and if those casts fail, then a ClassCastException occurs, but the erasure itself is the mechanism.
Question 10
A Java thread is currently executing its run() method. It then calls the wait() method on an object. What is the immediate state change for this thread?
RUNNABLE to BLOCKED
NEW to RUNNABLE
WAITING to TIMED_WAITING
RUNNABLE to WAITING
✓
Correct Answer
RUNNABLE to WAITING
When a thread calls wait() on an object, it releases the lock on that object and transitions from the RUNNABLE state to the WAITING state. It will remain in WAITING until another thread calls notify() or notifyAll() on the same object and the waiting thread re-acquires the lock. The transition "RUNNABLE to BLOCKED" occurs when a thread tries to acquire a lock that is already held by another thread. "WAITING to TIMED_WAITING" is incorrect; wait() without a timeout directly leads to WAITING. "NEW to RUNNABLE" is an initial state transition when start() is called.
Question 11
Encapsulation in Java primarily aims to achieve which of the following?
Bundling data and methods that operate on the data within a single unit and restricting direct access to the data.
✓
Defining a contract for behavior without specifying implementation.
Creating a hierarchy of classes through inheritance.
Allowing an object to take on many forms.
Correct Answer
Bundling data and methods that operate on the data within a single unit and restricting direct access to the data.
Encapsulation involves bundling data (attributes) and the methods that operate on that data into a single unit (a class) and controlling access to the data, typically by making fields private and providing public getter/setter methods. "Allowing an object to take on many forms" describes polymorphism. "Creating a hierarchy of classes through inheritance" describes inheritance. "Defining a contract for behavior without specifying implementation" describes abstraction, particularly through interfaces.
Question 12
You are iterating through an ArrayList using a for-each loop and decide to remove an element from the list during iteration. What is the most likely outcome?
A ConcurrentModificationException will be thrown.
✓
The loop will enter an infinite cycle.
The program will compile but fail to run.
The element will be successfully removed, and iteration continues normally.
Correct Answer
A ConcurrentModificationException will be thrown.
Modifying a collection (like removing an element) while iterating over it using an enhanced for loop (for-each) typically leads to a ConcurrentModificationException because the iterator's internal state becomes inconsistent with the underlying collection. To safely remove elements during iteration, one should use the Iterator's remove() method directly. The element "will be successfully removed" is incorrect as it will lead to an exception. The "loop will enter an infinite cycle" is not the typical behavior for this specific scenario. The program "will compile but fail to run" is correct in that it will compile, but the specific failure is a ConcurrentModificationException.
Question 13
To create a custom checked exception in Java, which superclass should your exception class extend?
RuntimeException
Error
Exception
✓
Throwable
Correct Answer
Exception
To create a custom checked exception, your class should extend the Exception class. Subclasses of Exception (excluding RuntimeException) are checked exceptions. Extending "RuntimeException" would create an unchecked exception. Extending "Error" is generally reserved for serious, unrecoverable problems and is also unchecked. Extending "Throwable" is the root of all exceptions and errors, but extending Exception is the more specific and appropriate choice for a custom checked exception.
Question 14
Consider a generic method: <T extends Comparable<T>> void sortArray(T[] array). What does the <T extends Comparable<T>> part signify?
T must be an interface that extends Comparable.
T must be a primitive type that can be compared.
T must be a class that implements the Comparable interface, allowing its instances to be compared with other instances of T.
✓
T can be any type, but its objects will be automatically cast to Comparable.
Correct Answer
T must be a class that implements the Comparable interface, allowing its instances to be compared with other instances of T.
The <T extends Comparable<T>> syntax defines a bounded type parameter. It means that the type T must implement the Comparable interface, specifically allowing comparison with other objects of type T. This ensures that objects of type T can be ordered. T "must be a primitive type" is incorrect; generics work with reference types. T "must be an interface" is incorrect; T is typically a class. Objects will "be automatically cast to Comparable" is incorrect; the type T itself must satisfy the bound.
Question 15
When a field is declared volatile in Java, what guarantees does it provide regarding visibility and ordering of operations across threads?
It prevents the garbage collector from reclaiming the field's memory prematurely.
It guarantees that reads of the volatile field will always see the most recent write by any thread, and prevents instruction reordering around volatile operations.
✓
It ensures mutual exclusion for critical sections involving the field.
It makes the field atomic for all types of operations (read, write, increment).
Correct Answer
It guarantees that reads of the volatile field will always see the most recent write by any thread, and prevents instruction reordering around volatile operations.
The volatile keyword guarantees two things: visibility (writes to a volatile variable are immediately visible to other threads) and prevents instruction reordering by the compiler and CPU around volatile reads/writes. It does not ensure "mutual exclusion" for compound operations; for that, synchronization is needed. It does not make all operations "atomic" (e.g., incrementing a volatile long is not atomic without further synchronization). It has no direct relation to "garbage collection".
Question 16
A class has multiple constructors, each with a different number or type of parameters. What is this OOP concept called?
Constructor overriding
Constructor overloading
✓
Method overriding
Method overloading
Correct Answer
Constructor overloading
Having multiple constructors with different signatures (different number or types of parameters) within the same class is known as constructor overloading. This allows objects to be initialized in various ways. "Constructor overriding" is not a valid concept in Java; constructors cannot be overridden. "Method overloading" refers to methods, not constructors, though the principle is similar. "Method overriding" refers to a subclass providing a specific implementation for a method already defined in its superclass.
Question 17
Which of the following statements about Java's Set interface is true?
A Set ensures that it contains no duplicate elements.
✓
A Set allows duplicate elements, but only if they are of different types.
A Set guarantees that elements are stored in the order they were inserted.
A Set provides indexed access to its elements.
Correct Answer
A Set ensures that it contains no duplicate elements.
A Set is a collection that cannot contain duplicate elements. This is its defining characteristic. A Set "guarantees that elements are stored in the order they were inserted" is true for LinkedHashSet, but not for all Set implementations like HashSet. A Set "allows duplicate elements" is fundamentally false. A Set "provides indexed access" is false; that is a characteristic of List.
Question 18
What is guaranteed to happen when a finally block is present in a try-catch-finally construct in Java?
The finally block will only execute if no exception was thrown.
The finally block will execute regardless of whether an exception occurred or was caught, unless the JVM exits.
✓
The finally block will execute only if an exception was caught.
The finally block will execute before any catch block.
Correct Answer
The finally block will execute regardless of whether an exception occurred or was caught, unless the JVM exits.
The finally block is guaranteed to execute regardless of whether an exception occurred in the try block, whether it was caught by a catch block, or if the try block completed normally. The only exceptions to this are if the JVM exits or if the thread executing the try/catch block is killed. It is not true that it "will only execute if no exception was thrown" or "only if an exception was caught". The "finally block will execute before any catch block" is incorrect; catch blocks execute before finally if an exception is thrown and caught.
Question 19
Using a raw type (e.g., List instead of List<String>) in Java generics can lead to what potential issue at runtime?
StackOverflowError
ClassCastException
✓
NullPointerException
OutOfMemoryError
Correct Answer
ClassCastException
Using raw types bypasses compile-time type checking. This means that elements of incorrect types can be added to the collection without a compiler warning. When these elements are later retrieved and implicitly cast (due to type erasure) to the expected type, a ClassCastException can occur at runtime. Raw types do not directly lead to "StackOverflowError", "OutOfMemoryError", or "NullPointerException" as their primary runtime issue; those are generally caused by infinite recursion, excessive memory allocation, or dereferencing a null object, respectively.
Question 20
Two threads, Thread A and Thread B, are attempting to acquire two locks, Lock X and Lock Y. Thread A acquires Lock X, and then attempts to acquire Lock Y. Simultaneously, Thread B acquires Lock Y, and then attempts to acquire Lock X. What is the most likely outcome of this scenario?
Starvation
Livelock
Race condition
Deadlock
✓
Correct Answer
Deadlock
This scenario describes a classic deadlock. Thread A holds Lock X and waits for Lock Y. Thread B holds Lock Y and waits for Lock X. Neither thread can proceed, and they are perpetually blocked. "Livelock" occurs when threads continuously change their state in response to each other without making progress. A "race condition" occurs when the outcome depends on the non-deterministic timing of multiple threads accessing shared mutable state. "Starvation" occurs when a thread is perpetually denied access to a shared resource, but other threads are making progress.
Question 21
Which statement is true regarding Java abstract classes?
An abstract class can have both abstract and concrete methods.
✓
An abstract class cannot have a constructor.
All methods in an abstract class must be declared abstract.
An abstract class can be instantiated directly.
Correct Answer
An abstract class can have both abstract and concrete methods.
An abstract class can contain a mix of abstract methods (without implementation) and concrete methods (with implementation). It serves as a base for other classes to extend. An abstract class "cannot have a constructor" is false; it can have constructors, which are called by the constructors of its subclasses. "All methods in an abstract class must be declared abstract" is false; otherwise, it would be an interface (before Java 8 default methods). An abstract class "can be instantiated directly" is false; abstract classes cannot be instantiated.
Question 22
Under ideal conditions (good hash function, low collision rate), what is the average time complexity for retrieving an element from a HashMap by its key?
O(n log n)
O(n)
O(log n)
O(1)
✓
Correct Answer
O(1)
Under ideal conditions, retrieving an element from a HashMap by its key has an average time complexity of O(1) because the hash function quickly directs the search to the correct bucket. O(log n) is typical for balanced binary search trees (like TreeMap). O(n) is typical for iterating through a list or in the worst-case scenario for a HashMap with many collisions. O(n log n) is typical for efficient sorting algorithms.