Preparing for a Senior Java Developer role in 2025? This comprehensive list of 100+ interview questions with answers covers real-world scenarios across:
- đź”— Spring Microservice Integration
- đź§ Core Java (Threads, Collections, Memory)
- đź§± Design Patterns
- 📊 Algorithms & Data Structures
- đź“„ SQL & Database Design
đź§ 1. Core Java (25 Questions)
Multithreading & Concurrency
1. Difference between synchronized
and ReentrantLock
?
synchronized
is a keyword that offers intrinsic locking with automatic release. ReentrantLock
provides more control (e.g., tryLock, fair locking) and must be manually unlocked.
2. What is a deadlock? How do you prevent it?
Deadlock occurs when two threads wait on each other to release locks. Prevent using lock ordering, timeout mechanisms, or tryLock.
3. What’s the purpose of volatile
?
Ensures visibility of changes to variables across threads. Prevents caching of variables locally.
4. How does ThreadLocal
work?
It maintains a separate value for each thread using a thread-local map internally.
5. When should you use Callable
over Runnable
?
Use Callable
when you need a return value or want to throw checked exceptions.
Collections
6. How is HashMap
implemented internally?
Uses an array of buckets (Node[]), where each entry is stored via hashing. Collisions handled using chaining or balanced trees in Java 8+.
7. What’s the difference between ArrayList
and LinkedList
?
ArrayList
uses dynamic arrays (fast random access). LinkedList
uses nodes (efficient inserts/deletes).
8. When to use ConcurrentHashMap
vs Collections.synchronizedMap()
?
ConcurrentHashMap
offers better concurrency with segment-based locking. synchronizedMap
locks the entire map.
9. What is fail-fast vs fail-safe iterator?
Fail-fast throws ConcurrentModificationException
. Fail-safe (e.g., CopyOnWriteArrayList
) uses snapshot.
10. How do TreeMap
and HashMap
differ?
TreeMap
is sorted and uses Red-Black Tree. HashMap
is unordered and uses hashing.
OOP & Best Practices
11. What are the 4 pillars of OOP in Java?
Encapsulation, Abstraction, Inheritance, Polymorphism.
12. Difference between composition and inheritance?
Composition uses "has-a" while inheritance uses "is-a" relationship.
13. What is the Liskov Substitution Principle?
Subtypes must be substitutable for their base types without altering correctness.
14. Can an interface have static methods?
Yes, from Java 8 onward.
15. What is the diamond problem? How does Java 8 handle it?
Occurs with multiple inheritance of methods. Java resolves it using explicit override.
Memory Management
16. What is garbage collection in Java?
Automatic process of reclaiming memory from unreachable objects.
17. Explain the Java memory model.
Heap (Young, Old), Stack, Metaspace. Thread-safe reads/writes governed by JMM.
18. What is PermGen vs Metaspace?
PermGen (pre-Java 8) was fixed-size. Metaspace grows dynamically.
19. How does G1GC differ from CMS?
G1GC is region-based, parallel, and has predictable pause times.
20. How can you detect and fix memory leaks?
Using tools like VisualVM, JProfiler. Common causes: static collections, listeners not removed.
Java 8+ Features
21. What is a functional interface?
An interface with a single abstract method. Enables lambda expressions.
22. Difference between map()
and flatMap()
in Streams?
map()
transforms each element. flatMap()
flattens nested structures.
23. What are method references?
A shorthand for calling methods using ::
syntax. E.g., System.out::println
.
24. What is Optional and how should it be used?
To avoid null
. Use isPresent()
, orElse()
, map()
. Don’t misuse as container.
25. What is the purpose of default methods in interfaces?
Allows adding methods without breaking implementations.
đź”— 2. Spring Boot & Microservices (25 Questions)
Spring Boot Internals
26. How does Spring Boot auto-configuration work?
Via @EnableAutoConfiguration
and condition-based beans using classpath detection.
27. Difference between @Component
, @Service
, @Repository
?
All are stereotypes. @Repository
adds DB exception translation. @Service
adds business semantics.
28. How does Spring manage bean lifecycle?
Using scopes, post processors, @PostConstruct
, @PreDestroy
, lifecycle interfaces.
29. What is the role of @ConditionalOnProperty
?
Conditionally enable beans based on property values.
30. How to handle circular dependencies?
Avoid via constructor injection. Use @Lazy
or setter injection as last resort.
Microservices Integration
31. How do you implement inter-service communication?
REST (RestTemplate/WebClient), gRPC, Kafka. Prefer Feign for declarative REST.
32. What is the difference between synchronous and asynchronous calls?
Sync waits for response; async uses callbacks or messaging (Kafka/RabbitMQ).
33. How do you implement retry, fallback, and circuit breaker?
Use Resilience4j or Spring Cloud Circuit Breaker with fallback methods.
34. How do you ensure backward compatibility between services?
Versioned endpoints (/v1/api
), contract testing (Pact), schema evolution tools.
35. What’s the role of API Gateway in microservice architecture?
Routes requests, applies auth, rate limits, transforms payloads.
Security & Resilience
36. How do you secure REST endpoints?
JWT with Spring Security, OAuth2 for user-based access.
37. Difference between OAuth2 and JWT?
OAuth2 is a protocol. JWT is a token format. OAuth2 may use JWT for tokens.
38. How do you implement RBAC in Spring Security?
Map roles to endpoints using annotations or config DSL.
39. How do you protect microservices against DDOS or abuse?
Rate limiting, circuit breakers, Web Application Firewall (WAF).
40. What is rate limiting and how do you implement it?
Restricts request volume. Use Bucket4j, Redis-based counters, API Gateway filters.
Configuration & Observability
41. What is Spring Cloud Config Server?
Centralized configuration using Git/FS/DB backends. Refreshable via /actuator/refresh
.
42. How do you implement distributed tracing?
Using Spring Sleuth and Zipkin/Jaeger.
43. How does actuator help in production?
Exposes health, metrics, beans, mappings. Use /actuator/*
endpoints.
44. How to monitor microservices in real time?
Prometheus + Grafana, Micrometer metrics.
45. What tools do you use for logs and metrics?
ELK stack (Elastic, Logstash, Kibana), Prometheus, OpenTelemetry.
Deployment & Failures
46. How do you achieve zero-downtime deployment?
Blue-green, rolling updates, Kubernetes readiness probes.
47. What is blue-green deployment?
Deploy to inactive environment, switch traffic after verification.
48. What happens if a service crashes? How do you recover?
Retry, circuit break, autoscale, use Kubernetes liveness probes.
49. How do you handle data consistency in distributed transactions?
Sagas (choreography/orchestration), eventual consistency, outbox pattern.
50. What is a Saga pattern and when should you use it?
Manages long-running distributed transactions via compensation steps.
đź§± 3. Design Patterns (20 Questions)
51. What is the Singleton pattern? How do you implement it in Java?
Ensures only one instance exists. Implement via private constructor and static method.
52. How is Factory pattern different from Abstract Factory?
Factory returns one product. Abstract Factory returns related families.
53. What is the Strategy pattern?
Encapsulates interchangeable algorithms. Promotes composition over inheritance.
54. Where is the Builder pattern commonly used?
Used in object construction (e.g., StringBuilder
, Lombok @Builder
).
55. What is the Observer pattern?
Allows subscribers to react to changes in state (e.g., event listeners).
56. Explain the Proxy pattern with real-world usage.
Proxy controls access (e.g., AOP, lazy loading in Hibernate).
57. Difference between Adapter and Decorator pattern?
Adapter changes interface. Decorator adds responsibility.
58. What is the Template Method pattern?
Defines skeleton of algorithm in superclass, lets subclass override steps.
59. When do you use Command pattern?
For encapsulating a request as an object (undo/redo systems).
60. What’s the benefit of Chain of Responsibility?
Decouples sender and receivers. Multiple handlers can process requests.
61. What is Dependency Injection? How does Spring use it?
A technique to inject dependencies rather than hard-coding. Spring uses constructors/setters/fields.
62. How is MVC implemented in Spring?
Controllers map requests, services handle logic, models are data objects, views render UI.
63. What is AOP? Common use cases?
Aspect-Oriented Programming for cross-cutting concerns like logging, transactions.
64. How is Lazy Initialization useful in patterns?
Delays object creation. Useful in Singleton, Proxy.
65. What’s the difference between Composition and Aggregation?
Composition: owns lifecycle. Aggregation: just a reference.
66. Can patterns introduce complexity? How do you balance it?
Yes. Apply only where there's recurring benefit. Avoid over-engineering.
67. What’s the role of the Mediator pattern?
Centralizes communication between objects to reduce coupling.
68. Example of Flyweight pattern in Java APIs?
Integer.valueOf()
, String.intern()
reuse objects to save memory.
69. What pattern does Java’s Enum Singleton use?
Enum is the safest way to implement Singleton, guards against reflection and serialization.
70. How to test code that uses Factory or Strategy pattern?
Inject mock strategies/factories using dependency injection or mocking frameworks.
📊 4. Algorithms & Data Structures (15 Questions)
71. How do you reverse a LinkedList without using extra space?
Iteratively change next
pointers. Keep track of previous/current nodes.
72. Write a function to check if a string is a palindrome.
Use two-pointer technique or reverse and compare.
73. What is the time complexity of HashMap operations?
Average case O(1). Worst-case O(n) due to collisions.
74. Explain binary search algorithm.
Efficient O(log n) algorithm on sorted arrays. Divide and conquer.
75. How does QuickSort work?
Divide around a pivot. Sort partitions recursively. Average O(n log n).
76. What’s the difference between BFS and DFS?
BFS uses queue (level order). DFS uses stack/recursion (depth first).
77. When is a heap used in Java?
PriorityQueue, heapsort. Useful for top-K problems.
78. Implement LRU cache.
Use LinkedHashMap or a combination of HashMap + Doubly Linked List.
79. What’s a Trie? Use case?
Tree-like structure for prefix searching (e.g., autocomplete).
80. Difference between Stack and Queue?
Stack: LIFO. Queue: FIFO. Used for parsing, task scheduling.
81. How do you detect a cycle in a graph?
DFS with visited set or Union-Find.
82. How do you find the intersection of two arrays?
Use Set or HashMap to track common elements.
83. What’s the difference between Array and LinkedList?
Array: fixed size, fast access. LinkedList: dynamic, fast insert/delete.
84. What is dynamic programming?
Solves problems by combining results of subproblems (e.g., Fibonacci).
85. What is memoization?
Cache results of expensive function calls.
đź“„ 5. SQL & Database (15 Questions)
86. Difference between INNER JOIN and LEFT JOIN?
INNER returns matching rows. LEFT returns all from left + matches.
87. What is normalization?
Structuring data to reduce redundancy (1NF, 2NF, 3NF).
88. How to prevent SQL Injection in Java?
Use PreparedStatements. Avoid string concatenation.
89. What is indexing? How does it work?
Speeds up queries using B-Trees/Hash indexes.
90. Difference between clustered and non-clustered index?
Clustered: sorts actual data. Non-clustered: separate structure.
91. What is ACID in databases?
Atomicity, Consistency, Isolation, Durability.
92. Explain isolation levels.
Read Uncommitted < Read Committed < Repeatable Read < Serializable.
93. What are transactions and how are they managed in Spring?
Logical units of work. Managed via @Transactional
.
94. What’s a deadlock in DB?
Two transactions waiting on each other’s locks.
95. How to profile slow queries?
Use EXPLAIN
, query logs, monitoring tools.
96. What’s the use of JOIN FETCH
in JPQL?
Prevents N+1 problem by fetching related entities.
97. How do you ensure consistency in distributed DBs?
Use eventual consistency, quorum-based reads/writes, 2PC.
98. What is optimistic vs pessimistic locking?
Optimistic: versioning. Pessimistic: lock rows.
99. When to use NoSQL over RDBMS?
For unstructured data, high scalability (e.g., MongoDB, Cassandra).
100. What’s a primary key vs unique key?
Primary key: uniquely identifies rows, not null. Unique allows one null.
âś… Wrap Up
Got this far? You're interview ready! Bookmark and revisit these Q&As before your next big opportunity. And if you want more deep dives (or a printable PDF), drop a comment!
Top comments (1)
🔥🔥🔥