1. Why is Java considered platform independent?
Difficulty: EasyType: MCQTopic: Java Basics
- Because JVM is written in C
- Because source code runs directly on any OS
- Because Java compiles to bytecode executed by a JVM on each platform
- Because Java ships its own OS
javac produces bytecode; the platform-specific JVM interprets/JIT-compiles it, enabling WORA.
Correct Answer: Because Java compiles to bytecode executed by a JVM on each platform
2. Pick the correct mapping:
Difficulty: EasyType: MCQTopic: JVM Basics
- JVM = tools + compiler; JDK = runtime
- JRE = JVM + libs; JDK = JRE + dev tools
- JDK = JVM only
- JRE = compiler only
JRE contains the JVM and core libraries; JDK bundles JRE plus compilers and tooling.
Correct Answer: JRE = JVM + libs; JDK = JRE + dev tools
3. Which area holds per-thread call frames (locals, operand stack)?
Difficulty: MediumType: MCQTopic: JVM Memory
- Heap
- Method Area
- JVM Stack
- Native Method Stack
Each thread has its own JVM stack containing frames for method execution.
Correct Answer: JVM Stack
4. Explain the delegation model of classloaders and why it matters for security.
Difficulty: MediumType: SubjectiveTopic: Classloading
Parent-first delegation ensures core classes loaded by bootstrap are trusted, preventing malicious shadowing; custom loaders typically delegate up before defining classes.
5. What does the JIT do at runtime?
Difficulty: MediumType: MCQTopic: JIT
- Converts Java source to bytecode
- Converts hot bytecode paths to native machine code
- Schedules OS threads
- Garbage collects unreachable objects
The JIT compiles frequently executed methods/loops to native code for speed.
Correct Answer: Converts hot bytecode paths to native machine code
6. Which is the canonical Java entry point?
Difficulty: EasyType: MCQTopic: Java Basics
- public static main(String args[])
- public void main(String args[])
- public static void main(String[] args)
- static public int main(String... a)
JVM searches for a public static void main(String[]). Varargs are allowed but return must be void.
Correct Answer: public static void main(String[] args)
7. What is the String pool and how do string literals vs new String(…) behave?
Difficulty: EasyType: SubjectiveTopic: Strings
Literals are interned in the String pool; identical literals share one instance. new String creates a distinct heap object even if an equal literal exists.
8. Which statement about wrappers is TRUE?
Difficulty: EasyType: MCQTopic: Types
- Wrappers are mutable
- Autoboxing can introduce unintended null unboxing NPEs
- Wrappers are faster than primitives
- Wrappers occupy no heap space
Unboxing a null Integer to int throws NPE; wrappers are immutable and live on heap.
Correct Answer: Autoboxing can introduce unintended null unboxing NPEs
9. Default value of an uninitialized instance boolean field is:
Difficulty: EasyType: MCQTopic: Java Basics
Instance fields get defaults; locals don’t. boolean defaults to false.
Correct Answer: false
10. Differentiate this(...) and super(...) constructor calls and their placement rules.
Difficulty: EasyType: SubjectiveTopic: OOP Keywords
Both must be the first statement. this(...) chains within the same class; super(...) calls parent ctor. Only one can appear, and compiler inserts implicit super() if none provided.
11. Match use-cases correctly:
Difficulty: MediumType: MCQTopic: Keywords
- final = cleanup hook; finally = constant; finalize = block after try
- final = non-override/const; finally = always-runs block; finalize = GC pre-cleanup hook
- final = logging; finally = destructor; finalize = thread stop
- All three are the same
final modifies classes/methods/variables; finally executes regardless of exception; finalize() is legacy GC callback (discouraged).
Correct Answer: final = non-override/const; finally = always-runs block; finalize = GC pre-cleanup hook
12. Compare default (package-private), protected, public, and private access in terms of cross-package visibility and inheritance.
Difficulty: MediumType: SubjectiveTopic: Access Control
private: class only; default: package; protected: package + subclasses (even cross-package via inheritance); public: everywhere.
13. Which order is correct for initialization when creating an instance?
Difficulty: MediumType: MCQTopic: Classloading
- Subclass fields → Subclass static → Superclass static → Superclass fields
- Superclass static → Subclass static → Superclass instance (fields/blocks/ctor) → Subclass instance (fields/blocks/ctor)
- Subclass static → Superclass static → Subclass instance → Superclass instance
- Instance then static
Statics load top-down in hierarchy, then per-instance initialization proceeds super→sub.
Correct Answer: Superclass static → Subclass static → Superclass instance (fields/blocks/ctor) → Subclass instance (fields/blocks/ctor)
14. Why are immutable types (e.g., String) favored for keys and thread safety?
Difficulty: EasyType: SubjectiveTopic: Immutability
Stable hashCode/equality avoids map/key corruption; no internal state changes simplify reasoning and eliminate data races.
15. Which best describes encapsulation in Java?
Difficulty: EasyType: MCQTopic: Encapsulation
- Binding data and methods that operate on that data into a single unit
- Using multiple classes to implement one feature
- Converting objects to primitives
- Hiding inheritance hierarchies
Encapsulation bundles state and behavior, typically with private fields and public getters/setters.
Correct Answer: Binding data and methods that operate on that data into a single unit
16. List two practical benefits of encapsulation for large codebases.
Difficulty: EasyType: SubjectiveTopic: Encapsulation
Improves invariants and validation at a single point; reduces coupling and exposes a minimal API, easing refactoring.
17. Java supports which form(s) of inheritance for classes?
Difficulty: EasyType: MCQTopic: Inheritance
- Multiple and multilevel
- Single and multilevel (no multiple class inheritance)
- Only multiple inheritance
- No inheritance
Java classes form single-inheritance trees; interfaces allow multiple inheritance of type.
Correct Answer: Single and multilevel (no multiple class inheritance)
18. Which pairing is correct?
Difficulty: MediumType: MCQTopic: OOP Design
- Composition → IS-A
- Aggregation → IS-A
- Inheritance → IS-A
- Encapsulation → HAS-A
Inheritance models an is-a relationship; composition/aggregation model has-a.
Correct Answer: Inheritance → IS-A
19. Differentiate compile-time and run-time polymorphism in Java with one-liners.
Difficulty: MediumType: SubjectiveTopic: Polymorphism
Overloading is compile-time (choose method by signature); overriding is runtime (dispatch by actual object).
20. Which is a valid method-override change?
Difficulty: MediumType: MCQTopic: Overriding
- Narrowing access from public to private
- Changing return type to an unrelated type
- Throwing broader checked exceptions than the base
- Using a covariant (more specific) return type
Access cannot be reduced; checked exceptions can be same/narrower; return can be covariant.
Correct Answer: Using a covariant (more specific) return type
21. Which methods are NOT polymorphic via override?
Difficulty: MediumType: MCQTopic: Keywords
- final methods
- static methods
- private methods
- All of the above
final cannot be overridden; static resolves by compile-time binding; private is not visible to subclasses.
Correct Answer: All of the above
22. How do abstract classes and interfaces each enable abstraction? Give a crisp contrast.
Difficulty: EasyType: SubjectiveTopic: Abstraction
Abstract classes: partial implementation + state; interfaces: contracts of behavior; since Java 8+, interfaces can have default/static methods but no instance state.
23. Which statements about Java interfaces are accurate (Java 8+)?
Difficulty: MediumType: MCQTopic: Interfaces
- Interfaces can have default and static methods
- Interfaces can have instance fields
- Interfaces can be instantiated directly
- Interfaces cannot extend other interfaces
They can declare constants but not instance fields; cannot be instantiated; may extend other interfaces.
Correct Answer: Interfaces can have default and static methods
24. When would you prefer composition over inheritance? Name two scenarios.
Difficulty: MediumType: SubjectiveTopic: OOP Design
When reusing behavior without inheriting unwanted API; when behavior needs to vary at runtime (strategy pattern); to avoid fragile base-class coupling.
25. Violating Liskov Substitution Principle (LSP) in an inheritance hierarchy most likely causes:
Difficulty: HardType: MCQTopic: LSP
- Better performance
- Objects of subtype failing when used as base type
- Cleaner APIs
- Safer covariance
LSP requires subtypes to be usable anywhere the base is expected without breaking semantics.
Correct Answer: Objects of subtype failing when used as base type
26. What do sealed classes/interfaces (Java 17) achieve?
Difficulty: MediumType: MCQTopic: Sealed Types
- Allow runtime addition of subclasses
- Restrict which classes can extend/implement them
- Auto-generate equals/hashCode
- Replace abstract classes
Sealed types control extension points, improving maintainability and exhaustiveness checks.
Correct Answer: Restrict which classes can extend/implement them
27. Which can make overload resolution surprising?
Difficulty: MediumType: MCQTopic: Overloading
- Autoboxing
- Varargs
- Primitive widening
- All of the above
The compiler applies a ranking (most specific) that can pick unexpected overloads with boxing/widening/varargs.
Correct Answer: All of the above
28. Explain how access modifiers (private/protected/public) support the OOP goals of encapsulation and modularity.
Difficulty: MediumType: SubjectiveTopic: Access Control
They define stable boundaries—hiding internals (private), exposing minimal extension points (protected), and clear public APIs—reducing coupling and easing evolution.
29. What is the main purpose of the Java String Pool?
Difficulty: EasyType: MCQTopic: Strings
- To store interned String literals and reuse references
- To cache compiled bytecode
- To buffer I/O for Strings
- To store thread-local Strings
The pool enables reuse of identical String literals, saving memory and speeding equality checks.
Correct Answer: To store interned String literals and reuse references
30. Why are Java Strings immutable? Give two benefits.
Difficulty: EasyType: SubjectiveTopic: Strings
Safety in sharing/caching (e.g., pool, classpath, keys) and security/thread-safety; also enables stable hash codes for map keys.
31. When should you prefer StringBuilder over StringBuffer?
Difficulty: EasyType: MCQTopic: Strings
- In single-threaded concatenations requiring performance
- When you need immutability
- When you need constant-time equals
- Always, regardless of threads
StringBuilder is non-synchronized and faster in single-threaded contexts.
Correct Answer: In single-threaded concatenations requiring performance
32. For Strings, which statement is true?
Difficulty: EasyType: MCQTopic: Equality
- == compares content, equals compares references
- equals compares content, == compares references
- Both compare references
- Both compare content
equals is overridden to compare character content; == checks object identity.
Correct Answer: equals compares content, == compares references
33. List the primary root interfaces in the Collections Framework and one concrete class for each.
Difficulty: MediumType: SubjectiveTopic: Collections
Collection(List/Set/Queue/Deque) and Map; e.g., ArrayList, HashSet, ArrayDeque, HashMap.
34. What happens when an ArrayList exceeds its capacity?
Difficulty: MediumType: MCQTopic: Lists
- It throws an exception
- It resizes by allocating a larger array and copying elements
- It spills to disk
- It converts to a LinkedList
ArrayList uses a backing array and grows by allocating a larger one then copying.
Correct Answer: It resizes by allocating a larger array and copying elements
35. Name one operation typically faster on ArrayList and one typically faster on LinkedList. Why?
Difficulty: MediumType: SubjectiveTopic: Lists
ArrayList random access (O(1)) due to contiguous array; LinkedList insert/remove in middle (O(1) after locating node) due to links.
36. Which characteristic defines a Set?
Difficulty: EasyType: MCQTopic: Collections
- Allows duplicates and maintains insertion order
- No duplicates; ordering depends on implementation
- Sorted descending by default
- Index-based random access
HashSet (no order), LinkedHashSet (insertion order), TreeSet (sorted).
Correct Answer: No duplicates; ordering depends on implementation
37. For objects used as keys in a HashMap, which is required?
Difficulty: MediumType: MCQTopic: Maps
- Override equals only
- Override hashCode only
- Override both equals and hashCode consistently
- Implement Comparable
Consistency ensures keys that are equal hash to same bucket and behave correctly.
Correct Answer: Override both equals and hashCode consistently
38. Contrast TreeMap and HashMap in terms of ordering, performance, and key requirements.
Difficulty: MediumType: SubjectiveTopic: Maps
TreeMap is sorted (log N ops, Comparable/Comparator needed); HashMap is unsorted (avg O(1) ops) and only needs equals/hashCode.
39. What typically triggers ConcurrentModificationException during iteration?
Difficulty: MediumType: MCQTopic: Iterators
- Using iterator.remove()
- Modifying the collection structurally outside the iterator during iteration
- Reading with for-each
- Calling size()
Fail-fast checks a modCount; external structural changes break the iteration contract.
Correct Answer: Modifying the collection structurally outside the iterator during iteration
40. Which creates a read-only view of a List?
Difficulty: EasyType: MCQTopic: Collections
- Collections.unmodifiableList(list)
- new ArrayList<>(list)
- list.subList(0, list.size())
- List.copyOf(list) then cast to ArrayList
It returns an unmodifiable view that throws on mutating operations.
Correct Answer: Collections.unmodifiableList(list)
41. When do you implement Comparable vs provide a Comparator?
Difficulty: MediumType: SubjectiveTopic: Ordering
Comparable defines a natural order in the class itself; Comparator supplies alternative or external orderings without changing the class.
42. Which collection is designed for high-concurrency reads with segmented/striped locking (or CAS) rather than a single lock?
Difficulty: MediumType: MCQTopic: Concurrent Coll
- Hashtable
- Collections.synchronizedMap(new HashMap<>())
- ConcurrentHashMap
- TreeMap
ConcurrentHashMap avoids a global lock to scale concurrent access; Hashtable and synchronizedMap use coarse-grained locks.
Correct Answer: ConcurrentHashMap
43. Name the four pillars of OOP in Java and give one-liner benefits for each.
Difficulty: EasyType: SubjectiveTopic: OOP Basics
Encapsulation (data safety), Abstraction (hide detail), Inheritance (reuse), Polymorphism (flexible behavior).
44. Which is TRUE about method overriding?
Difficulty: EasyType: MCQTopic: Overriding
- Return type must be identical only
- Access can be narrowed
- Return type can be covariant
- Static methods are commonly overridden
Overriding allows covariant return; access cannot be narrowed; static methods are hidden, not overridden.
Correct Answer: Return type can be covariant
45. Pick the correct statement:
Difficulty: EasyType: MCQTopic: OOP Keywords
- super refers to current object
- this calls parent constructors
- super accesses parent members/constructors
- this and super are interchangeable
this → current instance; super → immediate parent’s members/ctor.
Correct Answer: super accesses parent members/constructors
46. When would you choose an abstract class over an interface in modern Java?
Difficulty: MediumType: SubjectiveTopic: Interfaces
Abstract class for shared state/base implementation and ctor control; interface for capability types, multiple inheritance of behavior (default/static).
47. A class implements two interfaces that define the same default method. How do you resolve the conflict?
Difficulty: MediumType: MCQTopic: Interfaces
- You can’t; it’s a compile error with no fix
- Override the method in the class and optionally call InterfaceName.super.m()
- Mark one interface as primary
- Add final to one interface method
Class must override and can delegate to a specific interface’s default via Interface.super.method().
Correct Answer: Override the method in the class and optionally call InterfaceName.super.m()
48. Which methods cannot be overridden?
Difficulty: MediumType: MCQTopic: Keywords
- final and private
- static and abstract
- synchronized and native
- public and protected
final forbids overriding; private isn’t visible to subclasses. static methods are hidden, not overridden.
Correct Answer: final and private
49. Why are constructors not inherited? How does a subclass ensure proper initialization?
Difficulty: MediumType: SubjectiveTopic: Constructors
Constructors tie to class identity. Subclass chains initialization via super(...) call to construct the parent part first.
50. Pick the correct pairing:
Difficulty: EasyType: MCQTopic: Polymorphism
- Overloading: runtime; Overriding: compile-time
- Overloading: same name, different params; Overriding: same signature, subclass
- Both are runtime
- Both require covariant return
Overloading resolved at compile-time; overriding at runtime via dynamic dispatch.
Correct Answer: Overloading: same name, different params; Overriding: same signature, subclass
51. What do sealed classes primarily control?
Difficulty: MediumType: MCQTopic: Sealed Types
- Who can extend/implement them
- Immutability of instances
- Serialization format
- Automatic pattern matching for switch
sealed ... permits ... restricts the subclassing hierarchy for better design and exhaustiveness.
Correct Answer: Who can extend/implement them
52. Give one scenario where composition is preferable to inheritance and explain why.
Difficulty: MediumType: SubjectiveTopic: OOP Design
Prefer composition to avoid tight coupling and fragile base class—e.g., reuse behavior by delegating to a helper instead of extending.
53. LSP implies a subtype should:
Difficulty: MediumType: MCQTopic: LSP
- Expose extra public methods only
- Be replaceable for its base type without breaking client expectations
- Have fewer fields than base
- Always be final
Clients coded to the base shouldn’t observe incorrect behavior when given the subtype.
Correct Answer: Be replaceable for its base type without breaking client expectations
54. Why is it dangerous to base equals/hashCode on mutable fields in a polymorphic class hierarchy?
Difficulty: MediumType: SubjectiveTopic: Equality
Mutations can break set/map invariants and lookup; cross-type symmetry/consistency can also be violated.
55. Dynamic method dispatch in Java selects the implementation based on:
Difficulty: MediumType: MCQTopic: Polymorphism
- Reference type at compile time
- Object’s runtime type
- Package visibility
- JVM vendor
Overridden instance methods are chosen by the actual object type at runtime.
Correct Answer: Object’s runtime type
56. Differentiate Template Method and Strategy patterns in OOP terms.
Difficulty: MediumType: SubjectiveTopic: Patterns
Template Method fixes algorithm skeleton in a base class with overridable steps; Strategy composes behavior by swapping implementations at runtime.
57. Which pair correctly classifies exceptions in Java?
Difficulty: EasyType: MCQTopic: Exceptions
- IOException: unchecked, NullPointerException: checked
- IOException: checked, NullPointerException: unchecked
- SQLException: unchecked, ArithmeticException: checked
- RuntimeException: checked, Error: unchecked
Checked exceptions must be declared or handled; examples include IOException and SQLException. Unchecked exceptions extend RuntimeException; NullPointerException and ArithmeticException are typical. Errors are also unchecked and indicate serious VM problems.
Correct Answer: IOException: checked, NullPointerException: unchecked
58. Pick the correct hierarchy path.
Difficulty: MediumType: MCQTopic: Exceptions
- Throwable → Exception → RuntimeException → Error
- Throwable → Error → Exception → RuntimeException
- Throwable → Exception → RuntimeException
- Object → Exception → Throwable → RuntimeException
Throwable is the root. It has two direct children: Error and Exception. RuntimeException extends Exception. Errors are siblings of Exception, not children of RuntimeException.
Correct Answer: Throwable → Exception → RuntimeException
59. Which statement about finally is true?
Difficulty: MediumType: MCQTopic: Exceptions
- finally executes only if an exception is thrown.
- finally may not execute if System.exit is invoked.
- finally runs before catch.
- finally cannot access variables declared in try.
finally runs after try or catch for cleanup, regardless of normal or exceptional flow. It can be skipped in rare cases like System.exit, JVM crash, or power loss.
Correct Answer: finally may not execute if System.exit is invoked.
60. You catch ArithmeticException and Exception in that order. Which is correct?
Difficulty: MediumType: MCQTopic: Exceptions
- Order does not matter; the compiler reorders them.
- Specific exceptions must come before general ones.
- General exceptions must come before specific ones.
- Only one catch block is allowed per try.
Catch blocks are matched top-down. If a broader type comes first, narrower types are unreachable, causing a compile-time error.
Correct Answer: Specific exceptions must come before general ones.
61. What is required for a type to be used in try-with-resources?
Difficulty: MediumType: MCQTopic: Resources
- It must implement Cloneable.
- It must be final.
- It must implement AutoCloseable.
- It must be a java.io.* type.
try-with-resources auto-closes resources that implement AutoCloseable (or Closeable which extends it). This ensures deterministic cleanup even when exceptions occur.
Correct Answer: It must implement AutoCloseable.
62. In try-with-resources, where do exceptions thrown during close() appear?
Difficulty: HardType: MCQTopic: Exceptions
- They replace the primary exception.
- They are ignored silently.
- They appear as suppressed exceptions on the primary exception.
- They are delivered to a global handler only.
If both the try body and close() throw, the try body’s exception is primary, and close() exceptions are attached as suppressed, retrievable via getSuppressed().
Correct Answer: They appear as suppressed exceptions on the primary exception.
63. When would you create a custom checked exception versus a custom unchecked exception?
Difficulty: EasyType: SubjectiveTopic: Exceptions
Create a checked exception to force callers to acknowledge a recoverable domain error—like a business rule violation or a missing required configuration. Create an unchecked exception when the failure indicates a programmer mistake or an unexpected state that typical callers cannot handle—like illegal arguments, null misuses, or invariant violations. Use descriptive names and include context in the message.
64. Choose the correct statement.
Difficulty: EasyType: MCQTopic: Exceptions
- throw declares an exception at method signature; throws actually raises it.
- throws declares potential exceptions; throw actually raises one instance.
- Both throw and throws do the same and are interchangeable.
- throws can only list unchecked exceptions.
Use throws in the method signature to advertise possible exceptions; use throw inside code to create and raise a specific exception instance.
Correct Answer: throws declares potential exceptions; throw actually raises one instance.
65. List three exception-handling best practices you follow in production Java services and why.
Difficulty: MediumType: SubjectiveTopic: Best Practices
One: Fail fast with clear messages—include context like IDs and key parameters for quick diagnosis. Two: Do not swallow exceptions—either handle meaningfully or rethrow; always log with level and cause. Three: Use domain-specific exceptions for business errors, and keep stack traces for unexpected faults; map them to proper HTTP or API error codes for clients.
66. Which is the most accurate stance regarding java.lang.Error?
Difficulty: EasyType: MCQTopic: Exceptions
- Catch and retry Errors to improve resilience.
- Treat Errors as fatal conditions not meant to be caught routinely.
- Errors are just another kind of checked exception.
- Errors are thrown only by third-party libraries.
Errors like OutOfMemoryError or StackOverflowError signal serious conditions. They are unchecked and not intended for normal recovery logic.
Correct Answer: Treat Errors as fatal conditions not meant to be caught routinely.
67. What is exception translation and when is it appropriate?
Difficulty: MediumType: SubjectiveTopic: Exceptions
Exception translation means catching a low-level exception and throwing a higher-level, more meaningful one. It’s appropriate when moving across layers—for example, converting SQLException into a domain-specific DataAccessException. Preserve the cause using the constructor so the original stack trace remains available.
68. Which performance guideline is correct?
Difficulty: MediumType: MCQTopic: Performance
- Use exceptions for normal control flow to simplify logic.
- Creating exceptions is cheap and should be preferred to if-else.
- Avoid using exceptions for expected branches; they are relatively expensive.
- Throwing unchecked exceptions is free.
Throwing and capturing exceptions involves filling stack traces and unwinding frames. Use exceptions for exceptional cases, not routine branching.
Correct Answer: Avoid using exceptions for expected branches; they are relatively expensive.
69. Is a try-finally block valid without a catch?
Difficulty: EasyType: MCQTopic: Exceptions
- Yes, it is valid; finally still runs for cleanup.
- No, catch is mandatory.
- Only if the method is synchronized.
- Only for unchecked exceptions.
You can use try-finally to guarantee cleanup when you don’t need to handle the exception locally. The exception propagates after finally runs.
Correct Answer: Yes, it is valid; finally still runs for cleanup.
70. Describe how you implement global exception handling in a Spring Boot REST API and what you return to clients.
Difficulty: HardType: SubjectiveTopic: Exceptions
Use @ControllerAdvice with @ExceptionHandler methods to map exceptions to structured error responses. Return a stable JSON envelope with fields like timestamp, error code, message, and correlation ID. Map domain errors to 4xx with actionable messages; map unexpected faults to 5xx with a generic message and a trace ID. Always log server-side with the cause and context; never leak sensitive details in responses.
71. In modern HotSpot JVMs, which structure does HashMap use when a single bucket becomes too large?
Difficulty: MediumType: MCQTopic: HashMap
- It always keeps a simple linked list.
- It dynamically switches to a balanced tree (red-black) after a threshold.
- It converts the entire table to a skip list.
- It resizes immediately on the first collision.
HashMap maintains a linked list per bucket; when collisions make a bucket long (e.g., ≥8) and capacity is sufficient, it treeifies that bucket into a red-black tree. This improves worst-case lookups from O(n) to O(log n).
Correct Answer: It dynamically switches to a balanced tree (red-black) after a threshold.
72. What triggers a HashMap resize by default?
Difficulty: MediumType: MCQTopic: HashMap
- Number of keys equals current capacity.
- Load factor threshold is exceeded.
- Any collision occurs.
- GC occurs.
HashMap grows when size > capacity × loadFactor (default 0.75). Resizing redistributes entries to a bigger table, keeping average O(1) operations.
Correct Answer: Load factor threshold is exceeded.
73. Pick the correct statement about keys used in HashMap or HashSet.
Difficulty: EasyType: MCQTopic: Equality
- Only hashCode matters; equals is ignored.
- equals may return true even if hash codes differ.
- If equals returns true, hashCode must be equal.
- hashCode must be unique for all objects.
The contract: equal objects must have equal hash codes. Violating it breaks hashing collections, causing lost or duplicate entries. Distinct objects may share a hash code; the map handles collisions.
Correct Answer: If equals returns true, hashCode must be equal.
74. Which statement about ConcurrentHashMap is correct?
Difficulty: MediumType: MCQTopic: Concurrent Coll
- It allows null keys and values.
- Its operations are all globally synchronized.
- Reads are non-blocking; updates use fine-grained synchronization.
- Iterators are fail-fast and always throw on concurrent updates.
ConcurrentHashMap is designed for high concurrency—reads proceed without locking; writes use fine-grained locking or CAS. It disallows null keys and values to avoid ambiguity with missing mappings.
Correct Answer: Reads are non-blocking; updates use fine-grained synchronization.
75. What makes LinkedHashMap different from HashMap?
Difficulty: EasyType: MCQTopic: Maps
- It sorts entries by key using a comparator.
- It maintains insertion or access order via a doubly-linked list.
- It stores entries in a tree by default.
- It doesn’t use hash codes.
LinkedHashMap preserves a predictable iteration order: insertion order by default, or access order when configured for LRU-style caches.
Correct Answer: It maintains insertion or access order via a doubly-linked list.
76. Which is true for TreeMap?
Difficulty: EasyType: MCQTopic: Maps
- It allows one null key and many null values.
- It disallows null keys because it must compare keys.
- It allows unlimited null keys.
- It stores keys by hash order.
TreeMap uses natural ordering or a comparator; null keys cannot be compared and thus are not supported. Null values are allowed.
Correct Answer: It disallows null keys because it must compare keys.
77. What does Collections.unmodifiableList(list) guarantee?
Difficulty: MediumType: MCQTopic: Collections
- It creates a deep copy that cannot change.
- It returns a read-only view; underlying list changes still appear.
- It prevents the original list from being modified by anyone.
- It synchronizes all access.
Unmodifiable wrappers block mutating operations on the view but do not copy data. If the backing list changes elsewhere, the view reflects those changes.
Correct Answer: It returns a read-only view; underlying list changes still appear.
78. Which pair best matches iterator behavior?
Difficulty: MediumType: MCQTopic: Iterators
- ArrayList: fail-safe | ConcurrentHashMap: fail-fast
- ArrayList: fail-fast | ConcurrentHashMap: weakly consistent (fail-safe style)
- Both are fail-safe.
- Both are fail-fast.
Most standard collections have fail-fast iterators that throw on structural modification. ConcurrentHashMap provides weakly consistent iterators that reflect some concurrent changes without throwing.
Correct Answer: ArrayList: fail-fast | ConcurrentHashMap: weakly consistent (fail-safe style)
79. Why can’t you create new T[] inside a generic class in Java?
Difficulty: MediumType: MCQTopic: Generics
- Arrays are deprecated with generics.
- Type erasure removes T at runtime, so the JVM does not know the component type.
- It would be unsafe only for primitive types.
- You can; it compiles with a warning.
Generics are erased at runtime. Arrays need their reified element type. Without it, the JVM can’t enforce type safety for a new T[]. Workarounds include creating Object[] and casting, or using List<T>.
Correct Answer: Type erasure removes T at runtime, so the JVM does not know the component type.
80. According to the PECS rule for wildcards, when should you use ? extends and when ? super?
Difficulty: MediumType: MCQTopic: Generics
- Use extends to consume, super to produce.
- Use extends to produce, super to consume.
- Use extends and super interchangeably.
- Neither affects variance.
PECS: Producer Extends, Consumer Super. If you read items from a structure, use ? extends T. If you insert items into it, use ? super T. This preserves type safety with variance.
Correct Answer: Use extends to produce, super to consume.
81. When do you prefer Comparable over Comparator, and why?
Difficulty: EasyType: SubjectiveTopic: Ordering
Use Comparable when a class has a natural, single ordering—like String or BigDecimal—and you control the source to implement compareTo. Prefer Comparator when you need multiple orderings (e.g., by name, then by date) or you can’t modify the class. Comparator keeps sorting logic separate and flexible.
82. Which is true about PriorityQueue in Java?
Difficulty: EasyType: MCQTopic: Ordering
- Iteration returns elements in priority order.
- peek and poll respect priority, but iteration order is unspecified.
- It requires a balanced tree inside.
- It supports null elements.
PriorityQueue is heap-based: head operations return the minimal (or maximal) element per comparator. Iteration does not guarantee sorted traversal.
Correct Answer: peek and poll respect priority, but iteration order is unspecified.
83. Which pair correctly matches a BlockingQueue method and its behavior when the queue is full?
Difficulty: MediumType: MCQTopic: BlockingQueue
- add: blocks until space is available
- offer: throws IllegalStateException
- put: blocks until space is available
- offer with timeout: throws immediately
For full queues: add throws IllegalStateException, offer returns false, offer(timeout) waits up to the timeout, and put blocks until space is available.
Correct Answer: put: blocks until space is available
84. Explain the difference between an immutable collection and an unmodifiable view, and why it matters.
Difficulty: MediumType: SubjectiveTopic: Immutability
An immutable collection cannot change—no element can be added, removed, or mutated through any reference. An unmodifiable view disallows mutations through that view, but the backing collection may still change elsewhere and those changes will appear. Immutability is safer for sharing across threads and for defensive returns; unmodifiable views are lightweight guards around a mutable source.
85. Why prefer ExecutorService over manually creating threads?
Difficulty: EasyType: MCQTopic: Executors
- It uses fewer CPU cores.
- It pools and reuses threads, provides task submission APIs, lifecycle management, and better error handling.
- It always runs tasks faster than raw threads.
- It guarantees FIFO scheduling.
ExecutorService abstracts thread creation. You submit tasks, not threads; it reuses a pool, limits concurrency, offers futures for results, and supports graceful shutdown. This improves throughput and stability.
Correct Answer: It pools and reuses threads, provides task submission APIs, lifecycle management, and better error handling.
86. Which pool is best for a large number of short, independent CPU-bound tasks on an 8-core machine?
Difficulty: MediumType: MCQTopic: Executors
- newCachedThreadPool()
- newFixedThreadPool(8)
- newSingleThreadExecutor()
- newWorkStealingPool(1)
For CPU-bound tasks, set the pool size near the number of cores to minimize context switches and maximize CPU utilization. Cached pools can oversubscribe threads and degrade performance.
Correct Answer: newFixedThreadPool(8)
87. What is a key benefit of a work-stealing pool (ForkJoinPool)?
Difficulty: MediumType: MCQTopic: ForkJoin
- Guaranteed task ordering.
- Each worker steals tasks from others to balance load, improving parallelism for fine-grained tasks.
- It prevents deadlocks automatically.
- It uses a single global queue for fairness.
ForkJoinPool keeps per-worker deques; when a worker runs out of local tasks, it steals from the tail of another's deque, reducing contention and balancing work for divide-and-conquer algorithms.
Correct Answer: Each worker steals tasks from others to balance load, improving parallelism for fine-grained tasks.
88. How does CompletableFuture improve on Future?
Difficulty: MediumType: MCQTopic: Futures
- It only supports blocking get().
- It adds completion callbacks, non-blocking composition, and chaining of dependent stages.
- It runs only on a single thread.
- It cannot be combined with ExecutorService.
CompletableFuture supports async pipelines (thenApply, thenCompose), timeouts, combining results, and completion actions without blocking. It works with default or custom executors.
Correct Answer: It adds completion callbacks, non-blocking composition, and chaining of dependent stages.
89. AtomicInteger.incrementAndGet() is implemented using:
Difficulty: EasyType: MCQTopic: Atomics
- Global locks
- Wait/notify
- CAS (Compare-And-Set) with CPU atomics
- Synchronized blocks on Integer.class
java.util.concurrent.atomic uses lock-free algorithms built on CAS instructions. They retry on contention instead of blocking, reducing context switching.
Correct Answer: CAS (Compare-And-Set) with CPU atomics
90. One advantage of ReentrantLock over synchronized is:
Difficulty: MediumType: MCQTopic: Locks
- It is always faster in every scenario.
- It supports fairness policies, tryLock with timeout, and interruptible lock acquisition.
- It avoids all deadlocks automatically.
- It guarantees reentrancy is impossible.
ReentrantLock provides advanced features: timed/interruptible acquisition, optional fairness, and separate Lock/Condition objects. Performance depends on the workload; it’s not universally faster.
Correct Answer: It supports fairness policies, tryLock with timeout, and interruptible lock acquisition.
91. When does ReentrantReadWriteLock help most?
Difficulty: MediumType: MCQTopic: Locks
- When writes vastly outnumber reads.
- When reads dominate and can proceed concurrently while no writer holds the lock.
- When tasks are CPU bound.
- When fairness isn’t desired.
Read-write locks allow many readers to proceed in parallel, blocking only when a writer acquires the write lock. This improves throughput in read-heavy workloads.
Correct Answer: When reads dominate and can proceed concurrently while no writer holds the lock.
92. Name two practical strategies to prevent deadlocks in Java code.
Difficulty: EasyType: SubjectiveTopic: Deadlocks
One: Impose a strict global lock ordering and acquire locks in that order everywhere. Two: Use tryLock with timeout and back off if you can’t acquire all locks. Other options: minimize lock scope, prefer immutable data, or replace coarse locks with higher-level concurrency utilities.
93. Which statement is true about BlockingQueue?
Difficulty: EasyType: MCQTopic: BlockingQueue
- put blocks if the queue is full; take blocks if the queue is empty.
- add blocks if the queue is full.
- offer always blocks.
- remove blocks if the queue is empty.
Blocking queues coordinate producers and consumers. put waits for space; take waits for data. offer/add/remove have different, non-blocking behaviors and may fail or throw.
Correct Answer: put blocks if the queue is full; take blocks if the queue is empty.
94. Why provide a custom ThreadFactory to an Executor?
Difficulty: MediumType: MCQTopic: Executors
- To make threads faster.
- To control thread names, priority, daemon status, UncaughtExceptionHandler, and context class loader.
- To eliminate synchronization.
- To force single-thread execution.
A ThreadFactory standardizes thread characteristics across a pool, aiding debugging, monitoring, and safe error handling for uncaught exceptions.
Correct Answer: To control thread names, priority, daemon status, UncaughtExceptionHandler, and context class loader.
95. What is a practical use of a Semaphore in Java?
Difficulty: MediumType: MCQTopic: Sync Tools
- Replacing the GC.
- Limiting concurrent access to a finite resource, like 10 database connections.
- Ensuring strict FIFO scheduling of tasks.
- Eliminating race conditions without locks.
Semaphores manage permits. Threads acquire a permit before proceeding and release it afterward, capping concurrency to available resources.
Correct Answer: Limiting concurrent access to a finite resource, like 10 database connections.
96. What makes Phaser more flexible than CountDownLatch or CyclicBarrier?
Difficulty: HardType: MCQTopic: Sync Tools
- It is always faster.
- It supports dynamic registration and multi-phase coordination with onAdvance hooks.
- It uses no synchronization.
- It guarantees fairness among parties.
Phaser allows parties to register and deregister at runtime and supports multiple synchronization phases with custom phase-advance logic, making it a superset of many barrier patterns.
Correct Answer: It supports dynamic registration and multi-phase coordination with onAdvance hooks.
97. Explain what volatile guarantees and when it’s insufficient.
Difficulty: MediumType: SubjectiveTopic: Volatile
volatile guarantees visibility and ordering for a single variable: writes by one thread become visible to others, and reads/writes are not reordered across that variable. It does NOT make compound actions atomic (like ++), nor does it protect invariants across multiple variables. Use locks or atomics for atomicity and compound state changes.
98. Which sequence cleanly shuts down an ExecutorService?
Difficulty: EasyType: MCQTopic: Executors
- shutdownNow(); awaitTermination();
- awaitTermination(); shutdown();
- shutdown(); awaitTermination(timeout); then shutdownNow() if needed.
- System.exit(0).
Call shutdown to reject new tasks and let running tasks finish. Await for a bounded time. If tasks still run, call shutdownNow to interrupt and drain the queue. This avoids leaks and dangling threads.
Correct Answer: shutdown(); awaitTermination(timeout); then shutdownNow() if needed.
99. What does the Java Memory Model (JMM) primarily define?
Difficulty: EasyType: MCQTopic: JMM
- How objects are laid out in physical RAM.
- Rules for visibility and ordering of reads and writes between threads.
- Exact CPU cache sizes for HotSpot.
- How the garbage collector compacts memory.
The JMM specifies when a thread’s write becomes visible to other threads and which re-orderings are allowed. It’s about visibility and happens-before guarantees, not physical layouts or GC details.
Correct Answer: Rules for visibility and ordering of reads and writes between threads.
100. Which pair creates a happens-before relationship under the JMM?
Difficulty: MediumType: MCQTopic: JMM
- Two writes to the same field from different threads.
- A call to unlock on a monitor followed by a later lock of the same monitor by another thread.
- Two concurrent reads of a volatile variable.
- Two independent computations with no shared data.
Releasing a monitor happens-before the subsequent acquire of that monitor by another thread. This ensures visibility of changes made inside the critical section.
Correct Answer: A call to unlock on a monitor followed by a later lock of the same monitor by another thread.
101. What does 'volatile' guarantee in Java?
Difficulty: EasyType: MCQTopic: Volatile
- Atomicity for compound operations like ++.
- That a value is stored only on the heap.
- Visibility of writes to other threads and ordering around the volatile variable.
- Better performance than synchronized.
volatile publishes the latest value to all threads and prevents certain re-orderings. It does not make compound updates atomic; use locks or atomics for that.
Correct Answer: Visibility of writes to other threads and ordering around the volatile variable.
102. How can HotSpot’s escape analysis improve performance?
Difficulty: MediumType: MCQTopic: JVM Tuning
- By turning all objects into primitives.
- By allocating non-escaping objects on the stack and eliminating locks that don’t escape.
- By disabling JIT compilation for small methods.
- By forcing GC to run less often.
If an object never escapes a method or thread, the JIT can allocate it on the stack (scalar replacement) and remove unnecessary synchronization, reducing GC pressure and contention.
Correct Answer: By allocating non-escaping objects on the stack and eliminating locks that don’t escape.
103. Why separate the heap into young and old generations?
Difficulty: EasyType: MCQTopic: GC Basics
- To store Strings separately.
- Most objects die young, so collecting the young generation frequently is cheap and reduces work on long-lived objects.
- To increase pause times deliberately.
- Because the JMM requires it.
Generational hypothesis: new objects tend to be short-lived. Minor collections reclaim them quickly, while the old generation is collected less often.
Correct Answer: Most objects die young, so collecting the young generation frequently is cheap and reduces work on long-lived objects.
104. Which statement best distinguishes G1 from CMS?
Difficulty: MediumType: MCQTopic: GC Basics
- G1 is single-threaded; CMS is parallel.
- G1 divides the heap into regions and performs mostly concurrent, incremental collections with predictable pause targets.
- G1 is only for small heaps.
- CMS compacts on every cycle.
G1 uses regions and mixed collections to meet pause goals. CMS is concurrent but largely non-compacting and can suffer fragmentation.
Correct Answer: G1 divides the heap into regions and performs mostly concurrent, incremental collections with predictable pause targets.
105. What is the primary goal of ZGC and Shenandoah collectors?
Difficulty: MediumType: MCQTopic: GC Basics
- Maximum throughput at any pause cost.
- Ultra-low pause times via concurrent relocation and load barriers.
- Simplest implementation.
- Best performance on 32-bit JVMs.
Both aim for sub-millisecond pauses by doing most GC work concurrently and using barriers to keep mutators running while objects move.
Correct Answer: Ultra-low pause times via concurrent relocation and load barriers.
106. You observe long GC pauses in production. Outline a pragmatic 4-step tuning approach before changing the collector.
Difficulty: MediumType: SubjectiveTopic: JVM Tuning
One: Measure first—enable GC logs and capture p99 latency and allocation rates. Two: Fix allocation hot spots—reduce temporary objects, reuse buffers, enable pooling only if profiling proves it. Three: Right-size the heap and young generation to match live-set and allocation rate. Four: Set realistic pause goals (e.g., G1 MaxGCPauseMillis) and re-measure. Only then consider switching collectors (e.g., to ZGC) if goals still aren’t met.
107. Which pairing correctly matches reference type to its typical use?
Difficulty: HardType: MCQTopic: Soft/Weak/Phantom
- SoftReference → canonicalization map keys
- WeakReference → memory-sensitive caches that may be cleared eagerly
- PhantomReference → direct retrieval of referent before GC
- Strong reference → avoid memory leaks in caches
Weak references allow GC to reclaim entries aggressively—good for caches with no hard retention. Soft references are less aggressively reclaimed (historically for caches, though guidance now favors explicit policies). Phantom references are for post-mortem cleanup with ReferenceQueue; you cannot get the referent.
Correct Answer: WeakReference → memory-sensitive caches that may be cleared eagerly
108. Why is finalization discouraged and what’s the modern alternative?
Difficulty: MediumType: MCQTopic: Finalization & Cleaner
- It’s faster; use it for all cleanups.
- Finalizers run immediately; there is no risk.
- Finalizers are unpredictable and can resurrect objects; prefer try-with-resources or java.lang.ref.Cleaner for non-memory resources.
- There is no alternative.
Finalizers run at GC’s discretion and can cause leaks or latency spikes. Use explicit close patterns or Cleaner for safety and determinism.
Correct Answer: Finalizers are unpredictable and can resurrect objects; prefer try-with-resources or java.lang.ref.Cleaner for non-memory resources.
109. Explain why reducing allocation rate often improves latency even if throughput is unchanged.
Difficulty: MediumType: SubjectiveTopic: JVM Tuning
High allocation rates trigger more frequent young GCs and fill survivor/old regions faster, increasing pauses and promotion failures. Fewer temporary objects mean fewer barriers and less pressure on remembered sets. Lower churn gives the GC time to work concurrently, reducing pause frequency and tail latencies.
110. What is a safepoint and why might long time-to-safepoint (TTSP) spikes occur?
Difficulty: HardType: MCQTopic: GC Basics
- A point where threads speed up; TTSP spikes mean GC runs too often.
- A JVM point where all threads reach a known state so the VM can perform actions like GC; TTSP spikes can occur due to long non-interruptible native calls or tight loops without polls.
- A network checkpoint; TTSP depends on I/O.
- A classloading barrier; TTSP spikes indicate metaspace exhaustion.
At safepoints the JVM halts mutator threads. If a thread can’t poll (e.g., busy native call or hot loop with eliminated polls), the VM waits, inflating pause time.
Correct Answer: A JVM point where all threads reach a known state so the VM can perform actions like GC; TTSP spikes can occur due to long non-interruptible native calls or tight loops without polls.
111. What does G1 String Deduplication do?
Difficulty: MediumType: MCQTopic: Strings
- Interns every String automatically.
- Merges identical char[] or byte[] backing arrays across different String instances to reduce heap usage.
- Forces all Strings into the old generation.
- Disables string interning.
It identifies duplicate string contents and shares a single backing array, cutting memory footprint when many equal strings exist. It’s orthogonal to String.intern().
Correct Answer: Merges identical char[] or byte[] backing arrays across different String instances to reduce heap usage.
112. What is Metaspace and a common cause of it growing unexpectedly?
Difficulty: EasyType: SubjectiveTopic: JVM Memory
Metaspace holds class metadata (replacing PermGen). A common growth cause is classloader leaks—dynamically loading classes without unloading their defining classloader, often seen in hot-reloaded apps or container redeploys. Each leaked classloader pins its classes and metadata, expanding Metaspace.
113. What makes an interface a functional interface in Java?
Difficulty: EasyType: MCQTopic: Lambdas
- It contains only default methods.
- It has exactly one abstract method (SAM), regardless of default or static methods.
- It is annotated with @FunctionalInterface.
- It extends java.util.function.Function.
A functional interface is defined by a single abstract method. @FunctionalInterface is optional and only enforces the rule at compile time. Default and static methods don’t change the SAM count.
Correct Answer: It has exactly one abstract method (SAM), regardless of default or static methods.
114. Which is TRUE about lambdas compared to anonymous inner classes?
Difficulty: MediumType: MCQTopic: Lambdas
- Lambdas always create a new class at runtime.
- Lambdas capture effectively final variables from the enclosing scope.
- Lambdas allow multiple abstract methods.
- Lambdas can only target Runnable.
Lambdas close over effectively final variables, just like anonymous classes. They do not require generating a new class per use and can target any compatible functional interface.
Correct Answer: Lambdas capture effectively final variables from the enclosing scope.
115. Which method reference form refers to an instance method of a particular object?
Difficulty: EasyType: MCQTopic: Lambdas
- TypeName::staticMethod
- TypeName::instanceMethod
- objectRef::instanceMethod
- TypeName::new
There are four forms: static, instance of particular object, instance of arbitrary object of a particular type, and constructor. `objectRef::instanceMethod` is the particular object form.
Correct Answer: objectRef::instanceMethod
116. A Stream pipeline is composed of:
Difficulty: EasyType: MCQTopic: Streams
- Only intermediate operations
- Only a source and terminal operation
- A source, zero or more intermediate operations, and one terminal operation
- Multiple sources and multiple terminals
Streams are lazy: intermediate steps are recorded until a terminal operation triggers evaluation. There’s exactly one terminal operation per pipeline.
Correct Answer: A source, zero or more intermediate operations, and one terminal operation
117. Which pair correctly classifies operations?
Difficulty: MediumType: MCQTopic: Streams
- map, filter → terminal; collect → intermediate
- map, filter, sorted → intermediate; collect, reduce, forEach → terminal
- peek → terminal; allMatch → intermediate
- reduce → intermediate; limit → terminal
Mapping, filtering, sorting build the pipeline; collect, reduce, forEach consume it. `peek` is intermediate and `allMatch` is terminal.
Correct Answer: map, filter, sorted → intermediate; collect, reduce, forEach → terminal
118. When should you use flatMap instead of map?
Difficulty: MediumType: MCQTopic: Streams
- When transforming each element to exactly one element.
- When mapping each element to a stream or collection and you want a single flattened stream.
- When you need a terminal operation.
- When you want to preserve duplicates.
Use `map` for one-to-one transformations. Use `flatMap` for one-to-many where inner streams or collections are concatenated into a single stream.
Correct Answer: When mapping each element to a stream or collection and you want a single flattened stream.
119. Which operation is stateful and may require examining the whole stream?
Difficulty: HardType: MCQTopic: Streams
`distinct` tracks seen elements to remove duplicates, requiring state. `sorted` is also stateful. `filter`, `map`, and `peek` are stateless.
Correct Answer: distinct
120. Which is a safe guideline for using parallel streams?
Difficulty: HardType: MCQTopic: Streams
- Use parallel() by default; it is always faster.
- Prefer parallel streams when workloads are CPU-bound, data is large, operations are stateless, non-blocking, and order is not critical.
- Use parallel streams for I/O-heavy tasks to hide latency.
- Use parallel streams inside synchronized blocks.
Parallelism shines on big, CPU-bound, pure operations with minimal coordination. Blocking I/O, synchronization, or strict encounter order often negate benefits or harm performance.
Correct Answer: Prefer parallel streams when workloads are CPU-bound, data is large, operations are stateless, non-blocking, and order is not critical.
121. What does Collectors.groupingBy do by default?
Difficulty: MediumType: MCQTopic: Collectors
- Groups elements by a classifier into a Map with List values.
- Removes duplicates then groups.
- Sorts groups by keys automatically.
- Creates a ConcurrentMap in all cases.
Default `groupingBy(classifier)` uses a `HashMap<K, List<T>>`. Sorting or concurrent maps require additional downstream or mapFactory arguments.
Correct Answer: Groups elements by a classifier into a Map with List values.
122. When should you prefer collect over reduce?
Difficulty: HardType: MCQTopic: Collectors
- When combining into mutable containers like lists, maps, or StringBuilder.
- When computing associative numeric results.
- When you need short-circuiting.
- When you need no identity element.
`collect` is built for mutable result containers and supports parallel-friendly accumulation and combination. `reduce` targets immutable, associative reductions.
Correct Answer: When combining into mutable containers like lists, maps, or StringBuilder.
123. List two good practices and two anti-patterns when using Optional in Java.
Difficulty: EasyType: SubjectiveTopic: Optional
Good: return Optional from methods that may be empty; use terminal operations like orElse, orElseGet, orElseThrow instead of get(). Good: chain map/flatMap/filter to avoid nested ifs. Anti-patterns: use Optional for fields or parameters (adds overhead and ambiguity); call get() without checking presence; use Optional in performance-critical collections.
124. Which statement about encounter order is correct?
Difficulty: MediumType: MCQTopic: Streams
- Streams are always ordered.
- If the source is unordered (e.g., HashSet), operations like forEach may visit elements in any order unless you enforce ordering.
- sorted() has no effect on order.
- parallel() guarantees original order.
Encounter order is defined by the source; unordered sources can produce arbitrary visitation order. Use `sorted` or ordered sources (e.g., List, LinkedHashSet) when order matters, or `forEachOrdered` in parallel.
Correct Answer: If the source is unordered (e.g., HashSet), operations like forEach may visit elements in any order unless you enforce ordering.
125. Why use IntStream/LongStream/DoubleStream?
Difficulty: EasyType: MCQTopic: Streams
- They allow inheritance.
- They avoid boxing overhead and provide numeric-specific operations like sum and average.
- They allow null primitives.
- They are required for parallelism.
Primitive streams save allocations and add numeric terminals (sum, average, min, max). They convert via mapToInt, mapToLong, mapToDouble and boxed().
Correct Answer: They avoid boxing overhead and provide numeric-specific operations like sum and average.
126. Why are side effects inside Stream intermediate operations discouraged, and what should you use instead?
Difficulty: MediumType: SubjectiveTopic: Streams
Side effects (e.g., mutating external state in map/filter) break referential transparency, hinder parallelization, and cause subtle bugs. Prefer pure functions and let `collect` build results. If you must observe, use `peek` only for diagnostics; for imperative accumulation, a simple loop may be clearer.
127. What happens if you try to run two terminal operations on the same Stream instance?
Difficulty: EasyType: MCQTopic: Streams
- Both succeed and share the same data.
- The second terminal operation throws IllegalStateException: stream has already been operated upon or closed.
- The second returns an empty result.
- The stream restarts automatically.
Streams are single-use. Create a new stream from the source for additional terminals, or collect data to a reusable structure first.
Correct Answer: The second terminal operation throws IllegalStateException: stream has already been operated upon or closed.
128. Which statement is TRUE about creating threads in Java?
Difficulty: EasyType: MCQTopic: Threads
- Extending Thread is the only supported way.
- Implementing Runnable decouples task from thread and is generally preferred.
- Threads must always be started with run().
- A thread can be restarted after it terminates.
Runnable separates the work from the execution mechanism, allowing reuse with pools and avoiding subclassing limits. You start a thread with start(), which calls run() internally. A terminated thread cannot be restarted.
Correct Answer: Implementing Runnable decouples task from thread and is generally preferred.
129. Calling run() directly on a Thread instance will:
Difficulty: EasyType: MCQTopic: Threads
- Start a new thread of execution.
- Throw an IllegalStateException.
- Execute synchronously on the current thread.
- Schedule it on the ForkJoinPool.
Only start() creates a new OS-level thread managed by the JVM. Calling run() is just a normal method call on the current thread.
Correct Answer: Execute synchronously on the current thread.
130. What does the synchronized keyword guarantee?
Difficulty: MediumType: MCQTopic: Locks
- Only atomicity.
- Only visibility.
- Atomicity and visibility for the guarded critical section, with mutual exclusion per monitor.
- Fair scheduling among waiting threads.
Entering a synchronized block acquires the monitor; exiting establishes a happens-before edge that flushes writes to main memory. It ensures mutual exclusion and visibility but not fairness.
Correct Answer: Atomicity and visibility for the guarded critical section, with mutual exclusion per monitor.
131. Which is a correct use case for volatile?
Difficulty: MediumType: MCQTopic: Volatile
- Protecting compound actions like i++ under contention.
- Publishing a stop flag that multiple threads read frequently.
- Guarding a critical section instead of synchronized.
- Ensuring fairness in lock acquisition.
volatile provides visibility and ordering for single-variable reads/writes. It does not provide atomicity for compound operations like increment; use synchronization or atomic classes for that.
Correct Answer: Publishing a stop flag that multiple threads read frequently.
132. Which advantage can ReentrantLock provide over synchronized?
Difficulty: MediumType: MCQTopic: Locks
- Automatic fairness by default.
- Ability to attempt timed/non-blocking lock acquisition and to interrupt lock waits.
- Lower memory footprint in all cases.
- It prevents deadlocks automatically.
ReentrantLock supports tryLock (with or without timeout) and lockInterruptibly, plus optional fairness policy at construction. It does not inherently prevent deadlocks.
Correct Answer: Ability to attempt timed/non-blocking lock acquisition and to interrupt lock waits.
133. What is the primary benefit of using an ExecutorService?
Difficulty: EasyType: MCQTopic: Executors
- It guarantees tasks run in submission order.
- It manages thread creation, reuse, and shutdown, decoupling task submission from execution.
- It prevents race conditions automatically.
- It enforces time limits for all tasks.
Executors pool and reuse threads, reducing overhead and providing lifecycle control. Ordering and mutual exclusion are not guaranteed unless you choose specific executors or add your own coordination.
Correct Answer: It manages thread creation, reuse, and shutdown, decoupling task submission from execution.
134. What does Future.get() do by default if the task is not complete?
Difficulty: MediumType: MCQTopic: Futures
- Returns null immediately.
- Throws TimeoutException.
- Blocks until the task completes or throws due to interruption/cancellation/failure.
- Cancels the task then returns.
Future.get() is a blocking wait. Use the timed overload to bound waiting, and handle InterruptedException, ExecutionException, or CancellationException.
Correct Answer: Blocks until the task completes or throws due to interruption/cancellation/failure.
135. Which pair correctly describes composition methods?
Difficulty: HardType: MCQTopic: Futures
- thenApply transforms value synchronously; thenCompose flattens a future-of-future pipeline.
- thenApply runs on a new thread; thenRun passes the prior result to a Runnable.
- thenAccept returns a value; handle never sees exceptions.
- allOf returns List<T> of results.
thenApply maps a result; thenCompose chains async stages avoiding nested futures. thenRun ignores the value; handle observes both result and exception. allOf returns a CompletableFuture<Void>.
Correct Answer: thenApply transforms value synchronously; thenCompose flattens a future-of-future pipeline.
136. When should AtomicInteger be preferred over synchronized increments?
Difficulty: MediumType: MCQTopic: Atomics
- Always, regardless of contention and behavior needed.
- When you need lock-free, thread-safe, single-variable updates with CAS semantics.
- When you need to update multiple related fields atomically.
- When fairness between threads is required.
Atomic classes provide non-blocking, single-variable atomicity. They do not group multiple variables atomically; for that, use locks or higher-level constructs.
Correct Answer: When you need lock-free, thread-safe, single-variable updates with CAS semantics.
137. Define deadlock in Java concurrency and list two practical strategies to avoid it.
Difficulty: MediumType: SubjectiveTopic: Deadlocks
Deadlock occurs when threads hold locks the others need, and none can proceed. Avoidance strategies: 1) Establish a global lock ordering and always acquire locks in that order. 2) Use tryLock with timeout to detect and back off. Additional tips: minimize lock scope, prefer immutable data, and use higher-level concurrent structures.
138. What makes BlockingQueue useful for producer–consumer designs?
Difficulty: EasyType: MCQTopic: BlockingQueue
- It guarantees FIFO ordering and fairness.
- put and take block automatically when full or empty, coordinating producers and consumers without custom wait/notify.
- It executes tasks in parallel.
- It eliminates the need for any locks in the JVM.
Blocking queues provide built-in backpressure: producers wait when full, consumers wait when empty. Fairness and ordering depend on the specific implementation.
Correct Answer: put and take block automatically when full or empty, coordinating producers and consumers without custom wait/notify.
139. Which statement best characterizes the Fork/Join framework?
Difficulty: HardType: MCQTopic: ForkJoin
- It’s only for I/O-bound tasks.
- It uses work-stealing to balance fine-grained, CPU-bound tasks across worker threads.
- It guarantees deterministic order of task completion.
- It replaces all ExecutorService use cases.
Fork/Join targets divide-and-conquer algorithms. Workers steal tasks from others’ deques to stay busy. It’s not intended for I/O-heavy workloads nor does it preserve order.
Correct Answer: It uses work-stealing to balance fine-grained, CPU-bound tasks across worker threads.
140. Name three design techniques to achieve thread safety without heavy locking, and briefly explain why they help.
Difficulty: MediumType: SubjectiveTopic: Thread Safety
1) Immutability: immutable objects can be shared freely—no races on state. 2) Confinement: keep mutable state confined to a single thread (e.g., ThreadLocal or task confinement) to avoid sharing. 3) Stateless functions and message passing: prefer pure functions; exchange data via queues, reducing shared mutable state. These reduce contention and simplify reasoning.
141. Which pairing is CORRECT for Java I/O families?
Difficulty: EasyType: MCQTopic: Java IO
- InputStream/OutputStream → character data; Reader/Writer → byte data
- InputStream/OutputStream → byte data; Reader/Writer → character data
- Both families are interchangeable without adapters
- Reader/Writer cannot be buffered
Stream classes move raw bytes; Reader/Writer classes decode and encode characters using a charset. They’re not interchangeable, but bridges like InputStreamReader and OutputStreamWriter adapt bytes to characters and vice-versa.
Correct Answer: InputStream/OutputStream → byte data; Reader/Writer → character data
142. Why wrap file streams in buffered variants like BufferedInputStream or BufferedReader?
Difficulty: EasyType: MCQTopic: Java IO
- To compress data automatically
- To reduce costly kernel calls by reading or writing larger chunks
- To enforce thread safety
- To change the file’s encoding
Buffering batches I/O into fewer, larger operations, which is faster than many tiny reads and writes. It doesn’t add compression, thread safety, or change encodings by itself.
Correct Answer: To reduce costly kernel calls by reading or writing larger chunks
143. What is the safest way to ensure text is read with a specific encoding?
Difficulty: MediumType: MCQTopic: Java IO
- Use FileReader because it detects BOM and encoding automatically
- Use InputStreamReader with an explicit Charset, such as UTF_8
- Set a JVM flag once and rely on the platform default
- Encoding doesn’t matter when using Reader
Platform defaults vary and can break portability. Always specify the charset explicitly when converting bytes to characters to avoid mojibake and subtle data loss.
Correct Answer: Use InputStreamReader with an explicit Charset, such as UTF_8
144. Which statement about java.nio.file.Path and Files is TRUE?
Difficulty: MediumType: MCQTopic: NIO
- Path always represents an existing file
- Files.walk returns a lazily traversed stream that must be closed
- Paths.get returns an absolute path only
- Files.readAllLines streams the file without loading into memory
Files.walk produces a Stream that must be closed (try-with-resources). Path can represent non-existing locations; Paths.get can be relative. readAllLines loads all content into memory.
Correct Answer: Files.walk returns a lazily traversed stream that must be closed
145. How do you efficiently read basic file attributes (size, times) without opening the file contents?
Difficulty: MediumType: MCQTopic: NIO
- Use new FileInputStream(path) and check channel size
- Use Files.readAttributes(path, BasicFileAttributes.class)
- Read the first byte only
- It is not possible; reading requires opening contents
NIO.2 exposes metadata via attribute views like BasicFileAttributes and PosixFileAttributes without reading file payloads, which is lightweight and efficient.
Correct Answer: Use Files.readAttributes(path, BasicFileAttributes.class)
146. What does WatchService in NIO.2 provide?
Difficulty: MediumType: MCQTopic: NIO
- Guaranteed real-time notifications for every single file change
- Directory change notifications with events like CREATE, DELETE, MODIFY
- Automatic content diffing for changed files
- Cross-machine file replication
WatchService lets you register a directory for change events. It’s best effort, may coalesce events, and is not a content diff tool or replication system.
Correct Answer: Directory change notifications with events like CREATE, DELETE, MODIFY
147. Which advantage do Channels with ByteBuffer have over classic streams?
Difficulty: HardType: MCQTopic: NIO
- They automatically compress data
- They support non-blocking I/O and efficient bulk transfers, mapping well to OS primitives
- They remove the need for buffering
- They guarantee higher throughput regardless of workload
Channels integrate with selectors and ByteBuffers for non-blocking or zero-copy patterns, allowing efficient, scalable I/O. Throughput still depends on workload and hardware.
Correct Answer: They support non-blocking I/O and efficient bulk transfers, mapping well to OS primitives
148. When is a memory-mapped file (MappedByteBuffer) a good fit?
Difficulty: HardType: MCQTopic: NIO
- For tiny files only
- When random access to very large files is needed and OS page cache can help
- When you need automatic transactional writes
- When you must avoid any native resources
Memory mapping lets the OS page data on demand and can be very fast for large random access workloads. It uses native resources and requires careful unmapping and bounds handling.
Correct Answer: When random access to very large files is needed and OS page cache can help
149. What enables default Java serialization of a class?
Difficulty: EasyType: MCQTopic: Serialization
- Implementing java.io.Serializable
- Overriding toString()
- Extending ObjectOutputStream
- Annotating fields with @Serial
Default Java object serialization activates when a class implements Serializable. You can customize via writeObject/readObject, but the marker interface is the trigger.
Correct Answer: Implementing java.io.Serializable
150. Why should you declare serialVersionUID explicitly?
Difficulty: MediumType: MCQTopic: Serialization
- To compress the stream
- To control compatibility across versions and avoid InvalidClassException when the compiler’s computed value would differ
- To enable encryption during serialization
- To skip transient fields
serialVersionUID is a version stamp. Declaring it stabilizes compatibility decisions across builds and code changes. It has nothing to do with compression or encryption.
Correct Answer: To control compatibility across versions and avoid InvalidClassException when the compiler’s computed value would differ
151. Which combination best describes controlling serialized state?
Difficulty: MediumType: MCQTopic: Serialization
- Use transient to include a field; writeReplace to skip it
- Use transient to exclude a field; customize with writeObject/readObject for special handling
- Use @Override on toString to change serialized bytes
- Serialization always writes all fields regardless
Mark sensitive or derived fields transient to omit them. For tailored behavior, implement private writeObject/readObject hooks to transform, validate, or reconstruct state.
Correct Answer: Use transient to exclude a field; customize with writeObject/readObject for special handling
152. Why is native Java serialization considered risky in modern systems, and what safer alternatives can you use?
Difficulty: MediumType: SubjectiveTopic: Serialization
Deserialization can trigger gadget chains leading to remote code execution when untrusted data is accepted; the object graph is opaque, brittle across versions, and slow. Safer options: JSON or CBOR with vetted mappers, ProtoBuf/Avro/FlatBuffers for schema-driven, version-tolerant formats, or dedicated DTOs with explicit parsing. If you must deserialize, enable object filters (JEP 290), restrict classes, and do input validation.
153. With NIO.2, which statements are TRUE?
Difficulty: EasyType: MCQTopic: NIO
- Files.copy can overwrite by default
- Files.move can perform an atomic move when supported by the filesystem
- Files.copy always preserves attributes
- Files.move cannot replace an existing target
Use CopyOption flags to control behavior. For example, REPLACE_EXISTING to overwrite, COPY_ATTRIBUTES to preserve metadata, and ATOMIC_MOVE for all-or-nothing moves when supported.
Correct Answer: Files.move can perform an atomic move when supported by the filesystem
154. Explain why try-with-resources is preferred for I/O and give two practical benefits.
Difficulty: EasyType: SubjectiveTopic: Resources
It guarantees timely, exception-safe closing of Closeable and AutoCloseable resources. Benefits: 1) Avoids leaks by closing even when exceptions occur. 2) Keeps code concise and readable; suppressed exceptions are preserved, aiding debugging.