Java interview questions
3,928 questions across 39 topics, each with the correct answer and an explanation. Free to read.
Object-oriented programming
492 questions- When comparing two String objects, what's the difference between == and equals()?
- What does this program print?
- Which statements about the equals/hashCode contract are true? Select all that apply.
- In modern Java (8+), when would you choose an abstract class over an interface? Compare the two.
- What issue might arise if a constructor directly assigns a mutable object without copying it?
Collections
158 questions- Choose the typical (average) time complexity of each operation.
- What does this print?
- Which statement about nulls in maps is correct?
- Which interface should a class implement to define its natural ordering, so that Collections.sort(list)…
- If you need a collection that supports quick insertion and removal of elements at both ends, but also…
Streams & functional
4 questionsExceptions
160 questions- Which of these is an unchecked exception?
- R prints "open X" in its constructor and "close X" in close(). Put the printed lines in order.
- Which statements about finally are true? Select all that apply.
- Explain checked vs unchecked exceptions in Java. When would you use each in your own API?
- Why does chaining exceptions in Java help in practice?
Concurrency basics
110 questions- What does declaring a field volatile guarantee?
- What's the most accurate description of what this program prints?
- Which changes would make the counter in a multi-threaded increment loop correct? Select all that apply.
- Which ExecutorService method stops accepting new tasks but lets already-submitted tasks finish? (method name)
- Which method is used to wait for all CompletableFutures in a list to complete?
JVM & runtime
4 questionsI/O
4 questions- Which class should you wrap around a FileReader to read text efficiently line by line?
- Which java.nio.file.Files method reads all lines of a small text file into a List<String>? (method name)
- Which statements about Java serialization are true? Select all that apply.
- What does new File("data.txt") do if data.txt doesn't exist?
Design patterns
98 questions- new BufferedInputStream(new FileInputStream(file)) adds buffering to a stream by wrapping it. Which pattern…
- Classify each design pattern.
- Explain the Strategy pattern with a concrete Java example. When would you use it?
- A code review describes a ConfigManager singleton. Highlight the statements that describe real problems.
- Your checkout flow wants one clean charge(order) call, but each payment provider ships a different SDK.…
API Evolution
27 questions- How does the java.time package improve architectural design over java.util.Date?
- What does subtracting one month from March 31 using java.time.LocalDate evaluate to?
- How does java.time.Instant ensure thread safety?
- What will be the output of the following code? LocalDate date = LocalDate.of(2023, 2, 28); LocalDate newDate…
- How would you calculate the number of days between two java.time.LocalDate objects?
Authentication
81 questions- What role does the header play in a JWT token?
- In the context of JWT, what is the primary purpose of the signature?
- How can a Java developer verify the signature of a JWT using HMAC SHA-256?
- How would you explain a significant consequence of using stateless JWT tokens for authentication in an…
- Which statement about JWT payloads is correct?
Build Tools
48 questions- Why can automatic transitive dependency management in build tools like Maven or Gradle become a problem in…
- In a Maven project, where do you declare a dependency for a new library you want to use?
- Which Maven command would you use to ensure that the project is cleaned and rebuilt, including tests?
- When using Maven, which phase is responsible for verifying the quality of the code by running integration…
- In a Maven project, how are dependencies typically fetched?
Career Growth
20 questions- Which JVM feature is crucial for optimizing performance in large-scale Java applications?
- How would you explain an essential aspect of owning the production deployment lifecycle in an interview?
- How would you explain an effective communication strategy for a senior engineer during a post-mortem…
- Why does starting with a brute force solution during a live coding session help in practice?
- In terms of memory architecture, what should a Senior Engineer consider when optimizing a Java application?
Core Java
473 questions- In a nested try-catch block, if an exception is thrown in the inner try block and not caught there, what…
- What does executing a throw statement inside a catch block evaluate to?
- In Java, what happens if an exception is thrown in a method and not caught within that method?
- Which method would you use to add an element to a List at a specific position?
- Consider the following code snippet. What is the issue with the 'applyDiscount' method?
Dependency Injection
26 questions- Why might you prefer constructor injection over field injection when unit testing?
- In Spring Boot, how can you ensure that a bean is eagerly initialized at startup?
- What advantage does constructor injection offer over field injection concerning encapsulation?
- In Spring Boot, how does lazy initialization of beans affect constructor injection?
- How does Spring Boot handle dependency injection when multiple beans match the type being injected?
Distributed Resilience
67 questions- Why do teams use a circuit breaker in a microservices architecture in production code?
- Which problem might occur if correlation IDs are not propagated consistently across all services in a…
- How would you explain a common approach to implementing retries in a microservices-based Java application in…
- What could be a consequence of setting a very high threshold for failure in a circuit breaker?
- Which of the following best describes the 'Database-per-Service' pattern in a microservices architecture?
Engineering Interviews
91 questions- When transitioning to a Senior Engineer role, which trait is most critical for mentoring junior developers?
- In the context of JVM memory architecture, what is the primary role of the 'stack'?
- Why is it important to first outline a high-level design before diving into coding during a system design…
- During a live coding interview, why is it important to verbalize your thought process?
- What does the 'Result' component in the STAR framework mainly aim to achieve?
Garbage Collection
24 questions- Which tool can you use to analyze heap dumps in Java?
- In a Generational Garbage Collector, what triggers an object to move from the Young Generation to the Old…
- Why does Generational Garbage Collection help in practice?
- In the context of the Weak Generational Hypothesis, which statement is true about object lifespans?
- Why might a Java application experience increased garbage collection times during high traffic?
HTTP JSON APIs
27 questions- When defining API versioning strategies, what is a key benefit of using URL paths over HTTP headers?
- Why might an API client crash if JSON response shapes are not treated as strict contracts?
- Why might you choose to use an API gateway in conjunction with API versioning?
- In the context of Java's HttpClient, which method allows you to perform an asynchronous HTTP request?
- How can you ensure that a Java application using HttpClient does not suffer from resource exhaustion during…
Java Annotations
73 questions- Why do teams use Annotation Processors in Java in production code?
- Which reflection method would you use to check if a specific runtime annotation is present on a class?
- Given the following custom annotation, what is the default retention policy if none is specified?
- Why does the setAccessible(true) method in Java reflection matter in practice?
- How does breaking encapsulation using setAccessible(true) impact a Java application?
Java Interview Questions
400 questions- When should a Java developer choose ArrayDeque as a Stack deliberately?
- When should a Java developer choose TreeSet and NavigableSet deliberately?
- In Java, which comparison about ExecutorService, Future, and CompletableFuture is accurate?
- Which practice avoids a common mistake with Java Memory Model, volatile, and synchronized?
- When should a Java developer choose ConcurrentSkipListMap deliberately?
Java Threading
62 questions- Which method in ExecutorService is used to submit a Callable task?
- Which method would you use to create a Virtual Thread in Java?
- Which ExecutorService method can submit a Runnable for execution?
- What happens if a task throws an unchecked exception in an ExecutorService?
- Which method in ExecutorService can be used to attempt a graceful shutdown, allowing current tasks to…
JVM Architecture
28 questions- Why is lazy loading of classes beneficial in a Java application?
- Which tool can be used to analyze Metaspace memory usage in a running JVM?
- How would you explain the key difference between PermGen and Metaspace in an interview?
- Which JVM diagnostic tool provides thread dump information?
- In the context of JVM Garbage Collection, what role does Metaspace play?
Language Upgrades
67 questions- When refactoring an e-commerce application's checkout flow to use Java's switch expressions, what must be…
- Which of the following is a correct use of a switch expression in Java?
- How can sealed classes help in managing a complex class hierarchy in an e-commerce application?
- When using a switch expression with pattern matching, what is a potential benefit compared to using multiple…
- How does pattern matching for instanceof improve code readability and maintainability?
Memory Management
27 questions- What role does Metaspace play in Java's memory management?
- Which JVM flag would you use to analyze memory allocation and garbage collection behavior?
- Why does a reference variable in Java memory management matter in this design?
- A service that creates many runtime proxies crashes with OutOfMemoryError: Metaspace. What is the most…
- Why do teams use the 'jstack' tool in Java in production code?
Microservice Architecture
99 questions- In a microservices architecture, why is it important to use a database-per-service pattern?
- In a microservices architecture using Kafka, what is a typical approach to manage distributed transactions?
- Which of the following best describes the concept of immutable Docker images?
- In the context of microservices, what challenge does Eventual Consistency address?
- How would you explain a key consideration when implementing distributed tracing in a microservices…
Modern Java
185 questions- What could be a downside of overusing Java records in domain models?
- Given an enum with a method, how can each constant have a different implementation of that method?
- What keyword is used to define a Java Record?
- Which pattern is effectively implemented when using enums to represent singletons?
- How can you iterate over all constants of an enum in Java?
Networking
127 questions- How does an HttpClient distinguish between client and server errors?
- What does the HttpClient.newHttpClient() method do?
- Why is it useful to configuring FAIL_ON_UNKNOWN_PROPERTIES to false in Jackson's ObjectMapper?
- How would you explain a common issue when using ObjectMapper to deserialize nested JSON objects into Java…
- What happens if you attempt to deserialize a JSON array into a Java class with Jackson and…
OWASP Vulnerabilities
64 questions- Why is it risky to use string concatenation to build SQL queries?
- How would you explain a potential limitation of using only CSRF tokens for preventing CSRF attacks in an…
- In a Spring Security filter chain, what is the purpose of filters?
- What role does the 'Signature' play in a JWT?
- Why does the 'signature' in a JWT matter in this design?
Performance Tuning
67 questions- Why does a memory leak on JVM performance change runtime behavior?
- In a system using the Z Garbage Collector (ZGC), what is a notable advantage compared to traditional…
- How would you explain a common cause of a 'java.lang.OutOfMemoryError: Metaspace' error in a JVM application…
- How would you explain a key advantage of the Z Garbage Collector (ZGC) over traditional garbage collectors…
- CPU is pinned and requests are hanging. Which artifact tells you what threads are doing right now?
Project Reactor
62 questions- What does the Mono.just(T data) method do?
- In the context of Reactive Streams, what role does a Subscriber play?
- If a Mono completes empty, which of the following methods can be used to provide a default value?
- When transitioning from Spring MVC to WebFlux, what is a key advantage concerning server performance?
- When using Mono<User> in a reactive system, how should you handle a database call to ensure it remains…
Project Structure
38 questions- Why does a build tool like Maven in managing dependencies for a Java project matter in this design?
- Why might you choose to use integration tests despite their higher resource cost compared to unit tests?
- Why do teams use Continuous Integration in software development in production code?
- Which JUnit assertion would you use to verify that a method returns a null value?
- Why is it important to have strong encapsulation in a module system like JPMS?
Reactive Streams
120 questions- Why is it important to avoid blocking operations on the Event Loop in a Reactive Streams application?
- Which backpressure choice is usually most acceptable for a live price-ticker UI that only needs the newest…
- Why can using onBackpressureDrop in a high-throughput system become a problem in production code?
- In Reactive Streams, what does a Publisher do?
- How does Project Reactor's Flux handle backpressure by default?
Reflection API
77 questions- Which of the following describes the correct use of MethodHandles.lookup() to access a class’s private method?
- Given using Class.forName("com.example.MyClass") in Java, what outcome should you expect?
- Which method would you use to check if a class is an interface using Reflection?
- In what scenario would you prefer reflection for method invocation over direct method calls?
- Which of the following is NOT a drawback of using Java Reflection?
Software Architecture
60 questions- How would you explain a key advantage of using the Builder pattern when constructing an object with many…
- How can the Builder pattern be leveraged to support different configurations of an object, such as…
- What aspect of the Builder pattern makes it particularly suited for constructing immutable objects?
- How does the Builder pattern help in validating the legal states of the constructed object?
- In what scenario might the Builder pattern not be the best choice for object construction?
Spring Core
144 questions- Why do teams use Spring Profiles in a Spring Boot application in production code?
- In a Spring Boot application, what happens if a method annotated with @Transactional calls a private method…
- Which layer should coordinate inventory checks, payment, and order persistence for a checkout request?
- What role do Entities typically play in a Spring Boot application?
- How can you externalize configuration in a Spring Boot application?
Spring Security
23 questions- When configuring Spring Security, which filter should be placed first in the filter chain to handle…
- What HTTP response code does Spring Security typically return for unauthorized requests?
- In a stateless JWT token, what component ensures the token's integrity and prevents tampering?
- How does Spring Security handle a request identified as a potential CSRF attack?
- Why is separating authentication from authorization important in a real system?
SQL for Java Devs
172 questions- Why is it important to disable auto-commit mode for a JDBC transaction when performing multiple updates?
- How can JDBC transactions help maintain data integrity during an e-commerce checkout process?
- What would be the effect of not closing a PreparedStatement in a Java application?
- In JDBC, how do you ensure that SQL injection is prevented when executing a query that searches for a user…
- Why do teams use SQL JOINs to fetch relational data in a single query in production code?
System Design
39 questions- During a live coding session, you're asked to calculate the time complexity of your solution. What is the…
- If an interviewer says inventory accuracy is critical during checkout, which design statement is strongest?
- You are reviewing a codebase and spot a potential security issue. Which practice is most effective for…
- Which approach is the strongest way to start a senior system-design answer?
- When discussing SQL databases, what does ACID stand for, and why is it important?
Testing
80 questions- In a Gradle project, how can you ensure that integration tests are only run after unit tests have passed?
- How can build tools like Maven help manage library dependencies in Java projects?
- Why might you choose to use integration tests over unit tests for certain components in an e-commerce…
- Which benefit of automated unit testing is most critical for maintaining large Java projects?
- How would you explain a significant advantage of using mocks at the boundary of a system, rather than the…