Java Advanced MCQs

1 min read

Advanced Java encompasses complex programming paradigms, low-level runtime mechanics, and high-performance framework design beyond standard syntax. It probes deep into Java Virtual Machine (JVM) architecture, memory management models, advanced concurrency utilities from the java.util.concurrent package, generics with type erasure, and runtime reflection mechanisms. Mastery of these advanced concepts is critical for building scalable, thread-safe, and highly optimized enterprise-grade applications.

1. Which class provides thread-local variables in Java?

a) ThreadLocal
b) ThreadVar
c) LocalThread
d) ThreadStorage
Correct Answer: a) ThreadLocal
Explanation:
ThreadLocal provides variables that are read and written independently by each thread.

2. What does the submit method of ExecutorService return?

a) void
b) Thread
c) Future
d) Runnable
Correct Answer: c) Future
Explanation:
The submit method returns a Future representing the pending results of the task.

3. Which framework is designed for tasks that can be broken down recursively?

a) ExecutorService
b) ForkJoinPool
c) ScheduledThreadPool
d) ThreadPoolExecutor
Correct Answer: b) ForkJoinPool
Explanation:
ForkJoinPool is designed for work-stealing and divide-and-conquer algorithms.

4. What happens when a thread calls await on a CyclicBarrier?

a) It terminates
b) It throws an exception
c) It blocks until all parties reach the barrier
d) It resets the barrier
Correct Answer: c) It blocks until all parties reach the barrier
Explanation:
Threads block until the specified number of parties invoke await.

5. Which synchronization aid cannot be reset once its count reaches zero?

a) CyclicBarrier
b) Phaser
c) Semaphore
d) CountDownLatch
Correct Answer: d) CountDownLatch
Explanation:
CountDownLatch is a one-shot phenomenon and cannot be reset.

6. Which lock provides an optimistic reading mode in Java 8?

a) ReentrantLock
b) ReentrantReadWriteLock
c) StampedLock
d) SynchronizedLock
Correct Answer: c) StampedLock
Explanation:
StampedLock provides an optimistic reading mode returning a stamp for validation.

7. What is the primary advantage of LongAdder over AtomicLong?

a) Uses less memory
b) Faster single-thread reads
c) Reduces contention in highly concurrent updates
d) Supports atomic multiplication
Correct Answer: c) Reduces contention in highly concurrent updates
Explanation:
LongAdder maintains an array of variables to reduce thread contention under high update rates.

8. What does the volatile keyword guarantee?

a) Atomicity
b) Visibility of updates across threads
c) Thread-safe iteration
d) Garbage collection
Correct Answer: b) Visibility of updates across threads
Explanation:
The volatile keyword ensures that changes to a variable are immediately visible to other threads.

9. How does ConcurrentHashMap achieve thread safety in Java 8?

a) Synchronizing all methods
b) Segment-level locking only
c) CAS operations and synchronizing only the bucket head
d) Copying the map on write
Correct Answer: c) CAS operations and synchronizing only the bucket head
Explanation:
Java 8 uses CAS and synchronized blocks at the node level to improve concurrency.

10. What happens if a thread modifies a CopyOnWriteArrayList during iteration?

a) ConcurrentModificationException is thrown
b) Iterator reflects changes
c) Iterator continues over a snapshot
d) Modifying thread blocks
Correct Answer: c) Iterator continues over a snapshot
Explanation:
The iterator relies on a snapshot of the array taken at the time it was created.

11. Which BlockingQueue method blocks if the queue is full?

a) add
b) offer
c) put
d) insert
Correct Answer: c) put
Explanation:
The put method blocks until space becomes available.

12. What is the role of the Exchanger class?

a) Converts object types
b) Provides a synchronization point to swap objects
c) Exchanges thread priorities
d) Swaps locks
Correct Answer: b) Provides a synchronization point to swap objects
Explanation:
Exchanger facilitates a synchronization point where two threads can safely swap data.

13. What is the difference between thenApply and thenCompose in CompletableFuture?

a) One is synchronous, the other asynchronous
b) thenApply maps a result, thenCompose chains futures
c) thenApply handles errors
d) There is no difference
Correct Answer: b) thenApply maps a result, thenCompose chains futures
Explanation:
thenApply is like map, returning a new value. thenCompose is like flatMap, preventing nested futures.

14. What does Thread.interrupt do?

a) Stops the thread immediately
b) Pauses the thread
c) Sets the interrupt flag and wakes blocking threads
d) Destroys the thread
Correct Answer: c) Sets the interrupt flag and wakes blocking threads
Explanation:
It sets the interrupted status and causes blocking methods to throw InterruptedException.

15. Which memory area is NOT part of the JVM Heap?

a) Eden Space
b) Survivor Space
c) Tenured Generation
d) Metaspace
Correct Answer: d) Metaspace
Explanation:
Metaspace replaced PermGen and is allocated in native memory, outside the JVM heap.

16. What is a TLAB in JVM memory?

a) Thread Local Allocation Buffer
b) Thread Level Array Block
c) Total Lock Allocation Block
d) Temporary Local Array Buffer
Correct Answer: a) Thread Local Allocation Buffer
Explanation:
TLABs are small memory regions assigned to individual threads for lock-free object allocation.

17. How does the G1 Garbage Collector organize the heap?

a) One young and one old generation
b) Multiple equal-sized regions
c) Single contiguous block
d) Reference counting blocks
Correct Answer: b) Multiple equal-sized regions
Explanation:
G1 divides the heap into regions and dynamically assigns them as Eden, Survivor, or Old.

18. Which GC is known for sub-millisecond pause times regardless of heap size?

a) Parallel GC
b) Serial GC
c) ZGC
d) CMS
Correct Answer: c) ZGC
Explanation:
ZGC is a scalable low-latency garbage collector designed to keep pause times extremely low.

19. What does a WeakReference allow?

a) Prevents GC entirely
b) Keeps object until OOM
c) Allows object GC if no strong references exist
d) References primitives only
Correct Answer: c) Allows object GC if no strong references exist
Explanation:
Weak references do not prevent their referents from being reclaimed by the garbage collector.

20. Which reference type is best for memory-sensitive caches?

a) StrongReference
b) SoftReference
c) WeakReference
d) PhantomReference
Correct Answer: b) SoftReference
Explanation:
Soft references are cleared only in response to memory demand, making them ideal for caches.

21. What happens when a PhantomReference is enqueued?

a) Referent is accessible
b) finalize is invoked again
c) Notification for post-mortem cleanup is sent
d) Application crashes
Correct Answer: c) Notification for post-mortem cleanup is sent
Explanation:
Phantom references notify the application after the object has been finalized.

22. What is Escape Analysis?

a) Memory leak detection
b) JIT optimization to allocate objects on the stack
c) Algorithm to find unreachable objects
d) Security feature
Correct Answer: b) JIT optimization to allocate objects on the stack
Explanation:
If an object does not escape a method, the JIT compiler can allocate it on the stack to save heap space.

23. Which ClassLoader loads core Java API classes?

a) Extension
b) Application
c) Bootstrap
d) Custom
Correct Answer: c) Bootstrap
Explanation:
The Bootstrap ClassLoader loads the core classes found in the runtime environments.

24. What is the standard delegation principle for ClassLoaders?

a) Child first
b) Parent first
c) Sibling first
d) Random order
Correct Answer: b) Parent first
Explanation:
ClassLoaders delegate to their parent before attempting to load a class themselves.

25. What does the invokedynamic instruction enable?

a) Dynamic compilation
b) Deferred method linking to runtime
c) Bypassing security
d) Loading C libraries
Correct Answer: b) Deferred method linking to runtime
Explanation:
invokedynamic defers method linkage to runtime, heavily used for lambda expressions and dynamic languages.

26. In Java Modules, what does requires transitive do?

a) Hides the module
b) Loads dynamically
c) Grants implicit readability to consuming modules
d) Allows circular dependencies
Correct Answer: c) Grants implicit readability to consuming modules
Explanation:
Modules depending on the declaring module automatically get access to the transitive dependency.

27. What happens if you use Reflection to break strong encapsulation in Java 16+?

a) Succeeds silently
b) Throws InaccessibleObjectException
c) Throws ClassNotFoundException
d) Crashes JVM
Correct Answer: b) Throws InaccessibleObjectException
Explanation:
Since Java 16, internal APIs are strongly encapsulated and reflective access throws an exception.

28. What is the primary difference between Method and MethodHandle?

a) Method is faster
b) MethodHandle checks access at lookup time, Method at invocation
c) MethodHandle is for C code
d) No difference
Correct Answer: b) MethodHandle checks access at lookup time, Method at invocation
Explanation:
MethodHandles perform access checks at creation (lookup) time, making subsequent invocations faster.

29. What does PECS stand for in Java Generics?

a) Parameters Extends, Classes Super
b) Producer Extends, Consumer Super
c) Private Extends, Concurrent Super
d) Polymorphic Execution of Compiled Streams
Correct Answer: b) Producer Extends, Consumer Super
Explanation:
PECS is a mnemonic for bounded wildcards: Producers use extends, Consumers use super.

30. What is Type Erasure?

a) Garbage collection of generic objects
b) Compiler removing generic types to ensure backward compatibility
c) Runtime recovery of generic types
d) Deleting unused classes
Correct Answer: b) Compiler removing generic types to ensure backward compatibility
Explanation:
The compiler replaces generic parameters with bounds or Object, erasing them from runtime bytecode.

31. Why does the Java compiler generate Bridge Methods?

a) To bridge Java and C++
b) To allow private method access
c) To handle polymorphism correctly after type erasure
d) To connect interfaces
Correct Answer: c) To handle polymorphism correctly after type erasure
Explanation:
Bridge methods are synthesized to maintain polymorphic overriding when type erasure alters method signatures.

32. By default, which thread pool does a parallel Stream use?

a) CachedThreadPool
b) Current thread
c) ForkJoinPool.commonPool
d) ScheduledThreadPool
Correct Answer: c) ForkJoinPool.commonPool
Explanation:
Parallel streams utilize the common ForkJoinPool which adapts to the number of processor cores.

33. Which stream operation is stateful?

a) map
b) filter
c) sorted
d) flatMap
Correct Answer: c) sorted
Explanation:
Stateful operations like sorted must process the entire input before producing output.

34. What is the purpose of Spliterator?

a) Concatenating strings
b) Iterating and partitioning elements for parallel execution
c) Splitting arrays
d) Parsing regex
Correct Answer: b) Iterating and partitioning elements for parallel execution
Explanation:
Spliterator provides trySplit() to partition data across multiple threads.

35. What is the difference between reduce and collect in Streams?

a) reduce is intermediate
b) reduce is for immutable reduction, collect is for mutable accumulation
c) reduce works only on primitives
d) No difference
Correct Answer: b) reduce is for immutable reduction, collect is for mutable accumulation
Explanation:
reduce repeatedly applies a combining operation, while collect mutates a container like a List.

36. What does Buffer.flip() do in Java NIO?

a) Clears contents
b) Reverses elements
c) Switches buffer from write mode to read mode
d) Writes to disk
Correct Answer: c) Switches buffer from write mode to read mode
Explanation:
flip() sets the limit to the current position and the position back to zero for reading.

37. What is the main role of a Selector in Java NIO?

a) Selecting items from lists
b) Multiplexing non-blocking I/O operations across multiple Channels
c) Routing IP packets
d) Switching threads
Correct Answer: b) Multiplexing non-blocking I/O operations across multiple Channels
Explanation:
A Selector allows a single thread to monitor multiple channels for events like read or write.

38. What is MappedByteBuffer used for?

a) Heap storage
b) Mapping a file region directly into virtual memory
c) UDP channels
d) Thread blocking
Correct Answer: b) Mapping a file region directly into virtual memory
Explanation:
It maps files directly to memory for highly efficient I/O managed by the OS.

39. How does Files.walk differ from Files.find?

a) walk is deeper
b) find applies a BiPredicate to filter files lazily
c) walk is synchronous
d) find returns a List
Correct Answer: b) find applies a BiPredicate to filter files lazily
Explanation:
find takes a BiPredicate to efficiently filter the directory tree during traversal.

40. What does WatchService API do?

a) Profiles CPU
b) Monitors file system changes like creation or deletion
c) Tracks memory leaks
d) Observes threads
Correct Answer: b) Monitors file system changes like creation or deletion
Explanation:
It provides an OS-level mechanism to receive events on file system modifications.

41. What is the significance of serialVersionUID?

a) Database key
b) Encryption key
c) Verifies class compatibility during deserialization
d) Prevents serialization
Correct Answer: c) Verifies class compatibility during deserialization
Explanation:
It ensures the serialized object matches the loaded class structure.

42. Which method can replace a deserialized object instance (e.g., for Singletons)?

a) readObject
b) writeReplace
c) readResolve
d) clone
Correct Answer: c) readResolve
Explanation:
readResolve is called after deserialization to substitute the parsed instance.

43. How does Externalizable differ from Serializable?

a) Externalizable is a marker
b) Externalizable requires implementing readExternal and writeExternal
c) Externalizable is for primitives
d) Externalizable is faster by default
Correct Answer: b) Externalizable requires implementing readExternal and writeExternal
Explanation:
Externalizable mandates custom logic for object serialization and deserialization.

44. What is a Virtual Thread in Java 21?

a) Heavy OS thread
b) Mock testing thread
c) Lightweight JVM-managed thread that does not tie up an OS thread
d) GPU thread
Correct Answer: c) Lightweight JVM-managed thread that does not tie up an OS thread
Explanation:
Virtual threads reduce overhead, allowing millions of threads on a single JVM.

45. What is the primary goal of Structured Concurrency?

a) Single core execution
b) Treating multiple concurrent tasks as a single logical unit for better error handling
c) Converting async to sync
d) Removing locks
Correct Answer: b) Treating multiple concurrent tasks as a single logical unit for better error handling
Explanation:
It simplifies thread management, cancellation, and error propagation.

46. What are Scoped Values designed to replace?

a) Static variables
b) ThreadLocal variables
c) Synchronized blocks
d) System properties
Correct Answer: b) ThreadLocal variables
Explanation:
Scoped values are a safer, more efficient alternative to ThreadLocals for Virtual Threads.

47. Which feature extracts components directly in an instanceof check?

a) Method References
b) Pattern Matching
c) Type Erasure
d) Reflection
Correct Answer: b) Pattern Matching
Explanation:
Pattern matching checks a type and binds it to a variable in one step.

48. Which keyword returns a value from a block in a Switch Expression?

a) return
b) break
c) yield
d) continue
Correct Answer: c) yield
Explanation:
The yield keyword is used to return a result from a multi-line switch case block.

49. Which is true about Java Records?

a) Deep immutability
b) Can extend classes
c) Automatically generate constructor, equals, hashCode, and toString
d) Mutable fields
Correct Answer: c) Automatically generate constructor, equals, hashCode, and toString
Explanation:
Records generate standard boilerplate code for immutable data carriers.

50. How do you validate data in a Record?

a) Extending interfaces
b) Overriding setters
c) Using a compact constructor
d) External validation only
Correct Answer: c) Using a compact constructor
Explanation:
Compact constructors run validation without needing to redefine parameters.

51. What is the purpose of Sealed Classes?

a) Prevent serialization
b) Restrict which classes can extend them
c) Hide from reflection
d) Force immutability
Correct Answer: b) Restrict which classes can extend them
Explanation:
Sealed classes explicitly list allowed subclasses, enabling exhaustive pattern matching.

52. Which modifier must a subclass of a sealed class have?

a) final, sealed, or non-sealed
b) public
c) abstract
d) static
Correct Answer: a) final, sealed, or non-sealed
Explanation:
Subclasses must explicitly declare their extension status.

53. How do Text Blocks handle incidental indentation?

a) Preserves all spaces
b) Strips leading whitespace based on the closing delimiter
c) Removes all spaces
d) Replaces spaces with tabs
Correct Answer: b) Strips leading whitespace based on the closing delimiter
Explanation:
Text blocks automatically strip common leading indentation to align text logically.

54. What is the goal of Project Panama?

a) Compile to JS
b) Replace JNI with a faster, safer Foreign Function API
c) Mobile Java
d) Encrypt memory
Correct Answer: b) Replace JNI with a faster, safer Foreign Function API
Explanation:
Panama simplifies calling native C/C++ libraries and managing off-heap memory.

55. What is the purpose of the Vector API?

a) Replace java.util.Vector
b) Express vector computations that compile to hardware SIMD instructions
c) Draw SVG graphics
d) Multidimensional arrays
Correct Answer: b) Express vector computations that compile to hardware SIMD instructions
Explanation:
It allows parallel mathematical operations mapping directly to CPU SIMD features.

56. Where can the var keyword be used?

a) Class fields
b) Method return types
c) Local variables with initializers
d) Method parameters
Correct Answer: c) Local variables with initializers
Explanation:
Type inference with var is strictly limited to local variables that are initialized immediately.

57. What is ResultSet holdability?

a) If ResultSet stays open after a commit
b) Memory limit
c) Updatability
d) Scrollability
Correct Answer: a) If ResultSet stays open after a commit
Explanation:
Holdability defines whether the cursor remains open after a transaction commits.

58. What does a Savepoint do in JDBC?

a) Backs up database
b) Allows partial rollback of a transaction
c) Caches results
d) Restarts connection
Correct Answer: b) Allows partial rollback of a transaction
Explanation:
Savepoints allow you to roll back a transaction to a specific point without dropping the entire transaction.

59. What does executeBatch() return?

a) ResultSet
b) Boolean
c) Array of update counts
d) Total rows integer
Correct Answer: c) Array of update counts
Explanation:
It returns an int array representing the rows affected by each statement in the batch.

60. What is a major advantage of CachedRowSet?

a) Connects to multiple DBs
b) Disconnected from database, allowing serialization
c) Faster execution
d) Prevents SQL injection
Correct Answer: b) Disconnected from database, allowing serialization
Explanation:
It caches data in memory, allowing it to operate without an active DB connection.

61. What is Annotation Processing (APT)?

a) Runtime dependency injection
b) Compile-time tool to generate source files from annotations
c) XML processing
d) GC optimization
Correct Answer: b) Compile-time tool to generate source files from annotations
Explanation:
APT runs during compilation to generate code like getters and setters.

62. Which annotation defines how long an annotation is retained?

a) @Target
b) @Inherited
c) @Retention
d) @Documented
Correct Answer: c) @Retention
Explanation:
@Retention specifies if it is kept at SOURCE, CLASS, or RUNTIME.

63. What does @Target do?

a) Maps to a table
b) Specifies where the annotation can be applied
c) Defines retention policy
d) Defines threads
Correct Answer: b) Specifies where the annotation can be applied
Explanation:
@Target restricts the annotation to specific elements like fields, methods, or classes.

64. How is a repeatable annotation declared in Java 8?

a) @Multiple
b) @Repeatable meta-annotation along with a container annotation
c) Arrays by default
d) Not possible
Correct Answer: b) @Repeatable meta-annotation along with a container annotation
Explanation:
@Repeatable allows identical annotations on a single declaration.

65. What does the -Xms flag specify?

a) Max heap size
b) Max stack size
c) Initial heap size
d) Metaspace size
Correct Answer: c) Initial heap size
Explanation:
-Xms defines the starting heap memory allocation for the JVM.

66. What does UseStringDeduplication do?

a) Removes list duplicates
b) Points identical Strings to the same underlying array during GC
c) Disables String Pool
d) Caches all Strings
Correct Answer: b) Points identical Strings to the same underlying array during GC
Explanation:
It saves heap space by making identical String objects share the same backing array.

67. What is the Java Flight Recorder (JFR)?

a) GUI macro tool
b) Low-overhead profiling and event collection framework built into the JVM
c) Migration framework
d) Socket API
Correct Answer: b) Low-overhead profiling and event collection framework built into the JVM
Explanation:
JFR collects diagnostic data with extremely low performance overhead.

68. What is JMH used for?

a) Testing DBs
b) Building web apps
c) Accurate microbenchmarking handling JVM warm-up
d) Mocking objects
Correct Answer: c) Accurate microbenchmarking handling JVM warm-up
Explanation:
JMH mitigates JIT compilation effects to provide accurate performance metrics.

69. What is Class Data Sharing (CDS)?

a) Shares class metadata in memory across JVM instances to reduce startup time
b) Shares classes with Python
c) Network synchronization
d) Dynamic recompilation
Correct Answer: a) Shares class metadata in memory across JVM instances to reduce startup time
Explanation:
CDS memory-maps shared archives to reduce memory usage and improve startup.

70. Why was SecurityManager deprecated?

a) Outdated applet technology that restricts modern API development
b) Replaced by AI
c) Made JVM too fast
d) Moved to external library
Correct Answer: a) Outdated applet technology that restricts modern API development
Explanation:
It had a high maintenance cost and is rarely used in modern server-side Java.

71. What is the Java Cryptography Architecture (JCA)?

a) JVM architecture
b) Provider-based framework for cryptography
c) Bytecode obfuscator
d) Network protocol
Correct Answer: b) Provider-based framework for cryptography
Explanation:
JCA allows pluggable security providers for cryptographic operations.

72. What is the difference between KeyStore and TrustStore?

a) KeyStore holds public keys, TrustStore holds private keys
b) KeyStore holds private keys, TrustStore holds trusted public certificates
c) They are identical
d) Symmetric vs Asymmetric
Correct Answer: b) KeyStore holds private keys, TrustStore holds trusted public certificates
Explanation:
KeyStore authenticates you; TrustStore authenticates others.

73. How does HashMap handle heavy collisions in Java 8?

a) Secondary hash
b) Rejects duplicates
c) Converts linked lists to Red-Black trees
d) Instant resizing
Correct Answer: c) Converts linked lists to Red-Black trees
Explanation:
Treeifying buckets reduces worst-case lookup time from O(n) to O(log n).

74. What is the use case for WeakHashMap?

a) High concurrency
b) Identity mapping
c) Caches that automatically remove entries when keys are GC'd
d) Compact storage
Correct Answer: c) Caches that automatically remove entries when keys are GC'd
Explanation:
Keys are held with WeakReferences, allowing auto-removal if keys are unreferenced.

75. How does IdentityHashMap determine equality?

a) equals method
b) Reference equality using ==
c) hashCode
d) compareTo
Correct Answer: b) Reference equality using ==
Explanation:
It intentionally violates the Map contract by using reference equality.

76. Why is EnumSet highly efficient?

a) Red-Black Tree
b) Compressed String format
c) Backed by a single bit vector (long)
d) Does not allow removal
Correct Answer: c) Backed by a single bit vector (long)
Explanation:
EnumSets use bitwise operations on a single long, making them extremely fast.

77. Which interface provides methods like lowerEntry and higherKey?

a) SortedMap
b) NavigableMap
c) ConcurrentMap
d) Map
Correct Answer: b) NavigableMap
Explanation:
NavigableMap allows querying for closest matches in a sorted structure.

78. What framework does Arrays.parallelSort use?

a) ExecutorService
b) Fork/Join framework
c) Direct threading
d) MapReduce
Correct Answer: b) Fork/Join framework
Explanation:
It recursively splits arrays and sorts them using ForkJoinPool.

79. What is the purpose of a Thread Dump?

a) View heap memory
b) Display exact state of all threads to identify deadlocks
c) Database backup
d) Force GC
Correct Answer: b) Display exact state of all threads to identify deadlocks
Explanation:
Thread dumps are essential for troubleshooting performance issues and deadlocks.

80. Which file format is used for Heap Dumps?

a) .dump
b) .xml
c) .hprof
d) .log
Correct Answer: c) .hprof
Explanation:
HPROF is the binary format used by JVMs for heap dumps.

81. What is JNIEnv in JNI?

a) Environment variable
b) Pointer to an interface table with all JNI functions
c) Garbage collector proxy
d) Native compiler
Correct Answer: b) Pointer to an interface table with all JNI functions
Explanation:
JNIEnv provides the gateway to call JNI functions from native C/C++ code.

82. What is the advantage of Java Native Access (JNA)?

a) No native code
b) Direct access to native shared libraries without writing boilerplate JNI code
c) Inherent memory safety
d) Faster than JNI
Correct Answer: b) Direct access to native shared libraries without writing boilerplate JNI code
Explanation:
JNA uses dynamic proxies to avoid writing glue code in C/C++.

83. Which flag configures the thread stack size?

a) -Xmx
b) -Xms
c) -Xss
d) -XX:MaxPermSize
Correct Answer: c) -Xss
Explanation:
-Xss controls stack memory size for each thread.

84. What is stored in the Mark Word of an Object Header?

a) Class pointer
b) Identity hash code, GC age, and locking info
c) Primitive fields
d) Object name
Correct Answer: b) Identity hash code, GC age, and locking info
Explanation:
The Mark Word holds critical runtime state for synchronization and garbage collection.

85. Why was Biased Locking deprecated?

a) Consumed too much memory
b) High codebase complexity outweighed modern performance gains
c) Caused deadlocks
d) Prevented Virtual Threads
Correct Answer: b) High codebase complexity outweighed modern performance gains
Explanation:
Modern synchronized implementations are fast enough that biased locking is unnecessary.

86. What is a Memory Barrier in Java?

a) Heap limit
b) Hardware instruction enforcing memory operation ordering
c) Prevents OOM
d) Space boundary
Correct Answer: b) Hardware instruction enforcing memory operation ordering
Explanation:
Memory barriers prevent CPU reordering, crucial for the volatile keyword.

87. What does the @Contended annotation solve?

a) Deadlocks
b) False sharing among independent variables
c) Thread starvation
d) Priority inversion
Correct Answer: b) False sharing among independent variables
Explanation:
It adds padding to isolate variables onto distinct CPU cache lines.

88. What is the benefit of ByteBuffer.allocateDirect()?

a) Avoids GC
b) Allocates memory off-heap, allowing native OS I/O operations without intermediate copying
c) Compresses data
d) Allocates on stack
Correct Answer: b) Allocates memory off-heap, allowing native OS I/O operations without intermediate copying
Explanation:
Direct buffers bypass the JVM heap for higher performance in network and file I/O.

89. What is the role of a Condition object in ReentrantLock?

a) Conditionally acquire lock
b) Provides multiple wait-sets per lock for precise signaling
c) Limits threads
d) Checks interruption
Correct Answer: b) Provides multiple wait-sets per lock for precise signaling
Explanation:
Conditions replace Object wait and notify, allowing finer control over waiting threads.

90. What is true about ReentrantReadWriteLock?

a) Multiple writers allowed
b) Multiple concurrent readers allowed, but only one writer
c) Strict turns for read and write
d) No downgrading
Correct Answer: b) Multiple concurrent readers allowed, but only one writer
Explanation:
It optimizes read-heavy concurrency by not blocking concurrent reads.

91. What does Stream.generate() do?

a) Creates limited random numbers
b) Returns an infinite stream generated by a Supplier
c) Compiles a lambda
d) Generates a file
Correct Answer: b) Returns an infinite stream generated by a Supplier
Explanation:
generate creates infinite streams, often used with limit().

92. Which method converts a Stream of Lists into a Stream of elements?

a) map
b) concat
c) flatMap
d) reduce
Correct Answer: c) flatMap
Explanation:
flatMap flattens multiple nested structures into a single stream.

93. How does distinct() filter objects?

a) Memory reference
b) Using equals and hashCode
c) Using Comparable
d) Randomly
Correct Answer: b) Using equals and hashCode
Explanation:
Stream.distinct uses object equality methods to remove duplicates.

94. Which Collector partitions elements into exactly two groups based on a Predicate?

a) groupingBy
b) splittingBy
c) partitioningBy
d) dividingBy
Correct Answer: c) partitioningBy
Explanation:
partitioningBy creates a Map with Boolean keys (true and false).

95. What does Optional.orElseGet() do when empty?

a) Returns null
b) Throws exception
c) Invokes the provided Supplier lazily
d) Returns itself
Correct Answer: c) Invokes the provided Supplier lazily
Explanation:
orElseGet takes a Supplier and evaluates it only when the Optional is empty.

96. What is the default package accessibility in Java Modules?

a) Public to all
b) Strongly encapsulated and invisible unless exported
c) Reflection only
d) Public to classpath
Correct Answer: b) Strongly encapsulated and invisible unless exported
Explanation:
Modules hide internal packages by default for better security and maintainability.

97. What does the opens directive in module-info do?

a) Exports at compile time
b) Allows runtime deep reflection by other modules
c) Starts threads
d) Imports packages
Correct Answer: b) Allows runtime deep reflection by other modules
Explanation:
The opens directive permits frameworks (like Spring or Hibernate) to access private members via reflection.

98. What is jshell?

a) jcmd tool
b) Java's interactive REPL tool
c) Monitoring console
d) Statistics tool
Correct Answer: b) Java's interactive REPL tool
Explanation:
JShell allows developers to run snippets of Java interactively.

99. What defines CopyOnWriteArraySet?

a) Mathematically sorted
b) Backed by CopyOnWriteArrayList, thread-safe with no read locks
c) Blocks reads
d) Throws concurrent exceptions
Correct Answer: b) Backed by CopyOnWriteArrayList, thread-safe with no read locks
Explanation:
It creates a new array on every write, keeping reads entirely lock-free.

100. What is a Child-First delegation model in classloading?

a) Loads class before delegating to parent
b) Loads nested classes first
c) Delegates to children
d) Default JVM behavior
Correct Answer: a) Loads class before delegating to parent
Explanation:
Used in app servers like Tomcat to prioritize web app libraries over server libraries.

101. What does sun.misc.Unsafe do?

a) Standard arithmetic
b) Provides low-level, unsafe memory and thread operations
c) Throws exceptions
d) Encrypts passwords
Correct Answer: b) Provides low-level, unsafe memory and thread operations
Explanation:
Unsafe bypasses JVM safety checks, used internally for high-performance utilities.
← Previous: Important Java 8 Features MCQs
Next →: Java Basics MCQs for Developer Interviews & Certification
Python Functions MCQs

Python Functions MCQs

Functions in Python are reusable blocks of code designed to perform a specific task, promoting code modularity, readability, and DRY…

By MCQs Generator
Python Decorators & Generators MCQs

Python Decorators & Generators MCQs

Python decorators and generators are powerful advanced features that enable clean, modular, and high-performance programming. Decorators are higher-order functions that…

By MCQs Generator
C++ Strings MCQs

C++ Strings MCQs

In C++, strings are handled in two primary ways: traditional C-style strings (null-terminated character arrays) and the modern std::string class…

By MCQs Generator