Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Comprehensive Java Interview Practice Question Set Covering Core Concepts to Advanced Topics

Notes 2

Core Java Syntax & Language Features

  1. Which 8 primitive data types does Java support?
  2. How do reference equality (==) and logical object equality (equals()) differ?
  3. Explain the distinct roles of final, finally, and finalize(). What happened to finalize() in modern Java versions?
  4. What behaviors do static fields, methods, nested classes, and initializers enable?
  5. Define autoboxing and unboxing, and list a common performance pitfall associated with them.
  6. When does Java perform automatic type promotion, and when is explicit casting required? What risks come with explicit casting?
  7. Is String an immutable type? Justify your answer and explain why this design choice was made.
  8. Compare String, StringBuilder, and StringBuffer in terms of mutability, thread safety, and performance.
  9. What are Java’s wrapper classes, and why were they introduced alongside primitives?
  10. What effect does the transient modifier have on instance variables?
  11. List and explain the two core guarantees provided by the volatile keyword. Can it solve all concurrency issues?
  12. How does the instanceof operator work, and what Java 16+ enhancement simplifies its usage?
  13. Differentiate between super and this keywords in Java.
  14. What is Java’s default access modifier, and what visibility does it grant?
  15. How do constructors differ from regular instance or static methods?
  16. Contrast local variables and member variables in terms of scope, initialization requirements, memory location, and access modifiers.
  17. Outline the key differences between interfaces and abstract classes. When should you choose one over the other?
  18. Define polymorphism in Java, and provide a concise, working example of both compile-time and runtime polymorphism.
  19. Distinguish between method overloading and method overriding, including rules and use cases for each.
  20. Reiterate Java’s wrapper classes and their corresponding primitive types.
  21. What is the difference between break and continue statements, and how do labeled versions extend their functionality?
  22. Explain how to declare and use Java enums, including adding methods, fields, and constructors to them.
  23. What is the contractual relationship between hashCode() and equals()? What issues arise if this contract is violated?
  24. Name and briefly describe the most commonly used methods from java.lang.Object.
  25. Draw or describe Java’s checked/unchecked exception hierarchy, starting from Throwable.
  26. What are checked exceptions, unchecked exceptions, and errors? When should each be thrown or handled?
  27. Walk through how to create both checked and unchecked custom exceptions.
  28. How does try-with-resources simplify resource management? What requirement must resources meet to be used with it?
  29. What is the purpose of the assert keyword, and why is it disabled by default in production environments?
  30. How do package declarations organize Java code, and what naming conventions are typically followed?
  31. Differentiate between package and import statements, including what each does and does not do.
  32. What is the primary function of Class.forName()? Provide a common historical use case and note its modern alternatives.
  33. How do getClass() and Class.forName() differ in terms of class loading behavior and initialization?
  34. What does the clone() method do, and what interface must a class implement to support it?
  35. Explain shallow copying versus deep copying in Java, and list common implementation approaches for each.
  36. What was the original intended role of finalize(), and why is it deprecated as of Java 9?
  37. What happens when System.gc() is called? Does it guarantee garbage collection will occur immediately?
  38. Name 8-10 commonly used methods from java.lang.Math.
  39. Compare java.util.Random and java.util.concurrent.ThreadLocalRandom, focusing on thread safety and performance in multi-threaded environments.
  40. What utility do java.util.Arrays and java.util.Collections provide? Give 3-5 examples of key methods from each.
  41. What problem does java.util.Optional solve, and what best practices should you follow when using it?
  42. List 6-8 major features introduced in Java 8.
  43. Explain the syntax and structure of a Java 8 Lambda expression, and identify functional interfaces as their target types.
  44. Differentiate between intermediate and terminal operations in Java 8 Streams, and provide 2-3 examples of each.
  45. What are Java method references, and what are the four main types? Give examples of each.
  46. Compare Predicate<T>, Function<T,R>, and Consumer<T> functional interfaces, including their method signatures and use cases.
  47. What are default methods in interfaces, and why were they added in Java 8?
  48. What is the var keyword (Java 10+), and what restrictions apply to its usage?
  49. What are record classes (Java 16+), and what boilerplate code do they automatically generate?
  50. Explain Java’s module system (Java 9+), including its core goals and key components like module-info.java.

Java Collections Framework

  1. What is the fundamental difference between java.util.Collection and java.util.Map?
  2. Compare List, Set, and Map interfaces in terms of element ordering, duplicates, and key-value pairing.
  3. Explain the internal structures and performance characteristics of ArrayList and LinkedList, and list ideal use cases for each.
  4. Contrast HashMap and Hashtable, noting why Hashtable is considered legacy.
  5. Describe the internal structure of HashMap in Java 8+, including buckets, nodes, trees, and the threshold for treeification.
  6. How does HashMap resolve hash collisions, and what improvement did Java 8 make over earlier versions?
  7. What is the load factor of HashMap, and how does it balance memory usage and performance? What is the default value?
  8. Explain the HashMap resizing trigger and process, including rehashing behavior in Java 8+.
  9. Is HashMap thread-safe? What issues can arise if it is modified concurrently without proper synchronization?
  10. Outline the thread-safety mechanism of ConcurrentHashMap in Java 8+, and contrast it with the Java 7 segmented lock approach.
  11. What data structure underlies HashSet, and how does it enforce element uniqueness?
  12. What is the underlying implementation of TreeSet, and how does it maintain sorted order?
  13. Compare TreeMap and HashMap, focusing on ordering guarantees, performence, and use cases.
  14. Explain how LinkedHashMap preserves insertion or access order, and describe its internal structure.
  15. Differentiate between Collections.synchronizedXXX() wrapper methods and java.util.concurrent collection classes, including performance and locking granularity.
  16. What is CopyOnWriteArrayList, and what trade-offs does it make for thread safety? When is it most appropriate to use?
  17. List 5-7 common implementations of java.util.concurrent.BlockingQueue, and briefly describe each.
  18. Explain the internal structure and ordering logic of java.util.PriorityQueue.
  19. What is the java.util.Deque interface, and how does it extend Queue? Provide examples of common use cases.
  20. Compare Stack, Vector, and ArrayList, noting which are legacy and why.
  21. How do java.util.Iterator and java.util.ListIterator differ in functionality and supported collection types?
  22. Explain fail-fast and fail-safe iterators, including how they handle concurrent modifications and examples of collections that use each.
  23. Contrast java.util.Enumeration and java.util.Iterator, including legacy status, methods, and modification support.
  24. Reiterate how hash collisions are handled in Map implementations, focusing on HashMap.
  25. When using a custom object as a key in a hash-based Map or Set, which two methods must be overridden consistently?
  26. What is java.util.WeakHashMap, and what is its primary use case?
  27. How does java.util.IdentityHashMap differ from HashMap in terms of key comparison?
  28. What is java.util.EnumMap, and what advantages does it offer over a general-purpose Map for enum keys?
  29. Walk through how to implement a simple LRU cache using LinkedHashMap.
  30. Reiterate the Java 7 ConcurrentHashMap segmented lock principle and note why it was replaced.
  31. List 3-4 common ways to sort Java collections and arrays.
  32. Compare Collections.sort() and Arrays.sort(), including supported types, underlying algorithms, and in-place sorting behavior.
  33. Differentiate between java.lang.Comparable and java.util.Comparator interfaces, including method signatures, implementation location, and use cases.
  34. Explain common approaches to implementing shallow and deep copies of Java collections.
  35. What are the two possible reasons Map.get(key) returns null?
  36. Can null be used as a key or value in common Map implementations like HashMap, TreeMap, ConcurrentHashMap, and Hashtable?
  37. Does HashMap allow duplicate keys? What happens if you call put() with an existing key?
  38. Reiterate how Set implementations enforce element uniqueness.
  39. Provide a concise example of using Java 8 Streams to filter and sort a List of custom objects.
  40. List 3-4 strategies for ensuring thread safety when working with Java collections.
  41. What is java.util.concurrent.CopyOnWriteArraySet, and what is it based on? When should it be used?
  42. Explain how to use LinkedList as both a FIFO queue and a LIFO stack.
  43. Give 2-3 practical application scenarios for Deque.
  44. Show how to use a custom Comparator with PriorityQueue to reverse the default natural ordering.
  45. Compare Map.keySet(), Map.values(), and Map.entrySet() views, including what they return and whether they support removal.
  46. List 4-5 common ways to iterate over Java collections and maps, and note which are considered legacy or have limitations.
  47. How do Java 8 Streams differ from traditional Collection traversal?
  48. What does HashMap.putIfAbsent() do, and how is it useful?
  49. What are Java 9+ collection factory methods, and what constraints do the immutable collections they create have?
  50. Reiterate 5-6 key utility methods from Arrays and Collections each.

Java Multithreading & Concurrency

  1. Draw or describe the full lifecycle of a Java thread, including all states and transitions between them.
  2. List 4-5 common ways to create and start a Java thread, and note the preferred approach for most cases.
  3. Compare java.lang.Runnable and java.util.concurrent.Callable interfaces, including method signatures, return values, and exception handling.
  4. Why is implementing Runnable (or Callable) generally preferred over extending Thread?
  5. Name 5-6 pre-configured thread pool types provided by java.util.concurrent.Executors, and briefly describe each.
  6. Contrast Executors.newFixedThreadPool() and Executors.newCachedThreadPool(), focusing on thread count, queueing behavior, and ideal use cases.
  7. 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?
  8. What does the synchronized keyword do, and what two types of locks does it use implicitly?
  9. Differentiate between synchronized methods and synchronized blocks, including lock scope, flexibility, and best practices.
  10. Compare synchronized static methods and synchronized instance methods, focusing on which monitor lock they acquire.
  11. What is java.util.concurrent.locks.ReentrantLock, and what additional features does it offer over synchronized?
  12. Outline the key differences between ReentrantLock and synchronized, including flexibility, interruptibility, try-lock support, and fairness.
  13. Explain how java.util.concurrent.locks.ReentrantReadWriteLock works, and what use case it is optimized for.
  14. What is java.util.concurrent.locks.Condition, and how does it improve upon Object.wait()/notify()/notifyAll()?
  15. Reiterate the core guarantees of the volatile keyword (JMM visibility and禁止指令重排 for certain operations).
  16. Can volatile completely replace synchronized or Lock? Why or why not? Provide a use case where volatile is sufficient and one where it is not.
  17. Define the Java Memory Model (JMM), and explain its primary goals.
  18. What is the happens-before principle in JMM? List 5-6 common happens-before rules.
  19. What are atomic operation classes in java.util.concurrent.atomic, and what problem do they solve? Give 3-4 examples.
  20. Explain the Compare-And-Swap (CAS) algorithm, including its three operands, how it works, and common issues like ABA.
  21. How does java.util.concurrent.CountDownLatch work, and provide a practical use case.
  22. What is java.util.concurrent.CyclicBarrier, and how does it differ from CountDownLatch? Give a use case.
  23. Explain java.util.concurrent.Semaphore, including permits, acquire/release methods, and use cases like resource pooling or rate limiting.
  24. What is java.util.concurrent.Exchanger, and what is its purpose? Provide a simple example.
  25. Outline the internal implementation principle of BlockingQueue.
  26. Compare java.util.concurrent.LinkedBlockingQueue and java.util.concurrent.ArrayBlockingQueue, focusing on capacity, locking granularity, and performance.
  27. Reiterate how ConcurrentHashMap ensures thread safety in Java 8+.
  28. Reiterate the key characteristics, trade-offs, and ideal use cases of CopyOnWriteArrayList.
  29. 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?
  30. What are the four necessary conditions for a deadlock to occur? List 3-4 strategies to prevent or resolve deadlocks.
  31. Define livelock and thread starvation, and explain how they differ from deadlock.
  32. How does Thread.join() work, and what is its purpose?
  33. Contrast Thread.sleep() and Object.wait(), including lock release, interruptibility, wake-up triggers, and typical use cases.
  34. Explain how to properly use Object.wait(), Object.notify(), and Object.notifyAll(), including best practices like always waiting in a loop.
  35. What is Java’s thread interruption mechanism? How do you interrupt a thread, and how should a thread respond to an interrupt?
  36. What is a daemon thread, and what is its role? How do you set a thread as a daemon, and what restriction applies?
  37. Briefly explain how Java thread priority is implemented at the JVM and operating system levels.
  38. Compare java.util.concurrent.Future and java.util.concurrent.FutureTask, including their relationship and usage.
  39. What is java.util.concurrent.ForkJoinPool, and what type of problems is it designed to solve?
  40. Explain the work-stealing algorithm used by ForkJoinPool.
  41. How does java.util.concurrent.DelayQueue work, and what requirement must elements in it meet? Give a use case.
  42. What is java.util.concurrent.Phaser, and how does it improve upon CountDownLatch and CyclicBarrier?
  43. List and briefly describe the four built-in rejection policies for java.util.concurrent.ThreadPoolExecutor.
  44. Name 5-6 thread-safe collection classes in java.util and java.util.concurrent.
  45. How do immutable collections ensure thread safety? What are Java 9+ immutable collection factory methods?
  46. Is there a clear performance winner between synchronized and ReentrantLock in all scenarios? What factors affect their performance?
  47. Explain the double-checked locking (DCL) idiom for implementing a thread-safe singleton, including why it needs volatile in Java 5+.
  48. Reiterate the underlying implementation of atomic classes (CAS and sun.misc.Unsafe/java.lang.invoke.VarHandle).
  49. List 4-5 thread-safe ways to implement the singleton pattern in Java, and note which is considered the best practice by Joshua Bloch.
  50. 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:

  1. Class Loader Subsystem: Loads compiled .class files into JVM memory, performing verification, preparation, resolution, and initialization as defined by the Java Virtual Machine Specification.
  2. Runtime Data Area: Divided into thread-shared and thread-private regions to store program state, objects, metadata, and thread execution context.
  3. 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.
  4. Native Method Interface (JNI): Enables Java code to call and be called by native C/C++ applications and libraries.
  5. 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

  1. Walk through the full Java class loading process (loading → linking → initialization).
  2. What is the双亲委派模型 (parent delegation model) for class loaders, and what benefits does it provide?
  3. Name the three built-in JVM class loaders and describe their responsibilities.
  4. How do you implement a custom ClassLoader? Provide a simple use case.
  5. What causes class loader-related memory leaks?
  6. How do static variables affect JVM memory usage and garbage collection?
  7. What is the relationship between the Java Memory Model (JMM) and thread safety?
  8. How does escape analysis optimize object allocation in modern JVMs? List three optimizations it enables.
  9. Name 8-10 common JVM tuning parameters (heap, GC, Metaspace, etc.) and explain their purpose.
  10. List and briefly describe 5-6 common garbage collectors (Serial, Parallel, CMS, G1, ZGC, Shenandoah), including their target use cases and STW characteristics.
  11. What are the main drawbacks of the CMS garbage collector?
  12. When is the Serial garbage collector the best choice?
  13. What is the primary goal of the Parallel (Throughput) garbage collector?
  14. How do you enable and analyze GC logs? Name 2-3 tools for GC log analysis.
  15. What tools and techniques can you use to debug and diagnose Java heap memory leaks?
  16. List 4-5 best practices for optimizing Java memory usage.
  17. What are the key characteristics and use cases of the G1 garbage collector?
  18. Describe the memory layout of a Java object (object header, instance data, padding).
  19. What is the Mark Word in an object header, and what information does it store?
  20. What is Java’s object alignment requirement, and why is it enforced?
  21. How does WeakHashMap interact with garbage collection?
  22. What is a ReferenceQueue, and how is it used with soft/weak/phantom references?
  23. What are the four types of Java references (strong, soft, weak, phantom), and how do they differ in terms of GC eligibility?
  24. What is the purpose of JIT compilation? Differentiate between C1 and C2 compilers in HotSpot.
  25. What is method inlining, and how does it improve JVM performance?

Java IO & Networking

  1. How are Java IO streams classified? Provide examples of each category.
  2. Contrast java.io.InputStream (byte stream) and java.io.Reader (character stream), including their use cases and character encoding handling.
  3. Compare java.io.OutputStream and java.io.Writer.
  4. What are the key differences between byte streams and character streams in Java? When should you use each?
  5. Explain how to use java.io.BufferedReader and java.io.BufferedWriter for efficient text file I/O.
  6. Walk through a basic file copy operation using java.io.FileInputStream and java.io.FileOutputStream.
  7. How do you read and write text files using java.io.FileReader and java.io.FileWriter? What limitation do these classes have?
  8. What are the core differences between traditional Java IO (BIO) and Java NIO?
  9. Explain how to use java.nio.ByteBuffer and java.nio.CharBuffer, including key methods like flip(), clear(), rewind(), and compact().
  10. What is the relationship between Channel, Selector, and Buffer in Java NIO?
  11. How does java.io.RandomAccessFile work, and what makes it different from other file I/O classes?
  12. Explain the basic principles of Java object serialization using java.io.Serializable.
  13. What effect does the transient modifier have on object serialization?
  14. What is java.io.Externalizable, and how does it differ from Serializable?
  15. What security risks are associated with Java serialization and deserialization? How can you mitigate them?
  16. Walk through a basic TCP client-server setup using java.net.Socket and java.net.ServerSocket.
  17. Compare TCP and UDP protocols, including reliability, ordering, connection state, overhead, and use cases.
  18. How do you make a simple HTTP GET request using java.net.URL and java.net.HttpURLConnection?
  19. Explain how to send and receive UDP datagrams using java.net.DatagramSocket and java.net.DatagramPacket.
  20. What is non-blocking IO in Java NIO, and how does it work?
  21. What is the role of java.nio.channels.Selector in Java NIO? How does it enable multiplexed I/O?
  22. How do you use java.nio.channels.Pipe for inter-thread communication?
  23. Explain how to use java.nio.channels.FileLock to lock a file for exclusive or shared access.
  24. How do you monitor file system events (e.g., creation, modification, deletion) using java.nio.file.WatchService?
  25. Compare java.io.BufferedInputStream and java.io.BufferedReader.
  26. Contrast java.io.PrintWriter and java.io.BufferedWriter.
  27. What best practices should you follow for handling Java IO exceptions?
  28. How do you perform character encoding and decoding using java.nio.charset.Charset?
  29. What considerations should you keep in mind when using Java NIO with multiple threads?
  30. Explain how to use memory-mapped files with java.nio.channels.FileChannel.map().
  31. Compare java.util.Scanner and java.io.BufferedReader for reading text input.
  32. Walk through a basic object serialization and deserialization example using java.io.ObjectInputStream and java.io.ObjectOutputStream.
  33. What is the difference between blocking and non-blocking network IO in Java?
  34. Explain the multiplexed I/O mechanism used by Selector in Java NIO.
  35. How do you use java.nio.channels.SocketChannel and java.nio.channels.ServerSocketChannel for non-blocking TCP communication?
  36. How do you use java.nio.channels.DatagramChannel for non-blocking UDP communication?
  37. What are TCP sticky packets and fragmented packets? How can you handle them in Java network programming?
  38. Explain how to use java.io.PipedInputStream and java.io.PipedOutputStream for inter-thread communication.
  39. Reiterate the purpose and behavior of ByteBuffer.flip(), clear(), rewind(), and compact().
  40. How do you set socket timeouts (connect timeout, read timeout) in Java?
  41. What is Java NIO.2 asynchronous IO, and how do you use AsynchronousSocketChannel and AsynchronousServerSocketChannel?
  42. Compare java.net.HttpURLConnection and java.net.http.HttpClient (Java 11+).
  43. Differentiate between BIO, NIO, and AIO in Java.
  44. How do you use java.net.URLClassLoader to load classes from network resources?
  45. How do you implement UDP broadcast using DatagramSocket?
  46. How do you implement a heartbeat mechanism in Java network programming?
  47. List 4-5 best practices for optimizing Java network IO performance.
  48. Compare TCP long connections and short connections, including use cases and overhead.
  49. What role do SSL/TLS play in Java network communication? How do you use them with Socket, ServerSocket, and HttpClient?
  50. What best practices should you follow for handling Java network exceptions?

Java Design Patterns

  1. What is a software design pattern? What are the benefits of using them?
  2. How are GoF (Gang of Four) design patterns classified? Name the three main categories and give 2-3 examples of each.
  3. List 5-6 common implementation approaches for the singleton pattern.
  4. Compare lazy initialization and eager initialization for singleton patterns.
  5. Explain the double-checked locking (DCL) singleton implementation, including why volatile is required.
  6. Why is using an enum type considered the best practice for implementing a singleton in Java?
  7. What problem does the factory pattern solve?
  8. Differentiate between simple factory, factory method, and abstract factory patterns.
  9. Provide a concise example of the abstract factory pattern.
  10. What is the observer pattern? What are its key components? Give a practical use case.
  11. What were java.util.Observer and java.util.Observable, and why are they deprecated in Java 9+? What modern alternatives exist?
  12. What problem does the proxy pattern solve? Name the three main types of proxies.
  13. Compare static proxy and dynamic proxy in Java.
  14. Differentiate between JDK dynamic proxies and CGLIB dynamic proxies.
  15. What is the decorator pattern? How does it differ from inheritance? Give a well-known Java example.
  16. What problem does the adapter pattern solve? Name the two main types of adapters.
  17. What is the composite pattern? When should you use it?
  18. Explain the strategy pattern, including its key components and use cases. Provide a simple example.
  19. What is the state pattern? How does it differ from the strategy pattern?
  20. What is the template method pattern? What are its key components? Give a Java example.
  21. What is the chain of responsibility pattern? Give a practical use case.
  22. What problem does the command pattern solve? Name its key components.
  23. What is the iterator pattern? Why is it useful? How is it used in Java collections?
  24. What is the mediator pattern? How does it reduce coupling between components?
  25. What is the memento pattern? What are its key components? Give a use case.
  26. What is the prototype pattern? When should you use it instead of new?
  27. What is the flyweight pattern? What problem does it solve? Give a Java example.
  28. What is the bridge pattern? How does it differ from the adapter pattern?
  29. What is the builder pattern? When should you use it instead of a constructor with many parameters?
  30. Reiterate thread-safe singleton implementation approaches.
  31. Give 2-3 examples of factory pattern usage in the Spring framework.
  32. How is the proxy pattern used in Spring AOP?
  33. Reiterate the decorator pattern usage in Java IO streams.
  34. Give an example of the observer pattern in an event-driven system.
  35. How is the template method pattern used in JDBC programming?
  36. Provide an example of the strategy pattern for algorithm selection (e.g., sorting, payment processing).
  37. Give an example of the state pattern for implementing a finite state machine (e.g., a vending machine, traffic light).
  38. How is the chain of responsibility pattern used in logging frameworks?
  39. Give an example of the command pattern for a task queue or undo/redo system.
  40. Reiterate the iterator pattern usage in Java collections.
  41. How is the mediator pattern used in GUI systems?
  42. Give an example of the memento pattern for implementing undo functionality.
  43. How is the prototype pattern used for object cloning?
  44. Give an example of the flyweight pattern for caching or object pooling (e.g., string interning, database connection pool concepts).
  45. How can the bridge pattern be used in database access layers?
  46. Provide a concise example of the builder pattern for creating a complex immutable object.
  47. What are reflection and serialization attacks on singleton patterns? How can you prevent them?
  48. How can you combine the factory pattern with Spring IoC?
  49. How do design patterns improve code maintainability?
  50. How do design patterns improve system extensibility?

Spring Framework & Spring Boot

  1. Name and briefly describe the core modules of the Spring framework.
  2. Explain the core concepts of Spring IoC (Inversion of Control) and DI (Dependency Injection). What are the benefits of using IoC?
  3. What is Spring AOP (Aspect-Oriented Programming)? What cross-cutting concerns does it address?
  4. Compare org.springframework.beans.factory.BeanFactory and org.springframework.context.ApplicationContext.
  5. List the built-in bean scopes in Spring (both core and web).
  6. Differentiate between singleton and prototype bean scopes in Spring.
  7. What are the three main types of dependency injection in Spring? Which is recommended by the Spring team, and why?
  8. What does the @Autowired annotation do? How does Spring resolve ambiguity when multiple beans of the same type exist?
  9. What is the @Resource annotation, and how does it differ from @Autowired?
  10. What is the @Inject annotation (JSR-330), and how does it compare to @Autowired?
  11. Compare constructor injection and setter injection in Spring, including immutability, mandatory dependencies, and circular dependency handling.
  12. What lifecycle callbacks does Spring provide for beans?
  13. What is org.springframework.beans.factory.config.BeanPostProcessor, and how do you use it?
  14. What are org.springframework.beans.factory.InitializingBean and org.springframework.beans.factory.DisposableBean interfaces used for?
  15. What do the @PostConstruct and @PreDestroy annotations do? How do they compare to implementing InitializingBean/DisposableBean or using init-method/destroy-method?
  16. What is lazy initialization of beans in Spring? How do you enable it globally or for individual beans?
  17. What is org.springframework.beans.factory.FactoryBean, and how does it differ from a regular Spring bean?
  18. How do you create and register a custom bean scope in Spring?
  19. Explain how to use Spring’s event mechanism (ApplicationEvent, ApplicationListener, @EventListener).
  20. What are the two main types of transaction management in Spring?
  21. Compare programmatic transaction management and declarative transaction management in Spring.
  22. What does the @Transactional annotation do? What are some of its key attributes?
  23. Reiterate the implementation principles of Spring AOP (JDK dynamic proxies vs. CGLIB).
  24. When does Spring use JDK dynamic proxies versus CGLIB proxies for AOP? How can you force Spring to use CGLIB?
  25. What is a Spring AOP pointcut? What AspectJ pointcut expression primitives does Spring support?
  26. What is Spring AOP’s around advice? How does it differ from before, after returning, after throwing, and after (finally) advice?
  27. What is Spring Boot, and what problems does it solve?
  28. Compare Spring Boot and the traditional Spring framework.
  29. Explain the auto-configuration principle in Spring Boot.
  30. What does the @SpringBootApplication annotation do? What three annotations does it combine?
  31. What are Spring Boot Starters, and what benefits do they provide?
  32. Compare application.properties and application.yml configuration files in Spring Boot.
  33. How do you use Spring Boot Profiles to manage environment-specific configurations?
  34. What is Spring Boot Actuator, and what features does it provide?
  35. How do you use Spring Boot with Spring MVC to build a RESTful web service?
  36. Explain the basic principles of Spring Security.
  37. How does Spring handle circular dependencies between singleton beans? What limitations apply?
  38. Compare lazy initialization and eager initialization of Spring beans, including performance implications.
  39. 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:

  1. Bean Instantiation: Spring calls the bean’s constructor.
  2. Dependency Injection: Spring populates the bean’s properties (DI).
  3. Aware Callback Execution: Spring invokes methods from implemented Aware interfaces (e.g., BeanNameAware.setBeanName(), ApplicationContextAware.setApplicationContext()).
  4. BeanPostProcessor Pre-Initialization: BeanPostProcessor.postProcessBeforeInitialization() is called.
  5. Bean Initialization: Initialization methods are executed (@PostConstruct, InitializingBean.afterPropertiesSet(), init-method).
  6. BeanPostProcessor Post-Initialization: BeanPostProcessor.postProcessAfterInitialization() is called.
  7. Bean Ready for Use: The fully initialized bean is available to the application.

41. Additional Spring & Spring Boot Questions

  1. What is the difference between Spring MVC and RESTful web services?
  2. Explain the full request processing workflow of DispatcherServlet in Spring MVC.
  3. What is the role of HandlerMapping in Spring MVC?
  4. What does HandlerAdapter do in Spring MVC?
  5. What is the purpose of ViewResolver in Spring MVC?
  6. Explain Spring MVC’s parameter binding mechanism. What annotations are commonly used for parameter binding?
  7. What are the common ways to handle exceptions in Spring MVC?
  8. Differentiate between Spring MVC HandlerInterceptor and Servlet Filter.
  9. How do you configure logging in Spring Boot? What logging frameworks does Spring Boot suppport by default?
  10. How does the Spring framework improve system maintainability and extensibility?

Database & ORM

  1. Walk through the basic workflow of a JDBC operation (loading driver → getting connection → creating statement → executing query → processing results → closing resources).
  2. Compare Connection, Statement, and PreparedStatement in JDBC, focusing on performance, security, and use cases.
  3. What is ResultSet in JDBC? What are the different types of ResultSet (concurrency, holdability, type)?
  4. How do you manage transactions in JDBC?
  5. What is the difference between auto-commit mode and manual commit mode in JDBC?
  6. What is SQL injection? How can you prevent it in JDBC applications?
  7. How does PreparedStatement prevent SQL injection?
  8. How do you perform batch operations (batch insert/update/delete) using JDBC?
  9. What is a database connection pool? What benefits does it provide?
  10. Compare popular database connection pools like HikariCP, DBCP2, and Tomcat JDBC Pool. Which is the default in Spring Boot 2+?
  11. What is ORM (Object-Relational Mapping)? What are the pros and cons of using an ORM framework?
  12. What is the Hibernate framework? What role does it play as an ORM implementation?
  13. What is JPA (Java Persistence API)? How does it relate to Hibernate?
  14. Compare javax.persistence.EntityManager (JPA) and org.hibernate.Session (Hibernate).
  15. What are the different ways to configure object-relational mappings in Hibernate?
  16. Explain Hibernate’s first-level cache (session cache) and second-level cache (session factory cache).
  17. What is a JPA persistence context? How does it relate to Hibernate’s first-level cache?
  18. Compare lazy loading and eager loading in Hibernate/JPA. What are the risks of lazy loading?
  19. Differentiate between optimistic locking and pessimistic locking in Hibernate/JPA. When should you use each?
  20. Explain how to use JPA relationship annotations: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany.
  21. Compare Hibernate HQL (Hibernate Query Language) and SQL.
  22. How do you use Hibernate Criteria API for type-safe queries? Why is it deprecated in Hibernate 5.2+? What is its replacement?
  23. What is Spring Data JPA? What benefits does it provide over plain JPA/Hibernate?
  24. Explain Spring Data JPA’s method name query derivation rules. Provide 3-4 examples.
  25. What is the N+1 query problem in ORM frameworks? How can you solve it?
  26. What is the relationship between Hibernate Session and Transaction?
  27. What does EntityManager.flush() do? When should you call it?
  28. Compare Session.save() and Session.persist() in Hibernate.
  29. Differentiate between Session.merge() and Session.update() in Hibernate.
  30. Compare Session.delete() (Hibernate) and EntityManager.remove() (JPA).
  31. What is the purpose of ORM framework caching mechanisms?
  32. List 4-5 ways to optimize the performance of an ORM framework like Hibernate.
  33. Reiterate the pros and cons of using JDBC versus an ORM framework.
  34. How do you use Hibernate’s query cache? What prerequisites must be met?
  35. Compare JPA JPQL (Java Persistence Query Language) and native SQL queries.
  36. Explain the three Hibernate/JPA object states: transient (new), persistent (managed), and detached.
  37. How do ORM frameworks handle transactions? How do they integrate with Spring transaction management?
  38. How do you integrate Hibernate with Spring’s declarative transaction management?
  39. How do you implement optimistic locking in a database (without ORM)?
  40. How do you implement pessimistic locking in a database (without ORM)?
  41. What are common lazy loading pitfalls in ORM frameworks? How can you avoid them?
  42. What does the @Cacheable annotation do in JPA/Hibernate?
  43. How do you use Spring Data JPA’s @Query annotation to define custom JPQL or native SQL queries?
  44. List 2-3 ways to optimize batch inserts using an ORM framework.
  45. How do you perform pagination queries using JPA/Hibernate and Spring Data JPA?
  46. How do you implement dynamic queries using Spring Data JPA?
  47. What is Hibernate Validator? How do you use it for bean validation?
  48. What is a JPA EntityListener? How do you use it?
  49. What considerations should you keep in mind when using an ORM framework in a microservices architecture?
  50. How do ORM frameworks improve system performance and maintainability?

Microservices & Distributed Systems

  1. What is a microservices architecture? What are its core principles?
  2. Compare microservices architecture and monolithic architecture, including scalability, deployment, complexity, and team structure.
  3. What are the advantages and disadvantages of microservices architecture?
  4. What are some common strategies for splitting a monolith into microservices?
  5. Explain the core concepts of service registration and discovery. How do they work?
  6. Compare popular service registry/discovery tools: Eureka, Consul, ZooKeeper.
  7. What are the common client-side and server-side load balancing strategies?
  8. Compare client-side load balancing with Ribbon and server-side load balancing with Nginx.
  9. What is an API gateway in microservices architecture? What core functionalities does it provide?
  10. Compare Spring Cloud Netflix Zuul and Spring Cloud Gateway.
  11. What are the differences between synchronous and asynchronous communication in microservices? When should you use each?
  12. Compare RESTful APIs and gRPC for microservices communication.
  13. Why is distributed transaction management challenging in microservices? What are the key requirements?
  14. List 4-5 common distributed transaction solutions.
  15. Explain the TCC (Try-Confirm-Cancel) distributed transaction pattern.
  16. What is the reliable message-based (eventual consistency) distributed transaction pattern? How does it work?
  17. Explain the Saga distributed transaction pattern. What are the two main types of Sagas?
  18. What are common rate limiting strategies for microservices?
  19. Explain the circuit breaker pattern. What are its three states?
  20. Compare Hystrix (deprecated) and Resilience4j for circuit breaking and fault tolerance.
  21. What is service degradation in microservices? What are common degradation strategies?
  22. What is distributed tracing? How do Spring Cloud Sleuth and Zipkin work together to implement it?
  23. What are common use cases for distributed caching in microservices?
  24. Compare Redis and Memcached as distributed caching solutions.
  25. What are common ways to implement a distributed lock?
  26. Explain how to implement a distributed lock using Redis. What are common issues and how to mitigate them?
  27. Explain how to implement a distributed lock using ZooKeeper.
  28. What is idempotency in microservices? Why is it important? What are common ways to ensure idempotency?
  29. What is a configuration center in microservices? What benefits does it provide?
  30. Compare Spring Cloud Config and Alibaba Nacos as configuration centers.
  31. What are common security solutions for microservices architecture?
  32. Explain the OAuth2 and JWT (JSON Web Token) standards. How do they differ? When should you use each?
  33. What is gray release (canary release) in microservices? How do you implement it?
  34. What are common version management strategies for microservices APIs?
  35. How do you configure circuit breaking and service degradation using Resilience4j?
  36. Reiterate how to implement distributed tracing with Spring Cloud Sleuth and Zipkin.
  37. What are common strategies for handling high concurrency in microservices?
  38. List 4-5 common distributed ID generation schemes.
  39. Explain the Snowflake distributed ID generation algorithm.
  40. What is a distributed message queue? What core functionalities does it provide? What are common use cases?
  41. Compare popular distributed message queues: Kafka, RabbitMQ, RocketMQ.
  42. How do you ensure message idempotency when using a message queue?
  43. How do you ensure message ordering when using a message queue?
  44. Reiterate common solutions for ensuring data consistency in microservices.
  45. What are common database sharding (horizontal partitioning) strategies?
  46. What is the difference between distributed transactions (strong consistency) and eventual consistency?
  47. Reiterate common service degradation strategies.
  48. How do you handle service registration failures in microservices?
  49. What are core high availability design principles for microservices architecture?
  50. How do microservices architecture improve system scalability and maintainability?

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.