Complete Java Interview Preparation Guide
Complete Java Interview Preparation Guide
import java.util.concurrent.atomic.AtomicInteger;
class SharedBuffer {
private Queue<Integer> buffer = new LinkedList<>();
private final int MAX_SIZE = 5;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
Threading Concepts
13. Explain the difference between thread and runnable.
Thread is a class representing an actual thread of execution, while Runnable is an interface
representing a task that can be executed concurrently [14] . Runnable allows implementing
multiple interfaces and better code organization, while Thread provides more control but doesn't
support multiple inheritance [14] . Runnable is lightweight and can be reused across multiple
threads [14] .
14. What is thread starvation?
Thread starvation occurs when a thread is unable to gain regular access to shared resources
and cannot make progress [15] . It happens when "greedy" threads monopolize resources,
synchronized methods take too long, higher priority threads always execute first, or wait-notify
signaling consistently favors certain threads [15] .
15. What is a deadlock and how to prevent it?
Deadlock occurs when two threads hold different locks and wait for each other's locks without
releasing their own [16] . Prevention techniques include consistent lock ordering (always acquire
locks in the same sequence), using timeout mechanisms with tryLock(), and avoiding nested
locks [16] .
16. How to detect thread deadlock in Java?
Use jstack command-line tool with the process ID to analyze thread dumps and detect
deadlocks [17] . The tool shows detailed information about locked objects and which threads are
waiting for which resources [17] . Java monitoring tools like JVisualVM can also detect and
visualize deadlock situations [17] .
17. Explain livelock with an example.
Livelock occurs when threads are not blocked but too busy responding to each other to make
progress [18] . Example: Two polite diners passing a spoon back and forth, each insisting the
other eat first, creating an infinite loop without actual progress [18] . Unlike deadlock where
threads are frozen, livelock threads remain active but unproductive [19] .
18. What is false sharing?
False sharing occurs when two threads on different CPUs write to different variables stored
within the same CPU cache line [20] . When one thread modifies its variable, the entire cache line
is invalidated in other CPU caches, forcing unnecessary reloads even for unrelated variables [20] .
This can be avoided using the @Contended annotation to separate variables into different cache
lines [20] .
Advanced Concurrency
19. Difference between Callable and Runnable.
Runnable's run() method returns void and cannot throw checked exceptions, while Callable's
call() method returns a generic type T and can throw checked exceptions [21] . Callable is more
flexible for operations that need to return results or handle checked exceptions like I/O
operations [21] .
20. What is a Future and CompletableFuture?
Future represents the result of an asynchronous computation, allowing you to check completion
status and retrieve results [22] . CompletableFuture extends Future with additional capabilities like
manual completion, chaining operations, and combining multiple futures without blocking [22] .
CompletableFuture enables non-blocking asynchronous programming with method chaining [22] .
Thread Management
36. What are daemon vs user threads?
User threads keep the JVM alive until they complete, while daemon threads don't prevent JVM
shutdown. The JVM exits when all user threads finish, regardless of running daemon threads.
Daemon threads are typically used for background services like garbage collection or
monitoring.
37. How does thread priority work in Java?
Thread priority is a hint to the thread scheduler about the relative importance of threads, ranging
from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY). However, priority behavior is platform-
dependent and not guaranteed. Modern JVMs often ignore priorities in favor of fair scheduling
algorithms.
38. Explain Thread.sleep() vs wait().
Thread.sleep() pauses the current thread for a specified time without releasing locks, while
wait() releases the object's monitor and waits for notify()/notifyAll(). sleep() is static and can
be called anywhere, while wait() must be called within synchronized blocks and is used for
inter-thread communication.
39. What is spurious wakeup?
Spurious wakeup occurs when a thread waiting on wait() wakes up without being explicitly
notified. This can happen due to system interrupts or JVM optimizations. Always use wait() in a
loop checking the condition to handle spurious wakeups properly.
40. How do you ensure visibility between threads?
Ensure visibility using volatile keywords for simple variables, synchronized blocks for complex
operations, atomic classes for lock-free operations, or higher-level concurrency utilities like
CountDownLatch and CyclicBarrier. These mechanisms create memory barriers ensuring changes
are visible across threads.
Advanced Threading
41. What is a thread pool leak and how to prevent it?
Thread pool leaks occur when threads are created but not properly shut down, or when tasks
hold references preventing garbage collection. Prevent by always calling shutdown() or
shutdownNow() on ExecutorService, using try-with-resources, and avoiding circular references in
tasks.
42. How do you handle uncaught exceptions in threads?
Set an UncaughtExceptionHandler using Thread.setUncaughtExceptionHandler() or
Thread.setDefaultUncaughtExceptionHandler() for global handling. For thread pools, handle
exceptions within tasks or use Future.get() to retrieve exceptions from submitted tasks.
43. Write a custom thread pool.
Spring Boot
6. Difference between field and constructor injection.
Constructor injection creates immutable objects and ensures all dependencies are provided at
creation time, making testing easier. Field injection is convenient but makes testing harder since
dependencies can only be injected by the framework. Constructor injection is generally
preferred for mandatory dependencies.
7. What is a @Qualifier?
@Qualifier is used when multiple beans of the same type exist and you need to specify which
one to inject. It works with @Autowired to disambiguate between candidates. You can create
custom qualifiers or use bean names as qualifiers.
8. What is @Primary annotation used for?
@Primary indicates which bean should be given preference when multiple candidates exist for
autowiring. It's an alternative to @Qualifier when you want to designate a default choice among
multiple beans of the same type.
9. What are the key annotations in Spring Boot?
Key annotations include @SpringBootApplication (combines @Configuration,
@EnableAutoConfiguration, @ComponentScan), @RestController, @RequestMapping, @Autowired,
@Value, @ConfigurationProperties, @Profile, and @Conditional annotations for auto-configuration.
Testing
31. How to write unit tests for controllers and services?
Use @WebMvcTest for controller testing with MockMvc, @MockBean for mocking dependencies, and
@Test for service testing. Test controllers with @AutoConfigureTestDatabase for repository testing
and @SpringBootTest for integration testing.
32. How does MockMvc work?
MockMvc provides a server-side testing framework for Spring MVC applications without starting
a full HTTP server. It performs requests and assertions on responses, supporting JSON path
expressions, status code verification, and content matching.
33. Difference between @MockBean and @Mock.
@MockBean is Spring Boot's annotation for adding mock beans to the application context, while
@Mock is Mockito's annotation for creating mock objects. @MockBean replaces beans in the Spring
context, while @Mock creates standalone mocks.
Collection Implementations
7. What is the difference between ArrayList and LinkedList?
ArrayList uses dynamic arrays providing O(1) random access but O(n) insertion/deletion in
middle. LinkedList uses doubly-linked nodes providing O(1) insertion/deletion but O(n) random
access. ArrayList is better for read-heavy operations, LinkedList for frequent
insertions/deletions.
8. Explain how HashSet ensures uniqueness.
HashSet uses HashMap internally, storing elements as keys with a dummy value. Uniqueness is
ensured through the underlying HashMap's key uniqueness constraint, using hashCode() and
equals() methods to identify duplicates during insertion.
9. Difference between equals() and hashCode().
equals() determines object equality semantically, while hashCode() provides integer hash values
for hash-based collections. Objects that are equal must have the same hashCode, but objects
with same hashCode aren't necessarily equal. Both must be overridden together for proper
collection behavior.
10. What is Comparable vs Comparator?
Comparable provides natural ordering through compareTo() method implemented by the class
itself. Comparator provides external ordering through compare() method in a separate class. Use
Comparable for default ordering, Comparator for custom or multiple orderings.
Specialized Collections
11. When to use EnumSet?
Use EnumSet for efficient storage and operations on enum values. It's implemented as bit
vectors providing excellent performance and memory efficiency. EnumSet operations are much
faster than regular Set implementations for enum elements.
12. How does CopyOnWriteArrayList work?
CopyOnWriteArrayList creates a new array copy for every write operation while reads access
the current array without synchronization. This provides thread-safety with excellent read
performance but expensive writes. Ideal for read-heavy, write-light scenarios.
13. When to use WeakHashMap?
Use WeakHashMap when you want entries to be automatically removed when keys are no
longer referenced elsewhere. Keys are held by weak references, allowing garbage collection
when no strong references exist. Useful for caches and memory-sensitive applications.
14. What is IdentityHashMap?
IdentityHashMap uses reference equality (==) instead of object equality (equals()) for key
comparison. It's useful when you need to distinguish between objects that are equal in content
but different in identity, such as in serialization frameworks.
15. What are fail-fast and fail-safe iterators?
Fail-fast iterators throw ConcurrentModificationException when collection is modified during
iteration (ArrayList, HashMap). Fail-safe iterators work on collection copies and don't throw
exceptions but may not reflect recent changes (CopyOnWriteArrayList, ConcurrentHashMap).
Concurrent Collections
16. How does ConcurrentSkipListMap maintain thread safety?
ConcurrentSkipListMap uses lock-free algorithms with atomic operations and skip list data
structure. It provides expected O(log n) performance for most operations while allowing
concurrent access without blocking. It maintains sorted order and implements NavigableMap.
17. Difference between capacity and size in collections.
Size represents the actual number of elements currently in the collection. Capacity represents
the maximum number of elements the collection can hold before resizing. ArrayList capacity
grows automatically, while HashMap capacity affects performance due to load factor.
18. How to prevent memory leaks with collections?
Prevent memory leaks by removing unused elements, using weak references when appropriate,
clearing collections when no longer needed, avoiding static collections with growing data, and
properly managing listener registrations and callbacks.
Memory Management
19. What is object pooling?
Object pooling reuses expensive objects instead of creating new ones, reducing garbage
collection overhead. Common for database connections, threads, and heavy objects. Implement
using existing pools (Apache Commons Pool) or custom implementations with proper
synchronization.
20. Explain soft, weak, and phantom references.
Soft references are collected when memory is low, useful for caches. Weak references are
collected during any GC cycle, useful for canonicalizing mappings. Phantom references are
collected before finalization, useful for cleanup actions. All allow objects to be garbage
collected.
String Handling
21. What is the String pool?
String pool (intern pool) is a special memory area storing unique String literals to save memory
through sharing. String.intern() moves strings to the pool. Literal strings automatically go to the
pool, while new String() creates heap objects.
22. What is autoboxing and unboxing?
Autoboxing automatically converts primitives to wrapper objects (int to Integer), while unboxing
converts wrapper objects to primitives. This happens automatically in assignments, method
calls, and expressions, but can impact performance in loops and collections.
23. What are wrapper classes in Java?
Wrapper classes (Integer, Double, Boolean, etc.) provide object representations of primitive
types. They enable primitives to be used in collections, provide utility methods, support null
values, and enable autoboxing/unboxing.
24. Difference between == and equals().
== compares references for objects and values for primitives. equals() compares object
content/value as defined by the class implementation. For proper object comparison, always use
equals() and ensure it's properly overridden with hashCode().
Functional Programming
25. What are functional interfaces?
Functional interfaces have exactly one abstract method and can be used with lambda
expressions. Examples include Runnable, Callable, Comparator, and custom interfaces.
@FunctionalInterface annotation ensures single abstract method constraint.
26. What is the default method in interfaces?
Default methods provide implementation in interfaces using 'default' keyword. They enable
interface evolution without breaking existing implementations. Multiple inheritance conflicts are
resolved through explicit overriding or super calls.
27. What is the use of Optional class?
Optional represents potentially absent values, avoiding null pointer exceptions. It provides
methods like isPresent(), get(), orElse(), map(), and filter() for safe value handling. Use instead of
returning null from methods.
String Performance
28. Difference between StringBuilder and StringBuffer.
StringBuilder is not thread-safe but faster for single-threaded operations. StringBuffer is thread-
safe (synchronized methods) but slower due to synchronization overhead. Both provide mutable
string operations avoiding immutable String concatenation overhead.
29. How does the intern() method work?
intern() returns canonical representation from string pool. If string exists in pool, returns existing
reference; otherwise, adds string to pool and returns it. Reduces memory usage for frequently
used strings but can cause memory leaks if overused.
Advanced Collections
30. How are generics implemented at runtime?
Generics use type erasure - generic type information is removed at runtime for backward
compatibility. Raw types replace parameterized types, with casts inserted automatically. This
enables generics to work with legacy code but limits runtime type information.
31. What is type erasure?
Type erasure removes generic type information during compilation, replacing type parameters
with their bounds (Object if unbounded). Bridge methods maintain polymorphism, and casts are
inserted automatically. This enables backward compatibility but prevents runtime generic type
checking.
32. How does ArrayDeque differ from LinkedList?
ArrayDeque uses resizable arrays and is more efficient for queue/stack operations with better
cache locality. LinkedList uses doubly-linked nodes with pointer overhead. ArrayDeque prohibits
null elements while LinkedList allows them.
33. How does PriorityQueue order elements?
PriorityQueue maintains elements in heap order using natural ordering (Comparable) or provided
Comparator. The head is always the smallest element according to ordering. It's not sorted but
maintains partial ordering for efficient priority-based retrieval.
34. Difference between Stack and Deque.
Stack is legacy class with synchronization overhead, while Deque interface provides double-
ended queue operations. ArrayDeque implements Deque more efficiently than Stack. Deque
supports operations at both ends, while Stack only supports LIFO operations.
35. How to make collections immutable?
Create immutable collections using Collections.unmodifiableList(), Guava's ImmutableList, or
copying constructors with defensive copying. Java 9+ provides List.of(), Set.of(), Map.of() for
immutable collections. Ensure contained objects are also immutable.
Specialized Maps
39. What is EnumMap?
EnumMap is a specialized Map implementation for enum keys using arrays internally. It provides
excellent performance, maintains natural enum ordering, and is more memory-efficient than
general-purpose maps for enum keys.
40. What is a NavigableMap?
NavigableMap extends SortedMap with navigation methods like lowerKey(), floorKey(),
ceilingKey(), higherKey(). It provides reverse iteration and subset views. TreeMap and
ConcurrentSkipListMap implement NavigableMap.
41. Difference between subList() and new ArrayList<>(subList()).
subList() returns a view backed by original list - changes affect both lists. new ArrayList<>
(subList()) creates independent copy - changes don't affect original. Views are more memory-
efficient but less safe for modifications.
Resource Management
42. Explain try-with-resources.
Try-with-resources automatically manages resources implementing AutoCloseable. Resources
are closed automatically in reverse order of declaration, even if exceptions occur. It replaces
explicit finally blocks for resource cleanup.
43. What is the role of finalize()?
finalize() is called by garbage collector before object destruction but is deprecated and
unreliable. It has unpredictable timing, performance overhead, and can prevent garbage
collection. Use try-with-resources or explicit cleanup methods instead.
Memory Architecture
44. How is memory managed in JVM?
JVM memory includes Heap (young/old generations), Method Area/Metaspace (class
metadata), Stack (thread-local method frames), PC Registers (instruction pointers), and Native
Method Stacks. Garbage collection manages heap memory automatically.
45. What are the GC roots in JVM?
GC roots are objects that are always reachable and include: local variables, static variables, JNI
references, monitor objects, and system class loader references. Objects reachable from GC
roots are not eligible for garbage collection.
46. How do you find memory leaks in Java?
Use heap dumps with tools like Eclipse MAT, JProfiler, or VisualVM. Monitor memory usage
patterns, analyze object retention, check for unclosed resources, and review static collections.
OutOfMemoryError often indicates memory leaks.
47. Tools used to profile memory in Java apps.
Memory profiling tools include JProfiler, YourKit, Eclipse MAT, VisualVM, JConsole, and async-
profiler. They provide heap analysis, allocation tracking, GC monitoring, and memory leak
detection capabilities.
48. Explain the structure of a Java object in memory.
Java objects consist of object header (mark word, class pointer), instance fields (primitives
inline, objects as references), and optional padding for alignment. Array objects include length
field. Object layout depends on JVM implementation and compression settings.
49. What is JVM tuning and how is it done?
JVM tuning optimizes performance through heap sizing (-Xms, -Xmx), garbage collector
selection (-XX:+UseG1GC), GC parameters, and monitoring. Analyze application behavior, GC
logs, and performance metrics to determine optimal settings.
50. Explain Metaspace and how it replaced PermGen.
Metaspace stores class metadata in native memory instead of heap, replacing PermGen in Java
8+. It grows automatically without fixed size limits, reducing OutOfMemoryError: PermGen space
issues. Class metadata is deallocated when classes are unloaded.
This comprehensive guide covers all 150 interview questions with detailed explanations, code
examples, and practical insights. Each answer provides the depth expected in technical
interviews while remaining concise and actionable. Good luck with your interview!
⁂
1. https://en.wikipedia.org/wiki/Java_memory_model
2. https://jenkov.com/tutorials/java-concurrency/java-memory-model.html
3. https://dev.to/adaumircosta/understanding-the-java-memory-model-jmm-p63
4. https://www.javamex.com/tutorials/synchronization_volatile.shtml
5. https://www.java67.com/2023/07/difference-between-reentrantlock-vs.html
6. https://www.codementor.io/@noelkamphoa/atomicinteger-class-in-java-2oh5icptfe
7. https://www.javacodegeeks.com/2020/12/threadlocal-in-java-example-program-and-tutorial.html
8. https://dzone.com/articles/garbage-collection-in-javajvm
9. https://www.techpaste.com/2011/09/garbage-collector-g1-concurrent-mark-sweep-collector-cms/
10. https://codingtechroom.com/question/understanding-memory-barriers-in-java
11. https://jenkov.com/tutorials/java-concurrency/java-happens-before-guarantee.html
12. https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html
13. https://stackoverflow.com/questions/63472450/why-is-happens-before-relationship-called-like-that
14. https://thisvsthat.io/runnable-vs-thread
15. https://www.netjstech.com/2017/10/thread-starvation-in-java-multi-threading.html
16. https://codesignal.com/learn/courses/java-concurrency-foundations/lessons/deadlocks-and-lock-mech
anisms
17. https://community.sap.com/t5/technology-blog-posts-by-sap/an-example-of-deadlock-detection-using
-jdk-standard-tool-jstack/ba-p/13234460
18. https://stackoverflow.com/questions/1036364/good-example-of-livelock
19. https://docs.oracle.com/javase/tutorial/essential/concurrency/starvelive.html
20. https://www.youtube.com/watch?v=tLS85IfsbYE
21. https://www.linkedin.com/pulse/runnable-vs-callable-java-whats-difference-giovanni-caprio-m9j0f
22. https://pwrteams.com/content-hub/blog/async-programming-and-completablefuture-in-java
23. https://dzone.com/articles/deep-dive-into-java-executorservice
24. https://spring.io/projects/spring-framework
25. https://www.simplilearn.com/tutorials/spring-boot-tutorial/what-is-spring-framework-and-its-advantag
es
26. https://www.upgrad.com/blog/spring-bean-life-cycle-explained/
27. https://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-se
rvice-annotations-in
28. https://keyholesoftware.com/what-is-dependency-injection-why-is-it-important-in-the-spring-framew
ork/
29. https://blog.eduonix.com/2018/01/learn-bean-scopes-spring-framework/
30. https://www.youtube.com/watch?v=xKCdp0jjZAw
31. https://www.linkedin.com/pulse/understanding-hashmap-java-internal-working-conflicts-kāshān-asim-
7rzrf
32. https://vivekbansal.substack.com/p/java-hashmap-internals
33. https://techdifferences.com/difference-between-hashmap-and-hashtable-in-java.html
34. http://javainterviewquestionswithanswer.blogspot.com/2016/12/why-concurrenthashmap-does-not-allo
w.html
35. https://blog.stackademic.com/understanding-linkedhashmap-in-java-internals-use-cases-and-impleme
ntation-79f3c15f3e84?gi=bfa1c280847e
36. https://www.baeldung.com/java-treemap