Comprehensive Java Interview Practice Question Set Covering Core Concepts to Advanced Topics
Core Java Syntax & Language Features
- Which 8 primitive data types does Java support?
- How do reference equality (
==) and logical object equality (equals()) differ? - Explain the distinct roles of
final,finally, andfinalize(). What happened tofinalize()in modern Java versions? - What behaviors do
staticfields, methods, nested classes, and initializers enable? - Define autoboxing and unboxing, and list a common performance pitfall associated with them.
- When does Java perform automatic type promotion, and when is explicit casting required? What risks come with explicit casting?
- Is
Stringan immutable type? Justify your answer and explain why this design choice was made. - Compare
String,StringBuilder, andStringBufferin terms of mutability, thread safety, and performance. - What are Java’s wrapper classes, and why were they introduced alongside primitives?
- What effect does the
transientmodifier have on instance variables? - List and explain the two core guarantees provided by the
volatilekeyword. Can it solve all concurrency issues? - How does the
instanceofoperator work, and what Java 16+ enhancement simplifies its usage? - Differentiate between
superandthiskeywords in Java. - What is Java’s default access modifier, and what visibility does it grant?
- How do constructors differ from regular instance or static methods?
- Contrast local variables and member variables in terms of scope, initialization requirements, memory location, and access modifiers.
- Outline the key differences between interfaces and abstract classes. When should you choose one over the other?
- Define polymorphism in Java, and provide a concise, working example of both compile-time and runtime polymorphism.
- Distinguish between method overloading and method overriding, including rules and use cases for each.
- Reiterate Java’s wrapper classes and their corresponding primitive types.
- What is the difference between
breakandcontinuestatements, and how do labeled versions extend their functionality? - Explain how to declare and use Java enums, including adding methods, fields, and constructors to them.
- What is the contractual relationship between
hashCode()andequals()? What issues arise if this contract is violated? - Name and briefly describe the most commonly used methods from
java.lang.Object. - Draw or describe Java’s checked/unchecked exception hierarchy, starting from
Throwable. - What are checked exceptions, unchecked exceptions, and errors? When should each be thrown or handled?
- Walk through how to create both checked and unchecked custom exceptions.
- How does
try-with-resourcessimplify resource management? What requirement must resources meet to be used with it? - What is the purpose of the
assertkeyword, and why is it disabled by default in production environments? - How do
packagedeclarations organize Java code, and what naming conventions are typically followed? - Differentiate between
packageandimportstatements, including what each does and does not do. - What is the primary function of
Class.forName()? Provide a common historical use case and note its modern alternatives. - How do
getClass()andClass.forName()differ in terms of class loading behavior and initialization? - What does the
clone()method do, and what interface must a class implement to support it? - Explain shallow copying versus deep copying in Java, and list common implementation approaches for each.
- What was the original intended role of
finalize(), and why is it deprecated as of Java 9? - What happens when
System.gc()is called? Does it guarantee garbage collection will occur immediately? - Name 8-10 commonly used methods from
java.lang.Math. - Compare
java.util.Randomandjava.util.concurrent.ThreadLocalRandom, focusing on thread safety and performance in multi-threaded environments. - What utility do
java.util.Arraysandjava.util.Collectionsprovide? Give 3-5 examples of key methods from each. - What problem does
java.util.Optionalsolve, and what best practices should you follow when using it? - List 6-8 major features introduced in Java 8.
- Explain the syntax and structure of a Java 8 Lambda expression, and identify functional interfaces as their target types.
- Differentiate between intermediate and terminal operations in Java 8 Streams, and provide 2-3 examples of each.
- What are Java method references, and what are the four main types? Give examples of each.
- Compare
Predicate<T>,Function<T,R>, andConsumer<T>functional interfaces, including their method signatures and use cases. - What are
defaultmethods in interfaces, and why were they added in Java 8? - What is the
varkeyword (Java 10+), and what restrictions apply to its usage? - What are
recordclasses (Java 16+), and what boilerplate code do they automatically generate? - Explain Java’s module system (Java 9+), including its core goals and key components like
module-info.java.
Java Collections Framework
- What is the fundamental difference between
java.util.Collectionandjava.util.Map? - Compare
List,Set, andMapinterfaces in terms of element ordering, duplicates, and key-value pairing. - Explain the internal structures and performance characteristics of
ArrayListandLinkedList, and list ideal use cases for each. - Contrast
HashMapandHashtable, noting whyHashtableis considered legacy. - Describe the internal structure of
HashMapin Java 8+, including buckets, nodes, trees, and the threshold for treeification. - How does
HashMapresolve hash collisions, and what improvement did Java 8 make over earlier versions? - What is the load factor of
HashMap, and how does it balance memory usage and performance? What is the default value? - Explain the
HashMapresizing trigger and process, including rehashing behavior in Java 8+. - Is
HashMapthread-safe? What issues can arise if it is modified concurrently without proper synchronization? - Outline the thread-safety mechanism of
ConcurrentHashMapin Java 8+, and contrast it with the Java 7 segmented lock approach. - What data structure underlies
HashSet, and how does it enforce element uniqueness? - What is the underlying implementation of
TreeSet, and how does it maintain sorted order? - Compare
TreeMapandHashMap, focusing on ordering guarantees, performence, and use cases. - Explain how
LinkedHashMappreserves insertion or access order, and describe its internal structure. - Differentiate between
Collections.synchronizedXXX()wrapper methods andjava.util.concurrentcollection classes, including performance and locking granularity. - What is
CopyOnWriteArrayList, and what trade-offs does it make for thread safety? When is it most appropriate to use? - List 5-7 common implementations of
java.util.concurrent.BlockingQueue, and briefly describe each. - Explain the internal structure and ordering logic of
java.util.PriorityQueue. - What is the
java.util.Dequeinterface, and how does it extendQueue? Provide examples of common use cases. - Compare
Stack,Vector, andArrayList, noting which are legacy and why. - How do
java.util.Iteratorandjava.util.ListIteratordiffer in functionality and supported collection types? - Explain fail-fast and fail-safe iterators, including how they handle concurrent modifications and examples of collections that use each.
- Contrast
java.util.Enumerationandjava.util.Iterator, including legacy status, methods, and modification support. - Reiterate how hash collisions are handled in
Mapimplementations, focusing onHashMap. - When using a custom object as a key in a hash-based
MaporSet, which two methods must be overridden consistently? - What is
java.util.WeakHashMap, and what is its primary use case? - How does
java.util.IdentityHashMapdiffer fromHashMapin terms of key comparison? - What is
java.util.EnumMap, and what advantages does it offer over a general-purposeMapfor enum keys? - Walk through how to implement a simple LRU cache using
LinkedHashMap. - Reiterate the Java 7
ConcurrentHashMapsegmented lock principle and note why it was replaced. - List 3-4 common ways to sort Java collections and arrays.
- Compare
Collections.sort()andArrays.sort(), including supported types, underlying algorithms, and in-place sorting behavior. - Differentiate between
java.lang.Comparableandjava.util.Comparatorinterfaces, including method signatures, implementation location, and use cases. - Explain common approaches to implementing shallow and deep copies of Java collections.
- What are the two possible reasons
Map.get(key)returnsnull? - Can
nullbe used as a key or value in commonMapimplementations likeHashMap,TreeMap,ConcurrentHashMap, andHashtable? - Does
HashMapallow duplicate keys? What happens if you callput()with an existing key? - Reiterate how
Setimplementations enforce element uniqueness. - Provide a concise example of using Java 8 Streams to filter and sort a
Listof custom objects. - List 3-4 strategies for ensuring thread safety when working with Java collections.
- What is
java.util.concurrent.CopyOnWriteArraySet, and what is it based on? When should it be used? - Explain how to use
LinkedListas both a FIFO queue and a LIFO stack. - Give 2-3 practical application scenarios for
Deque. - Show how to use a custom
ComparatorwithPriorityQueueto reverse the default natural ordering. - Compare
Map.keySet(),Map.values(), andMap.entrySet()views, including what they return and whether they support removal. - List 4-5 common ways to iterate over Java collections and maps, and note which are considered legacy or have limitations.
- How do Java 8 Streams differ from traditional
Collectiontraversal? - What does
HashMap.putIfAbsent()do, and how is it useful? - What are Java 9+ collection factory methods, and what constraints do the immutable collections they create have?
- Reiterate 5-6 key utility methods from
ArraysandCollectionseach.
Java Multithreading & Concurrency
- Draw or describe the full lifecycle of a Java thread, including all states and transitions between them.
- List 4-5 common ways to create and start a Java thread, and note the preferred approach for most cases.
- Compare
java.lang.Runnableandjava.util.concurrent.Callableinterfaces, including method signatures, return values, and exception handling. - Why is implementing
Runnable(orCallable) generally preferred over extendingThread? - Name 5-6 pre-configured thread pool types provided by
java.util.concurrent.Executors, and briefly describe each. - Contrast
Executors.newFixedThreadPool()andExecutors.newCachedThreadPool(), focusing on thread count, queueing behavior, and ideal use cases. - How do you set and get the priority of a Java thread? What range of values is allowed, and what are the default, minimum, and maximum constants? Does thread priority guarantee execution order across all JVMs and operating systems?
- What does the
synchronizedkeyword do, and what two types of locks does it use implicitly? - Differentiate between
synchronizedmethods andsynchronizedblocks, including lock scope, flexibility, and best practices. - Compare
synchronizedstatic methods andsynchronizedinstance methods, focusing on which monitor lock they acquire. - What is
java.util.concurrent.locks.ReentrantLock, and what additional features does it offer oversynchronized? - Outline the key differences between
ReentrantLockandsynchronized, including flexibility, interruptibility, try-lock support, and fairness. - Explain how
java.util.concurrent.locks.ReentrantReadWriteLockworks, and what use case it is optimized for. - What is
java.util.concurrent.locks.Condition, and how does it improve uponObject.wait()/notify()/notifyAll()? - Reiterate the core guarantees of the
volatilekeyword (JMM visibility and禁止指令重排 for certain operations). - Can
volatilecompletely replacesynchronizedorLock? Why or why not? Provide a use case wherevolatileis sufficient and one where it is not. - Define the Java Memory Model (JMM), and explain its primary goals.
- What is the happens-before principle in JMM? List 5-6 common happens-before rules.
- What are atomic operation classes in
java.util.concurrent.atomic, and what problem do they solve? Give 3-4 examples. - Explain the Compare-And-Swap (CAS) algorithm, including its three operands, how it works, and common issues like ABA.
- How does
java.util.concurrent.CountDownLatchwork, and provide a practical use case. - What is
java.util.concurrent.CyclicBarrier, and how does it differ fromCountDownLatch? Give a use case. - Explain
java.util.concurrent.Semaphore, including permits, acquire/release methods, and use cases like resource pooling or rate limiting. - What is
java.util.concurrent.Exchanger, and what is its purpose? Provide a simple example. - Outline the internal implementation principle of
BlockingQueue. - Compare
java.util.concurrent.LinkedBlockingQueueandjava.util.concurrent.ArrayBlockingQueue, focusing on capacity, locking granularity, and performance. - Reiterate how
ConcurrentHashMapensures thread safety in Java 8+. - Reiterate the key characteristics, trade-offs, and ideal use cases of
CopyOnWriteArrayList. - Explain the internal working principle of
java.lang.ThreadLocal, and list 2-3 common use cases. What memory leak risk does it pose, and how can you mitigate it? - What are the four necessary conditions for a deadlock to occur? List 3-4 strategies to prevent or resolve deadlocks.
- Define livelock and thread starvation, and explain how they differ from deadlock.
- How does
Thread.join()work, and what is its purpose? - Contrast
Thread.sleep()andObject.wait(), including lock release, interruptibility, wake-up triggers, and typical use cases. - Explain how to properly use
Object.wait(),Object.notify(), andObject.notifyAll(), including best practices like always waiting in a loop. - What is Java’s thread interruption mechanism? How do you interrupt a thread, and how should a thread respond to an interrupt?
- What is a daemon thread, and what is its role? How do you set a thread as a daemon, and what restriction applies?
- Briefly explain how Java thread priority is implemented at the JVM and operating system levels.
- Compare
java.util.concurrent.Futureandjava.util.concurrent.FutureTask, including their relationship and usage. - What is
java.util.concurrent.ForkJoinPool, and what type of problems is it designed to solve? - Explain the work-stealing algorithm used by
ForkJoinPool. - How does
java.util.concurrent.DelayQueuework, and what requirement must elements in it meet? Give a use case. - What is
java.util.concurrent.Phaser, and how does it improve uponCountDownLatchandCyclicBarrier? - List and briefly describe the four built-in rejection policies for
java.util.concurrent.ThreadPoolExecutor. - Name 5-6 thread-safe collection classes in
java.utilandjava.util.concurrent. - How do immutable collections ensure thread safety? What are Java 9+ immutable collection factory methods?
- Is there a clear performance winner between
synchronizedandReentrantLockin all scenarios? What factors affect their performance? - Explain the double-checked locking (DCL) idiom for implementing a thread-safe singleton, including why it needs
volatilein Java 5+. - Reiterate the underlying implementation of atomic classes (CAS and
sun.misc.Unsafe/java.lang.invoke.VarHandle). - List 4-5 thread-safe ways to implement the singleton pattern in Java, and note which is considered the best practice by Joshua Bloch.
- Name 6-7 commonly used concurrency utility classes in
java.util.concurrent, and briefly describe each.
JVM & Memory Management
1. JVM Core Components
The Java Virtual Machine relies on five interconnected subsystems to execute bytecode:
- Class Loader Subsystem: Loads compiled
.classfiles into JVM memory, performing verification, preparation, resolution, and initialization as defined by the Java Virtual Machine Specification. - Runtime Data Area: Divided into thread-shared and thread-private regions to store program state, objects, metadata, and thread execution context.
- Execution Engine: Translates and executes bytecode, using an interpreter for quick startup and a Just-In-Time (JIT) compiler for optimizing hot code paths; also triggers garbage collection.
- Native Method Interface (JNI): Enables Java code to call and be called by native C/C++ applications and libraries.
- Native Method Libraries: Stores platform-specific implementations of native methods referenced via JNI.
2. JVM Runtime Memory Layout
graph TD
subgraph Off-Heap Memory
Metaspace
DirectMemory
end
subgraph Heap Memory (GC-Managed)
subgraph Young Generation
Eden
S0["Survivor 0 (From)"]
S1["Survivor 1 (To)"]
end
subgraph Old Generation
OldGen
Humongous["Humongous Objects (G1 Only)"]
end
end
subgraph Thread-Private Memory
PC["Program Counter"]
JStack["Java Virtual Machine Stack"]
NStack["Native Method Stack"]
end
3. Heap vs. Stack Comparison
| Aspect | Heap Memory | JVM Stack Memory |
|---|---|---|
| Visibility | Shared across all application threads | Exclusive to a single execution thread |
| Primary Contents | Object instances, array objects | Local variables, method parameters, return addresses, primitive copies |
| Allocation Speed | Slower (requires GC coordination) | Very fast (stack pointer arithmetic) |
| Lifetime Control | Determined by garbage collection | Tied directly to method call/return cycles |
| GC Involvement | Yes (Minor/Major/Full GC runs here) | No (automatically popped on method exit) |
| Common OOM Errors | OutOfMemoryError: Java heap space |
StackOverflowError (too deep recursion) |
| Management | Handled by JVM garbage collectors | Managed automatically by JVM thread execution |
4. Method Area (Metaspace in Java 8+)
The method area is a thread-shared region that stores class-level metadata and compiled code:
| Content Category | Detailed Description |
|---|---|
| Class Structural Data | Full class name, access modifiers, field declarations, method signatures, parent class, implemented interfaces |
| Runtime Constant Pool | Compile-time literals, symbolic references to types, fields, and methods resolved during runtime |
| Static Variables | Class-level static fields (moved to heap in some JVM implementations post-Java 7) |
| JIT Compiled Code Cache | Optimized native machine code generated by the JIT compiler for frequently executed methods |
| ClassLoader Metadata | References to the class loader that loaded the class, and other internal JVM bookkeeping |
5. Generational Heap Organization
| Heap Region | Primary Purpose | Notes |
|---|---|---|
| Eden Space | Initial allocation point for nearly all new small/medium objects | Largest chunk of the Young Generation (~80% by default) |
| Survivor Spaces (S0/S1) | Temporary holding area for objects that survive Minor GC | Two equal-sized spaces (~10% each by default); always one empty |
| Old (Tenured) Generation | Stores long-lived objects that survive multiple Minor GC cycles | Major/Full GC typically triggers here; larger and slower to collect |
| Humongous Region (G1 Only) | Stores objects larger than 50% of a G1 region size | Allocated directly in contiguous Old Generation-like regions |
| Metaspace | Replaced PermGen in Java 8; stores class metadata | Resides in native (off-heap) memory; auto-expands up to system limits |
6. Young Generation Default Ratio
The Young Generation is split into Eden and two Survivor spaces with a 8:1:1 ratio by default (configurable via -XX:SurvivorRatio):
┌─────────────────────────────────────────────────┐
│ Young Generation │
│ ┌──────────────────────────┬──────────┬──────────┐ │
│ │ Eden (80%) │ S0 (10%)│ S1 (10%)│ │
│ └──────────────────────────┴──────────┴──────────┘ │
└─────────────────────────────────────────────────┘
7. Minor vs. Major/Full GC
| Aspect | Minor GC (Young GC) | Major GC (Old GC) / Full GC |
|---|---|---|
| Target Region | Only Young Generation (Eden + one Survivor) | Major GC: Only Old Generation; Full GC: Young + Old + Metaspace |
| Trigger Condition | Eden space is fully occupied | Old Generation space insufficient, Metaspace full, System.gc() (hint), or JVM tooling |
| Speed | Fast (small region, few surviving objects) | Slow (large region, many objects to scan/move) |
| Frequency | Very frequent (depends on allocation rate) | Infrequent (depends on object promotion rate) |
| STW Duration | Short Stop-The-World pause | Long Stop-The-World pause (most impactful to application latency) |
| Default Algorithm | Copying (no fragmentation) | Mark-Sweep or Mark-Compact (reduces fragmentation) |
8. GC Roots
GC Roots are special objects that the garbage collector treats as always "live"; any object reachable (directly or indirectly) from a GC Root is not eligible for collection. Common GC Root types include:
| Root Type | Description |
|---|---|
| Local Variables & Parameters | Objects referenced by variables/parameters in active Java stack frames |
| Class Static Fields | Objects referenced by static variables of loaded classes |
| Runtime Constant Pool References | Objects referenced by entries in the runtime constant pool of loaded classes |
| JNI Local/Global References | Objects referenced by JNI handles in active native code |
| Active Threads | All currently running Java threads (their thread objects are roots) |
| JVM Internal References | Objects used internally by the JVM (e.g., system class loaders, core classes) |
9. Common Java Memory Leak Scenarios
Even with automatic garbage collection, Java applications can suffer from memory leaks—defined as unintentional retention of references to objects that are no longer needed, preventing GC from reclaiming their memory. Below are the most prevalent causes:
9.1 Static Collection Misuse
Static fields live for the entire JVM lifecycle. If a static collection accumulates objects without proper cleanup, those objects will never be GC’d.
import java.util.concurrent.ConcurrentLinkedQueue;
public class StaticResourceStore {
// Static queue persists indefinitely
private static final ConcurrentLinkedQueue<LargePayload> PAYLOAD_CACHE = new ConcurrentLinkedQueue<>();
public static void addPayload(LargePayload payload) {
PAYLOAD_CACHE.add(payload); // No corresponding removal logic!
}
}
9.2 Unregistered Listeners/Callbacks
When an object registers a listener with a long-lived subject (e.g., a UI component, application event bus) but fails to unregister it, the subject holds a reference to the listener, blocking its GC.
9.3 Improper ThreadLocal Cleanup
In thread-pooled environments (e.g., web servers), threads are reused. If ThreadLocal.set() is called without a corresponding ThreadLocal.remove() in a finally block, the thread’s ThreadLocalMap retains a reference to the value, causing a leak across requests.
9.4 Unclosed AutoCloseable Resources
Resources like FileInputStream, Connection, Socket, and ByteBuffer.allocateDirect() occupy native or heap memory. Failing to close them (preferably with try-with-resources) leaks both JVM and OS resources.
9.5 Broken equals()/hashCode() for Hash-Based Keys
If a custom class used as a key in HashMap/HashSet has inconsistent equals() and hashCode() implementations, duplicate logical keys may be inserted into the collection, causing memory bloat.
9.6 Non-Static Inner Class References
Non-static inner classes hold an implicit reference to their outer enclosing instance. If the inner class instance outlives the outer instance, the outer instance is prevented from being GC’d. Use static nested classes if no access to outer instance members is needed.
10. Excessive Object Creation Pitfalls
Frequent creation of short-lived, unnecessary objects increases GC pressure, leading to more frequent STW pauses and reduced throughput. Common examples and fixes:
| Pitfall Type | Example Anti-Pattern | Optimization Strategy |
|---|---|---|
| Loop-Based String Concatenation | String result = ""; for (int i=0; i<1000; i++) result += i; |
Use StringBuilder (single-threaded) or StringBuffer (multi-threaded) |
| Temporary Collection Reuse | for (Request req : requests) { List<Item> temp = new ArrayList<>(); ... } |
Reuse a single collection with clear() (if thread-safe) |
| Unnecessary Autoboxing/Unboxing | Long sum = 0L; for (long num : nums) sum += num; |
Use primitive variables for arithmetic loops |
| Duplicate Immutable Object Creation | for (int i=0; i<1000; i++) { Boolean flag = new Boolean(true); ... } |
Use cached immutable values (e.g., Boolean.TRUE, Integer.valueOf(1)) |
11. Heap vs. Off-Heap (Direct) Memory
| Aspect | Heap Memory | Off-Heap (Direct) Memory |
|---|---|---|
| Location | Managed within JVM heap boundaries | Allocated in OS native memory outside heap |
| Management | Fully automatic via JVM garbage collectors | Requires explicit deallocation (or Cleaner for DirectByteBuffer) |
| Access Speed | Slower for I/O (requires JVM ↔ OS copy) | Faster for I/O (direct OS kernel access) |
| Allocation Cost | Low (managed by TLABs for small objects) | High (no thread-local allocation buffers) |
| Typical Use Cases | General-purpose object allocation | High-performance I/O (NIO), large caches, avoiding GC pauses |
12. Heap ByteBuffer vs. Direct ByteBuffer
| Aspect | Heap ByteBuffer | Direct ByteBuffer |
|---|---|---|
| Allocation Method | ByteBuffer.allocate(int capacity) |
ByteBuffer.allocateDirect(int capacity) |
| Memory Location | JVM heap | OS native off-heap memory |
| I/O Overhead | Requires intermediate JVM ↔ OS copy | No intermediate copy (zero-copy I/O eligible) |
| GC Impact | Subject to normal GC pauses | No GC impact (until Cleaner runs) |
| Allocation Speed | Fast | Slow (for frequent small allocations) |
13. PermGen vs. Metaspace
| Aspect | PermGen (Java ≤7) | Metaspace (Java ≥8) |
|---|---|---|
| Memory Location | Part of JVM heap | Native OS off-heap memory |
| Size Flexibility | Fixed maximum size (-XX:MaxPermSize) |
Auto-expands up to available system memory (configurable via -XX:MaxMetaspaceSize) |
| Common OOM Error | OutOfMemoryError: PermGen space |
OutOfMemoryError: Metaspace |
| Replacement Reason | Fixed size hard to tune, caused OOMs with dynamic class loading (e.g., JSPs, application servers) | Uses native memory for better scalability and easier tuning |
14. Additional JVM & Memory Questions
- Walk through the full Java class loading process (loading → linking → initialization).
- What is the双亲委派模型 (parent delegation model) for class loaders, and what benefits does it provide?
- Name the three built-in JVM class loaders and describe their responsibilities.
- How do you implement a custom
ClassLoader? Provide a simple use case. - What causes class loader-related memory leaks?
- How do static variables affect JVM memory usage and garbage collection?
- What is the relationship between the Java Memory Model (JMM) and thread safety?
- How does escape analysis optimize object allocation in modern JVMs? List three optimizations it enables.
- Name 8-10 common JVM tuning parameters (heap, GC, Metaspace, etc.) and explain their purpose.
- List and briefly describe 5-6 common garbage collectors (Serial, Parallel, CMS, G1, ZGC, Shenandoah), including their target use cases and STW characteristics.
- What are the main drawbacks of the CMS garbage collector?
- When is the Serial garbage collector the best choice?
- What is the primary goal of the Parallel (Throughput) garbage collector?
- How do you enable and analyze GC logs? Name 2-3 tools for GC log analysis.
- What tools and techniques can you use to debug and diagnose Java heap memory leaks?
- List 4-5 best practices for optimizing Java memory usage.
- What are the key characteristics and use cases of the G1 garbage collector?
- Describe the memory layout of a Java object (object header, instance data, padding).
- What is the Mark Word in an object header, and what information does it store?
- What is Java’s object alignment requirement, and why is it enforced?
- How does
WeakHashMapinteract with garbage collection? - What is a
ReferenceQueue, and how is it used with soft/weak/phantom references? - What are the four types of Java references (strong, soft, weak, phantom), and how do they differ in terms of GC eligibility?
- What is the purpose of JIT compilation? Differentiate between C1 and C2 compilers in HotSpot.
- What is method inlining, and how does it improve JVM performance?
Java IO & Networking
- How are Java IO streams classified? Provide examples of each category.
- Contrast
java.io.InputStream(byte stream) andjava.io.Reader(character stream), including their use cases and character encoding handling. - Compare
java.io.OutputStreamandjava.io.Writer. - What are the key differences between byte streams and character streams in Java? When should you use each?
- Explain how to use
java.io.BufferedReaderandjava.io.BufferedWriterfor efficient text file I/O. - Walk through a basic file copy operation using
java.io.FileInputStreamandjava.io.FileOutputStream. - How do you read and write text files using
java.io.FileReaderandjava.io.FileWriter? What limitation do these classes have? - What are the core differences between traditional Java IO (BIO) and Java NIO?
- Explain how to use
java.nio.ByteBufferandjava.nio.CharBuffer, including key methods likeflip(),clear(),rewind(), andcompact(). - What is the relationship between
Channel,Selector, andBufferin Java NIO? - How does
java.io.RandomAccessFilework, and what makes it different from other file I/O classes? - Explain the basic principles of Java object serialization using
java.io.Serializable. - What effect does the
transientmodifier have on object serialization? - What is
java.io.Externalizable, and how does it differ fromSerializable? - What security risks are associated with Java serialization and deserialization? How can you mitigate them?
- Walk through a basic TCP client-server setup using
java.net.Socketandjava.net.ServerSocket. - Compare TCP and UDP protocols, including reliability, ordering, connection state, overhead, and use cases.
- How do you make a simple HTTP GET request using
java.net.URLandjava.net.HttpURLConnection? - Explain how to send and receive UDP datagrams using
java.net.DatagramSocketandjava.net.DatagramPacket. - What is non-blocking IO in Java NIO, and how does it work?
- What is the role of
java.nio.channels.Selectorin Java NIO? How does it enable multiplexed I/O? - How do you use
java.nio.channels.Pipefor inter-thread communication? - Explain how to use
java.nio.channels.FileLockto lock a file for exclusive or shared access. - How do you monitor file system events (e.g., creation, modification, deletion) using
java.nio.file.WatchService? - Compare
java.io.BufferedInputStreamandjava.io.BufferedReader. - Contrast
java.io.PrintWriterandjava.io.BufferedWriter. - What best practices should you follow for handling Java IO exceptions?
- How do you perform character encoding and decoding using
java.nio.charset.Charset? - What considerations should you keep in mind when using Java NIO with multiple threads?
- Explain how to use memory-mapped files with
java.nio.channels.FileChannel.map(). - Compare
java.util.Scannerandjava.io.BufferedReaderfor reading text input. - Walk through a basic object serialization and deserialization example using
java.io.ObjectInputStreamandjava.io.ObjectOutputStream. - What is the difference between blocking and non-blocking network IO in Java?
- Explain the multiplexed I/O mechanism used by
Selectorin Java NIO. - How do you use
java.nio.channels.SocketChannelandjava.nio.channels.ServerSocketChannelfor non-blocking TCP communication? - How do you use
java.nio.channels.DatagramChannelfor non-blocking UDP communication? - What are TCP sticky packets and fragmented packets? How can you handle them in Java network programming?
- Explain how to use
java.io.PipedInputStreamandjava.io.PipedOutputStreamfor inter-thread communication. - Reiterate the purpose and behavior of
ByteBuffer.flip(),clear(),rewind(), andcompact(). - How do you set socket timeouts (connect timeout, read timeout) in Java?
- What is Java NIO.2 asynchronous IO, and how do you use
AsynchronousSocketChannelandAsynchronousServerSocketChannel? - Compare
java.net.HttpURLConnectionandjava.net.http.HttpClient(Java 11+). - Differentiate between BIO, NIO, and AIO in Java.
- How do you use
java.net.URLClassLoaderto load classes from network resources? - How do you implement UDP broadcast using
DatagramSocket? - How do you implement a heartbeat mechanism in Java network programming?
- List 4-5 best practices for optimizing Java network IO performance.
- Compare TCP long connections and short connections, including use cases and overhead.
- What role do SSL/TLS play in Java network communication? How do you use them with
Socket,ServerSocket, andHttpClient? - What best practices should you follow for handling Java network exceptions?
Java Design Patterns
- What is a software design pattern? What are the benefits of using them?
- How are GoF (Gang of Four) design patterns classified? Name the three main categories and give 2-3 examples of each.
- List 5-6 common implementation approaches for the singleton pattern.
- Compare lazy initialization and eager initialization for singleton patterns.
- Explain the double-checked locking (DCL) singleton implementation, including why
volatileis required. - Why is using an enum type considered the best practice for implementing a singleton in Java?
- What problem does the factory pattern solve?
- Differentiate between simple factory, factory method, and abstract factory patterns.
- Provide a concise example of the abstract factory pattern.
- What is the observer pattern? What are its key components? Give a practical use case.
- What were
java.util.Observerandjava.util.Observable, and why are they deprecated in Java 9+? What modern alternatives exist? - What problem does the proxy pattern solve? Name the three main types of proxies.
- Compare static proxy and dynamic proxy in Java.
- Differentiate between JDK dynamic proxies and CGLIB dynamic proxies.
- What is the decorator pattern? How does it differ from inheritance? Give a well-known Java example.
- What problem does the adapter pattern solve? Name the two main types of adapters.
- What is the composite pattern? When should you use it?
- Explain the strategy pattern, including its key components and use cases. Provide a simple example.
- What is the state pattern? How does it differ from the strategy pattern?
- What is the template method pattern? What are its key components? Give a Java example.
- What is the chain of responsibility pattern? Give a practical use case.
- What problem does the command pattern solve? Name its key components.
- What is the iterator pattern? Why is it useful? How is it used in Java collections?
- What is the mediator pattern? How does it reduce coupling between components?
- What is the memento pattern? What are its key components? Give a use case.
- What is the prototype pattern? When should you use it instead of
new? - What is the flyweight pattern? What problem does it solve? Give a Java example.
- What is the bridge pattern? How does it differ from the adapter pattern?
- What is the builder pattern? When should you use it instead of a constructor with many parameters?
- Reiterate thread-safe singleton implementation approaches.
- Give 2-3 examples of factory pattern usage in the Spring framework.
- How is the proxy pattern used in Spring AOP?
- Reiterate the decorator pattern usage in Java IO streams.
- Give an example of the observer pattern in an event-driven system.
- How is the template method pattern used in JDBC programming?
- Provide an example of the strategy pattern for algorithm selection (e.g., sorting, payment processing).
- Give an example of the state pattern for implementing a finite state machine (e.g., a vending machine, traffic light).
- How is the chain of responsibility pattern used in logging frameworks?
- Give an example of the command pattern for a task queue or undo/redo system.
- Reiterate the iterator pattern usage in Java collections.
- How is the mediator pattern used in GUI systems?
- Give an example of the memento pattern for implementing undo functionality.
- How is the prototype pattern used for object cloning?
- Give an example of the flyweight pattern for caching or object pooling (e.g., string interning, database connection pool concepts).
- How can the bridge pattern be used in database access layers?
- Provide a concise example of the builder pattern for creating a complex immutable object.
- What are reflection and serialization attacks on singleton patterns? How can you prevent them?
- How can you combine the factory pattern with Spring IoC?
- How do design patterns improve code maintainability?
- How do design patterns improve system extensibility?
Spring Framework & Spring Boot
- Name and briefly describe the core modules of the Spring framework.
- Explain the core concepts of Spring IoC (Inversion of Control) and DI (Dependency Injection). What are the benefits of using IoC?
- What is Spring AOP (Aspect-Oriented Programming)? What cross-cutting concerns does it address?
- Compare
org.springframework.beans.factory.BeanFactoryandorg.springframework.context.ApplicationContext. - List the built-in bean scopes in Spring (both core and web).
- Differentiate between singleton and prototype bean scopes in Spring.
- What are the three main types of dependency injection in Spring? Which is recommended by the Spring team, and why?
- What does the
@Autowiredannotation do? How does Spring resolve ambiguity when multiple beans of the same type exist? - What is the
@Resourceannotation, and how does it differ from@Autowired? - What is the
@Injectannotation (JSR-330), and how does it compare to@Autowired? - Compare constructor injection and setter injection in Spring, including immutability, mandatory dependencies, and circular dependency handling.
- What lifecycle callbacks does Spring provide for beans?
- What is
org.springframework.beans.factory.config.BeanPostProcessor, and how do you use it? - What are
org.springframework.beans.factory.InitializingBeanandorg.springframework.beans.factory.DisposableBeaninterfaces used for? - What do the
@PostConstructand@PreDestroyannotations do? How do they compare to implementingInitializingBean/DisposableBeanor usinginit-method/destroy-method? - What is lazy initialization of beans in Spring? How do you enable it globally or for individual beans?
- What is
org.springframework.beans.factory.FactoryBean, and how does it differ from a regular Spring bean? - How do you create and register a custom bean scope in Spring?
- Explain how to use Spring’s event mechanism (
ApplicationEvent,ApplicationListener,@EventListener). - What are the two main types of transaction management in Spring?
- Compare programmatic transaction management and declarative transaction management in Spring.
- What does the
@Transactionalannotation do? What are some of its key attributes? - Reiterate the implementation principles of Spring AOP (JDK dynamic proxies vs. CGLIB).
- When does Spring use JDK dynamic proxies versus CGLIB proxies for AOP? How can you force Spring to use CGLIB?
- What is a Spring AOP pointcut? What AspectJ pointcut expression primitives does Spring support?
- What is Spring AOP’s around advice? How does it differ from before, after returning, after throwing, and after (finally) advice?
- What is Spring Boot, and what problems does it solve?
- Compare Spring Boot and the traditional Spring framework.
- Explain the auto-configuration principle in Spring Boot.
- What does the
@SpringBootApplicationannotation do? What three annotations does it combine? - What are Spring Boot Starters, and what benefits do they provide?
- Compare
application.propertiesandapplication.ymlconfiguration files in Spring Boot. - How do you use Spring Boot Profiles to manage environment-specific configurations?
- What is Spring Boot Actuator, and what features does it provide?
- How do you use Spring Boot with Spring MVC to build a RESTful web service?
- Explain the basic principles of Spring Security.
- How does Spring handle circular dependencies between singleton beans? What limitations apply?
- Compare lazy initialization and eager initialization of Spring beans, including performance implications.
- How do you create and use custom annotations in Spring?
40. Spring Aware Interfaces
Spring provides a set of Aware interfaces that allow beans to interact with the Spring container by receiving callbacks to container-managed resources or metadata. The bean lifecycle step order involving Aware interfaces is:
- Bean Instantiation: Spring calls the bean’s constructor.
- Dependency Injection: Spring populates the bean’s properties (DI).
- Aware Callback Execution: Spring invokes methods from implemented
Awareinterfaces (e.g.,BeanNameAware.setBeanName(),ApplicationContextAware.setApplicationContext()). - BeanPostProcessor Pre-Initialization:
BeanPostProcessor.postProcessBeforeInitialization()is called. - Bean Initialization: Initialization methods are executed (
@PostConstruct,InitializingBean.afterPropertiesSet(),init-method). - BeanPostProcessor Post-Initialization:
BeanPostProcessor.postProcessAfterInitialization()is called. - Bean Ready for Use: The fully initialized bean is available to the application.
41. Additional Spring & Spring Boot Questions
- What is the difference between Spring MVC and RESTful web services?
- Explain the full request processing workflow of
DispatcherServletin Spring MVC. - What is the role of
HandlerMappingin Spring MVC? - What does
HandlerAdapterdo in Spring MVC? - What is the purpose of
ViewResolverin Spring MVC? - Explain Spring MVC’s parameter binding mechanism. What annotations are commonly used for parameter binding?
- What are the common ways to handle exceptions in Spring MVC?
- Differentiate between Spring MVC
HandlerInterceptorand ServletFilter. - How do you configure logging in Spring Boot? What logging frameworks does Spring Boot suppport by default?
- How does the Spring framework improve system maintainability and extensibility?
Database & ORM
- Walk through the basic workflow of a JDBC operation (loading driver → getting connection → creating statement → executing query → processing results → closing resources).
- Compare
Connection,Statement, andPreparedStatementin JDBC, focusing on performance, security, and use cases. - What is
ResultSetin JDBC? What are the different types ofResultSet(concurrency, holdability, type)? - How do you manage transactions in JDBC?
- What is the difference between auto-commit mode and manual commit mode in JDBC?
- What is SQL injection? How can you prevent it in JDBC applications?
- How does
PreparedStatementprevent SQL injection? - How do you perform batch operations (batch insert/update/delete) using JDBC?
- What is a database connection pool? What benefits does it provide?
- Compare popular database connection pools like HikariCP, DBCP2, and Tomcat JDBC Pool. Which is the default in Spring Boot 2+?
- What is ORM (Object-Relational Mapping)? What are the pros and cons of using an ORM framework?
- What is the Hibernate framework? What role does it play as an ORM implementation?
- What is JPA (Java Persistence API)? How does it relate to Hibernate?
- Compare
javax.persistence.EntityManager(JPA) andorg.hibernate.Session(Hibernate). - What are the different ways to configure object-relational mappings in Hibernate?
- Explain Hibernate’s first-level cache (session cache) and second-level cache (session factory cache).
- What is a JPA persistence context? How does it relate to Hibernate’s first-level cache?
- Compare lazy loading and eager loading in Hibernate/JPA. What are the risks of lazy loading?
- Differentiate between optimistic locking and pessimistic locking in Hibernate/JPA. When should you use each?
- Explain how to use JPA relationship annotations:
@OneToOne,@OneToMany,@ManyToOne,@ManyToMany. - Compare Hibernate HQL (Hibernate Query Language) and SQL.
- How do you use Hibernate Criteria API for type-safe queries? Why is it deprecated in Hibernate 5.2+? What is its replacement?
- What is Spring Data JPA? What benefits does it provide over plain JPA/Hibernate?
- Explain Spring Data JPA’s method name query derivation rules. Provide 3-4 examples.
- What is the N+1 query problem in ORM frameworks? How can you solve it?
- What is the relationship between Hibernate
SessionandTransaction? - What does
EntityManager.flush()do? When should you call it? - Compare
Session.save()andSession.persist()in Hibernate. - Differentiate between
Session.merge()andSession.update()in Hibernate. - Compare
Session.delete()(Hibernate) andEntityManager.remove()(JPA). - What is the purpose of ORM framework caching mechanisms?
- List 4-5 ways to optimize the performance of an ORM framework like Hibernate.
- Reiterate the pros and cons of using JDBC versus an ORM framework.
- How do you use Hibernate’s query cache? What prerequisites must be met?
- Compare JPA JPQL (Java Persistence Query Language) and native SQL queries.
- Explain the three Hibernate/JPA object states: transient (new), persistent (managed), and detached.
- How do ORM frameworks handle transactions? How do they integrate with Spring transaction management?
- How do you integrate Hibernate with Spring’s declarative transaction management?
- How do you implement optimistic locking in a database (without ORM)?
- How do you implement pessimistic locking in a database (without ORM)?
- What are common lazy loading pitfalls in ORM frameworks? How can you avoid them?
- What does the
@Cacheableannotation do in JPA/Hibernate? - How do you use Spring Data JPA’s
@Queryannotation to define custom JPQL or native SQL queries? - List 2-3 ways to optimize batch inserts using an ORM framework.
- How do you perform pagination queries using JPA/Hibernate and Spring Data JPA?
- How do you implement dynamic queries using Spring Data JPA?
- What is Hibernate Validator? How do you use it for bean validation?
- What is a JPA
EntityListener? How do you use it? - What considerations should you keep in mind when using an ORM framework in a microservices architecture?
- How do ORM frameworks improve system performance and maintainability?
Microservices & Distributed Systems
- What is a microservices architecture? What are its core principles?
- Compare microservices architecture and monolithic architecture, including scalability, deployment, complexity, and team structure.
- What are the advantages and disadvantages of microservices architecture?
- What are some common strategies for splitting a monolith into microservices?
- Explain the core concepts of service registration and discovery. How do they work?
- Compare popular service registry/discovery tools: Eureka, Consul, ZooKeeper.
- What are the common client-side and server-side load balancing strategies?
- Compare client-side load balancing with Ribbon and server-side load balancing with Nginx.
- What is an API gateway in microservices architecture? What core functionalities does it provide?
- Compare Spring Cloud Netflix Zuul and Spring Cloud Gateway.
- What are the differences between synchronous and asynchronous communication in microservices? When should you use each?
- Compare RESTful APIs and gRPC for microservices communication.
- Why is distributed transaction management challenging in microservices? What are the key requirements?
- List 4-5 common distributed transaction solutions.
- Explain the TCC (Try-Confirm-Cancel) distributed transaction pattern.
- What is the reliable message-based (eventual consistency) distributed transaction pattern? How does it work?
- Explain the Saga distributed transaction pattern. What are the two main types of Sagas?
- What are common rate limiting strategies for microservices?
- Explain the circuit breaker pattern. What are its three states?
- Compare Hystrix (deprecated) and Resilience4j for circuit breaking and fault tolerance.
- What is service degradation in microservices? What are common degradation strategies?
- What is distributed tracing? How do Spring Cloud Sleuth and Zipkin work together to implement it?
- What are common use cases for distributed caching in microservices?
- Compare Redis and Memcached as distributed caching solutions.
- What are common ways to implement a distributed lock?
- Explain how to implement a distributed lock using Redis. What are common issues and how to mitigate them?
- Explain how to implement a distributed lock using ZooKeeper.
- What is idempotency in microservices? Why is it important? What are common ways to ensure idempotency?
- What is a configuration center in microservices? What benefits does it provide?
- Compare Spring Cloud Config and Alibaba Nacos as configuration centers.
- What are common security solutions for microservices architecture?
- Explain the OAuth2 and JWT (JSON Web Token) standards. How do they differ? When should you use each?
- What is gray release (canary release) in microservices? How do you implement it?
- What are common version management strategies for microservices APIs?
- How do you configure circuit breaking and service degradation using Resilience4j?
- Reiterate how to implement distributed tracing with Spring Cloud Sleuth and Zipkin.
- What are common strategies for handling high concurrency in microservices?
- List 4-5 common distributed ID generation schemes.
- Explain the Snowflake distributed ID generation algorithm.
- What is a distributed message queue? What core functionalities does it provide? What are common use cases?
- Compare popular distributed message queues: Kafka, RabbitMQ, RocketMQ.
- How do you ensure message idempotency when using a message queue?
- How do you ensure message ordering when using a message queue?
- Reiterate common solutions for ensuring data consistency in microservices.
- What are common database sharding (horizontal partitioning) strategies?
- What is the difference between distributed transactions (strong consistency) and eventual consistency?
- Reiterate common service degradation strategies.
- How do you handle service registration failures in microservices?
- What are core high availability design principles for microservices architecture?
- How do microservices architecture improve system scalability and maintainability?