Top Java Interview Questions

Top 50 Java interview questions with curated answers across core concepts, practical scenarios, and interview-ready fundamentals.

Top 50 Java Interview Questions

  1. Analyze the following code snippet. Which statement is true?
  2. Compare and contrast RESTful APIs and gRPC. When would you choose one over the other?
  3. Consider a `@Service` bean with mutable state. How would changing the bean's scope from the default `singleton` to `prototype` affect a potential concurrency issue?
  4. A compensating transaction must be designed to be idempotent. Why is this property crucial?
  5. An agent that instruments a large number of classes in a complex application will most significantly impact which performance metric?
  6. Analyze the following code, which processes a list using a parallel stream. Which statement is true?
  7. Analyze the following code snippet. Which statement correctly describes its behavior?
  8. An interface is considered a functional interface if it has one abstract method. If an interface extends another interface, how does this affect its status as a functional interface?
  9. Analyze the following concurrent code that uses a shared `BCryptPasswordEncoder`. Which statement is correct?
  10. Analyze the following JPA code snippet that implements a ManyToMany relationship between 'User' and 'Group' entities. Is it a correct implementation of a bidirectional relationship?
  11. An AI tool suggested the following code to process a large dataset using Java Streams. However, it's inefficient. Identify the problem and suggest a more efficient solution.
  12. A Testcontainers test using a MySQL container fails with an 'OutOfMemoryError' after running for a while. What is a likely cause and how can it be addressed?
  13. Identify the bug in the following Spring MVC controller code snippet. The code is intended to retrieve a product by its name, but it has a design flaw.
  14. A singleton-scoped bean has a dependency on a prototype-scoped bean. What is the potential problem with this design?
  15. A Spring Boot application is configured for SSL but clients using standard browsers get a security warning when connecting. What is the most likely cause?
  16. Identify the bug in the following code snippet that attempts to add elements to a List of Lists using wildcards. Explain why it's incorrect.
  17. An agent's injected code uses `invocationCount.get()` followed by `invocationCount.set(newValue)` on an `AtomicInteger`. Why is this still a potential race condition?
  18. A local variable from an enclosing scope used inside a lambda expression must be `final` or 'effectively final'. Why does Java enforce this rule?
  19. A project has a large number of transitive dependencies, leading to slow build times and a bloated final artifact. What is the best approach to address this performance issue?
  20. A developer synchronized access to a `HashMap` to prevent race conditions. What is the primary performance drawback of this approach compared to using a `ConcurrentHashMap`?
  21. Describe a scenario where using Docker Compose is beneficial and explain how it simplifies the process of managing multiple containers.
  22. Compare and contrast instrumentation-based profilers (e.g., JProfiler) with sampling-based profilers (e.g., Async Profiler).
  23. Describe a scenario where using a custom `AuthenticationProvider` in Spring Security is beneficial. Explain how you would implement it, highlighting key considerations.
  24. Describe a scenario where using the 'prototype' scope in Spring is beneficial despite its potential performance overhead. Explain how to ensure thread safety in such a scenario.
  25. Describe a scenario where using `CompletableFuture`'s `thenCombine`, `thenAcceptBoth`, and `runAfterBoth` methods would be beneficial. Explain the nuances of choosing between these methods.
  26. Describe a scenario where using a Semaphore is more appropriate than using a simple lock (ReentrantLock). Explain the advantages and disadvantages of choosing Semaphore in that scenario.
  27. Describe a scenario where using Testcontainers for integration testing might introduce performance bottlenecks. How would you address such performance issues?
  28. Describe a scenario where you would need to customize HikariCP's connection test query and explain why a default test query might not suffice.
  29. Compare and contrast optimistic and pessimistic locking in the context of Spring Data JPA. When would you choose one over the other?
  30. Compare and contrast Spring's `@Autowired` annotation with the standard Java `@Resource` annotation for dependency injection.
  31. Compare and contrast pessimistic and optimistic locking in the context of JPA and Spring Data. When would you choose one over the other?
  32. Describe a scenario where the compensation mechanism in a Saga fails. How can you mitigate this risk?
  33. Describe a scenario where you would use G1GC over ParallelGC and explain the key performance metrics you'd monitor to justify your choice. What are the potential drawbacks of your decision?
  34. Describe a common strategy for analyzing a heap dump to identify memory leaks in a Java application. What tools are typically used in this process?
  35. Beyond code optimization, what build-time strategies can be used to minimize the final size and memory footprint of a GraalVM native executable?
  36. Describe how instruction reordering by the JVM can impact multithreaded programs and explain techniques to mitigate the risks associated with it.
  37. Describe how out-of-order execution and compiler optimizations can affect the correctness of multithreaded Java programs, and explain how the JMM mitigates these risks.
  38. Describe a robust strategy for handling token revocation in a Spring Security application using OAuth 2.0, considering both JWTs and opaque tokens.
  39. Compare and contrast Filebeat and Fluentd as log collection agents in a Kubernetes environment.
  40. Describe a comprehensive strategy for managing secrets in a microservices architecture using Spring Boot and incorporating best practices for security and operational efficiency.
  41. Compare and contrast Abstraction and Encapsulation in OOP. How do these two principles relate to each other?
  42. Compare and contrast abstract classes and interfaces in Java. When would you choose to use one over the other?
  43. Describe a use case where `TreeMap`'s range query capabilities would be highly beneficial compared to using a `HashMap`.
  44. Compare and contrast the use of an in-memory `HashMap` versus an external database for storing key-value data. What are the architectural tradeoffs involved in choosing one over the other?
  45. A `Person` object will be used as a key in a `HashMap`. Write a correct implementation of the `equals()` and `hashCode()` methods for the `Person` class below.
  46. Describe a scenario where using Optional could lead to performance degradation. How would you mitigate this issue?
  47. Describe a scenario where using `flatMap` with streams would be particularly beneficial, and explain how it addresses the problem compared to a nested loop approach.
  48. Describe different types of test doubles (mocks, stubs, spies, fakes) and explain when you would choose one over another in the context of unit testing with JUnit 5.
  49. Describe the architectural implications of adopting virtual threads in a large-scale, microservice-based application. Consider factors like resource contention and performance bottlenecks.
  50. A trading engine needs tens of thousands of lightweight threads. Explain how tuning `-Xss` impacts total JVM footprint while keeping enough headroom for heap-based order books.