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
- Analyze the following code snippet. Which statement is true?
- Compare and contrast RESTful APIs and gRPC. When would you choose one over the other?
- 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?
- A compensating transaction must be designed to be idempotent. Why is this property crucial?
- An agent that instruments a large number of classes in a complex application will most significantly impact which performance metric?
- Analyze the following code, which processes a list using a parallel stream. Which statement is true?
- Analyze the following code snippet. Which statement correctly describes its behavior?
- 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?
- Analyze the following concurrent code that uses a shared `BCryptPasswordEncoder`. Which statement is correct?
- 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?
- 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.
- 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?
- 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.
- A singleton-scoped bean has a dependency on a prototype-scoped bean. What is the potential problem with this design?
- 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?
- 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.
- An agent's injected code uses `invocationCount.get()` followed by `invocationCount.set(newValue)` on an `AtomicInteger`. Why is this still a potential race condition?
- A local variable from an enclosing scope used inside a lambda expression must be `final` or 'effectively final'. Why does Java enforce this rule?
- 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?
- 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`?
- Describe a scenario where using Docker Compose is beneficial and explain how it simplifies the process of managing multiple containers.
- Compare and contrast instrumentation-based profilers (e.g., JProfiler) with sampling-based profilers (e.g., Async Profiler).
- Describe a scenario where using a custom `AuthenticationProvider` in Spring Security is beneficial. Explain how you would implement it, highlighting key considerations.
- 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.
- Describe a scenario where using `CompletableFuture`'s `thenCombine`, `thenAcceptBoth`, and `runAfterBoth` methods would be beneficial. Explain the nuances of choosing between these methods.
- 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.
- Describe a scenario where using Testcontainers for integration testing might introduce performance bottlenecks. How would you address such performance issues?
- Describe a scenario where you would need to customize HikariCP's connection test query and explain why a default test query might not suffice.
- Compare and contrast optimistic and pessimistic locking in the context of Spring Data JPA. When would you choose one over the other?
- Compare and contrast Spring's `@Autowired` annotation with the standard Java `@Resource` annotation for dependency injection.
- Compare and contrast pessimistic and optimistic locking in the context of JPA and Spring Data. When would you choose one over the other?
- Describe a scenario where the compensation mechanism in a Saga fails. How can you mitigate this risk?
- 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?
- 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?
- Beyond code optimization, what build-time strategies can be used to minimize the final size and memory footprint of a GraalVM native executable?
- Describe how instruction reordering by the JVM can impact multithreaded programs and explain techniques to mitigate the risks associated with it.
- 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.
- Describe a robust strategy for handling token revocation in a Spring Security application using OAuth 2.0, considering both JWTs and opaque tokens.
- Compare and contrast Filebeat and Fluentd as log collection agents in a Kubernetes environment.
- Describe a comprehensive strategy for managing secrets in a microservices architecture using Spring Boot and incorporating best practices for security and operational efficiency.
- Compare and contrast Abstraction and Encapsulation in OOP. How do these two principles relate to each other?
- Compare and contrast abstract classes and interfaces in Java. When would you choose to use one over the other?
- Describe a use case where `TreeMap`'s range query capabilities would be highly beneficial compared to using a `HashMap`.
- 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?
- 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.
- Describe a scenario where using Optional could lead to performance degradation. How would you mitigate this issue?
- 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.
- 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.
- Describe the architectural implications of adopting virtual threads in a large-scale, microservice-based application. Consider factors like resource contention and performance bottlenecks.
- 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.