Practical Java & Spring Boot Practice Questions & Quiz

70 questions / 10 random questions

Java design concurrency Spring DI and transactions web and security JPA testing and operations
Try a 10-question Practical Java & Spring Boot quiz

Random questions, instant feedback, and review for missed questions.

Start quiz →

View recommended Practical Java & Spring Boot resources →

Included topics (70 questions)

Q1

When using a custom class as a HashMap key, which equals() and hashCode() implementation is appropriate?

Answer: Implement both equals() and hashCode() from the same immutable fields

Objects that are equal according to equals() must return the same hash code. Deriving both methods from fields that do not change while used as keys preserves correct bucket lookup.

Q2

Files and JDBC resources must be closed reliably even when an exception occurs. Which Java approach is most appropriate?

Answer: Declare the resources in try-with-resources

Try-with-resources closes AutoCloseable resources in reverse order and retains close failures as suppressed exceptions when the body also fails.

Q3

Which service-method design appropriately uses Optional to represent a possibly absent result?

Answer: Return Optional and let the caller decide the absence policy

Using Optional as a return type makes possible absence explicit in the API contract. The caller can choose an exception, fallback value, or alternate business flow.

Q4

Which implementation is safe and clear when aggregating elements with a parallel Stream?

Answer: Avoid shared mutable state and use a Collector or an associative reduce

Parallel streams split and combine work, so aggregation should avoid shared mutable state and remain stable under different grouping orders. Standard collectors implement suitable reduction behavior.

Q5

Multiple threads increment a shared counter, and lost updates must be prevented. Which approach is appropriate?

Answer: Increment with AtomicLong.incrementAndGet()

incrementAndGet() performs read, increment, and write atomically. volatile provides visibility but does not make the compound count++ operation atomic.

Q6

Two external APIs should be called concurrently with CompletableFuture and their successful results combined. Which method is appropriate?

Answer: Combine both futures with thenCombine() and define failure handling

Starting independent futures before combining them with thenCombine() preserves concurrency. External I/O also requires timeouts, exception mapping, and an appropriate executor.

Q7

A DTO must not change after an order is finalized. Which design is appropriate?

Answer: Use final fields or a record and defensively copy mutable collections

An immutable object prevents observable state changes after construction. A final reference does not freeze its target, so mutable collections require defensive copies or unmodifiable exposure.

Q8

Under the PECS rule, which parameter type can consume Integer values by adding them to a list?

Answer: Use List<? super Integer> as the parameter type

PECS means Producer Extends, Consumer Super. A consumer that accepts Integer values uses List<? super Integer>, allowing a list of Integer or one of its supertypes.

Q9

Which Spring dependency-injection approach best exposes required dependencies and supports testability for a service class?

Answer: Constructor injection taking the repository as a required argument

Constructor injection requires dependencies at creation time, supports final fields, and lets unit tests pass test doubles without starting the Spring container.

Q10

What is wrong with storing a request-specific user ID in a field of a singleton-scoped Spring service?

Answer: Concurrent requests share the instance, so user IDs get mixed up

A Spring singleton bean is normally shared across the application. Request-specific state belongs in method arguments or an appropriate scope, while shared services should generally remain stateless.

Q11

Which Spring Boot configuration approach appropriately switches endpoints among development, staging, and production?

Answer: Separate common and profile settings and supply secrets externally

Spring Boot externalized configuration and profiles allow the same artifact to receive environment-specific values, including secrets from a secret store. This separates deployment differences from code.

Q12

What must be considered when a @Transactional public method A calls another @Transactional method B in the same service through this?

Answer: Self-invocation bypasses the proxy, so B's transaction attributes may not apply

With proxy-based declarative transactions, interception occurs when calls enter through the proxy. If self-invocation is expected to apply semantics such as REQUIRES_NEW, move the boundary to another bean or otherwise make it explicit.

Q13

A RuntimeException is thrown from a @Transactional method. Which statement describes the standard rollback behavior?

Answer: Unhandled RuntimeException rolls back; use rollbackFor for checked exceptions

By default, Spring rolls back for RuntimeException and Error. Checked and business exceptions need an explicit policy, and swallowed failures may require marking the transaction rollback-only.

Q14

Which order-processing design avoids holding a database transaction during a slow external payment API call?

Answer: Record state in a short transaction and integrate asynchronously via an outbox

Separating external I/O from the database transaction and atomically recording state plus an event keeps locks short. The asynchronous side needs idempotency, retries, and compensation.

Q15

How should a Spring MVC request DTO declaratively validate email format and required fields?

Answer: Add Bean Validation constraints to the DTO and use @Valid on the controller argument

Combining constraints such as @NotBlank and @Email with @Valid validates input before controller processing. A centralized exception handler can standardize error responses.

Q16

Many related settings should be type-safe and validated at startup. Which Spring Boot approach is appropriate?

Answer: Bind them with @ConfigurationProperties and validate with constraints

@ConfigurationProperties binds values under a prefix into a typed object. Validation can fail startup when required configuration is missing or invalid.

Q17

Which REST API design makes retries of PUT /users/123 safe?

Answer: Update by replacement so repeated PUTs of the same representation yield the same state

PUT should be idempotent: repeating the same request has the same intended final state. Operations with duplicate creation effects need a different design or an idempotency key.

Q18

An asynchronous job creation request has been accepted, but processing is not complete. Which HTTP response is appropriate?

Answer: Return 202 Accepted with a Location or identifier for status checks

202 indicates that a request was accepted but processing is not yet complete. Provide a job resource through which clients can observe progress, results, or failure.

Q19

Business exceptions from multiple controllers must be converted into one consistent JSON error format. Which Spring MVC feature is appropriate?

Answer: Handle them centrally with @RestControllerAdvice and @ExceptionHandler

@RestControllerAdvice centralizes cross-controller exception handling and maps exception types to HTTP status codes and safe error bodies.

Q20

You need correlation IDs for all HTTP requests and separate authorization-related logic around controller invocation. Which division is appropriate?

Answer: Use a Servlet Filter for correlation IDs and a HandlerInterceptor for handler-aware work

A Filter handles requests and responses broadly at the servlet chain. An Interceptor runs around Spring MVC handler execution and suits logic that needs controller or annotation metadata.

Q21

A web application uses cookie-based login. Which control prevents unintended state-changing requests made with the user's credentials?

Answer: Enable Spring Security CSRF protection and validate the token

Browsers automatically send the target site's cookies, allowing an attacker site to trigger state changes. A CSRF token validates that the request includes a value the attacker cannot supply.

Q22

A cross-origin SPA calls a Spring Boot API. You must restrict allowed origins and methods. Which approach is appropriate?

Answer: Configure CORS with explicit trusted origins, methods, and headers

CORS should narrowly define trusted callers and the necessary methods, headers, and credential behavior. It is separate from authentication and authorization, so both controls remain necessary.

Q23

A Spring Boot API is protected as an OAuth 2.0 resource server. What must be validated for JWT access tokens?

Answer: Validate the issuer signature, iss, exp, and the API audience and authorities

Readable JWT content does not prove authenticity. Validate the signature with trusted keys, standard claims, expiration, intended audience, and required scopes or roles.

Q24

Which request-logging design is appropriate for a production API?

Answer: Log correlation ID, route, outcome, and duration structurally and mask secrets

Logs should be structured for search and aggregation and use correlation IDs for tracing. Tokens, cookies, passwords, and personal data should be minimized, masked, and subject to retention limits.

Q25

A list API lazily loads related entities, issuing one list query followed by one query per row. Which improvement is appropriate?

Answer: Fetch only the required relationships in bulk with a fetch join or EntityGraph

Resolve N+1 queries by defining a use-case-specific fetch plan. DTO projections avoid unnecessary data; fetch joins and similar approaches require attention to duplicate rows and pagination.

Q26

A controller accesses a lazy relationship after the transaction ends and receives LazyInitializationException. Which design is appropriate?

Answer: Load data inside the service transaction and return an API DTO

Load use-case data within an explicit service transaction and map it to an external DTO. This keeps the web layer independent of the persistence context.

Q27

Which JPA feature prevents silent last-write-wins when multiple users edit the same entity?

Answer: Detect conflicts with optimistic locking via @Version

A @Version column includes the previously read version in the update condition. If another update occurred, the row-count mismatch detects the conflict so the user can reload or merge.

Q28

A large, frequently updated order table must be paged while reducing duplicate or missing rows and deep OFFSET cost. Which approach is appropriate?

Answer: Use keyset pagination with a stable unique order and the last key

Using a stable unique order such as creation time plus ID and querying after the previous last key avoids deep OFFSET scans. Define how concurrent updates and snapshot expectations are handled.

Q29

Tens of thousands of rows must be inserted with JPA while controlling memory use. Which batch approach is appropriate?

Answer: Persist in batches and call flush() and clear() periodically

Combining JDBC batching with periodic flush and clear reduces database round trips and persistence-context growth. Identifier generation strategy can also affect batching.

Q30

When passing user input into a MyBatis query, which basic binding prevents SQL injection?

Answer: Bind values with #{value} and pick identifiers from an allowlist

#{} binds a value as a PreparedStatement parameter. Identifiers such as table or ORDER BY column names cannot be parameterized, so map client choices to a server-side allowlist.

Q31

A Spring Boot application runs on multiple instances. Which approach safely delivers database schema changes?

Answer: Version ordered migrations with Flyway and apply them in stages

Treat migrations as immutable versioned history and order changes using techniques such as expand-and-contract so old and new application versions can coexist. Define single execution and failure recovery.

Q32

You want a lightweight test of controller routing, validation, JSON responses, and security without starting the database or every bean. Which test is appropriate?

Answer: Use @WebMvcTest with MockMvc and replace dependencies with test doubles

A web slice test limits context to Spring MVC concerns and uses MockMvc to exercise routing, conversion, validation, filters, and security integration.

Q33

PostgreSQL-specific SQL and migrations must be verified in CI. Which approach reduces false confidence from H2 differences?

Answer: Test against the target PostgreSQL version started by Testcontainers

A reproducible real PostgreSQL container verifies dialect, types, constraints, indexes, and migrations under production-like database behavior.

Q34

An integration test is @Transactional and rolls back after completion. Which issue can it easily miss?

Answer: Constraint violations or event handling that only happen on flush or commit

SQL may be deferred within the persistence context. Explicitly flush when testing database errors, and use a separate test with real transaction completion for after-commit behavior.

Q35

A Spring Boot application runs on Kubernetes. How should process liveness be separated from traffic readiness?

Answer: Separate liveness from readiness and consider dependencies only in readiness

Liveness represents a process failure recoverable by restart, while readiness indicates whether the instance can currently serve traffic. Avoid restart storms caused by a shared external database failure.

Q36

Which Spring Boot operational design reduces interruption of in-flight requests during a rolling update?

Answer: Remove readiness first and finish in-flight work with graceful shutdown

Stop new traffic by removing the instance from load balancing, then let graceful shutdown complete in-flight requests within the grace period. Coordinate this with Kubernetes preStop and terminationGracePeriod.

Q37

An external API becomes slow or fails. Which design limits cascading failure into the calling Spring Boot service?

Answer: Combine timeouts, bounded retries, and a circuit breaker

Bound call duration and concurrency and retry only transient failures with backoff. A circuit breaker fails fast during sustained failure, preventing resource exhaustion and cascades.

Q38

A hot cache key expires under load and many requests hit the database simultaneously. Which mitigation is appropriate?

Answer: Combine per-key single-flight loading with TTL jitter

For a cache stampede, single-flight loading lets one request refresh while others wait, and TTL jitter avoids synchronized expiry. Serving briefly stale data may also fit some requirements.

Q39

Which consumer design avoids creating the same order twice when a broker redelivers an event?

Answer: Use a unique event ID and save the result and processed record in one transaction

At-least-once delivery requires assuming duplicates. Persisting a unique event key atomically with the business update lets redelivery be recognized without repeating the side effect.

Q40

Which JVM configuration and monitoring approach helps a Spring Boot application run reliably within a container memory limit?

Answer: Budget non-heap memory, leave headroom, and monitor GC, RSS, and OOM

A JVM process uses heap plus metaspace, thread stacks, direct buffers, and native libraries. Size heap with headroom below the container limit and tune it from observed behavior.

Q41

What is the primary goal of using virtual threads in a Java 21 server where many requests wait on blocking I/O?

Answer: Reduce thread-waiting cost and raise concurrency with synchronous code

Virtual threads can release their carrier while blocked, allowing many I/O-bound tasks to share a smaller set of OS threads. They do not make each task faster or remove external resource limits.

Q42

After adopting virtual threads, an API backs up waiting for database connections under load. What is the appropriate response?

Answer: Measure the pool and database capacity and bound concurrency to them

Virtual threads reduce the cost of blocked threads but do not increase database or downstream capacity. Design bulkheads and timeouts from queue depth, connection utilization, and wait time.

Q43

Order states must be limited to a finite set, and missing switch handling should be detectable at compile time. Which Java design fits?

Answer: Model states with a sealed interface and records and use an exhaustive switch

A sealed type restricts possible implementations. Enumerating permitted types in a switch makes omissions easier to detect when a new state is added.

Q44

A method annotated with @Async runs synchronously when invoked through this within the same bean. What is the main cause and remedy?

Answer: Self-invocation bypasses the proxy, so move it to another bean

With standard proxy-based interception, advice applies to calls entering through the proxy. A this call within the target instance bypasses that proxy.

Q45

Bean Validation should also apply to public service-method parameters. Which approach is appropriate?

Answer: Enable method validation and add @Validated plus constraints to the bean and parameters

Spring method validation can declare parameter and return-value constraints at bean boundaries beyond controllers. Proxy invocation requirements must also be considered.

Q46

Which understanding of @Transactional(readOnly = true) on a query-only service operation is correct?

Answer: It signals read-only intent and hints but does not guarantee write prohibition

readOnly conveys intent to transaction and ORM infrastructure and may optimize behavior such as flushing. Enforcement depends on the manager and database, so permissions and tests still matter.

Q47

Updates to the same inventory row must be serialized briefly, waiting or failing on contention. Which JPA mechanism is appropriate?

Answer: Use a PESSIMISTIC_WRITE lock with a short transaction and lock timeout

Pessimistic locking uses database row locks to control conflicting updates. Manage lock order, timeouts, and transaction duration to reduce deadlocks and waits.

Q48

A list API loads full entities and associations, causing memory pressure. Which Spring Data JPA design returns only required columns?

Answer: Define a DTO or interface projection as the query result

A projection selects the columns needed by the API directly and reduces entity management and unnecessary association loading. It also separates update entities from read views.

Q49

A public API needs standardized errors with fields such as type, title, status, and detail. Which Spring MVC type is appropriate?

Answer: Return application/problem+json using ProblemDetail

ProblemDetail represents the RFC Problem Details format with standard fields and extension properties. It supports a machine-readable contract while hiding internal details.

Q50

When adding a field to an API response DTO, what basic policy best preserves backward compatibility with existing clients?

Answer: Make the added field optional and require tolerance of unknown fields

An additive change under tolerant-reader expectations is a common compatible response evolution. Required fields and type or semantic changes need versioning or a migration window.

Q51

A Spring listener should run only when the service's database update commits. Which feature is appropriate?

Answer: Use @TransactionalEventListener with AFTER_COMMIT

@TransactionalEventListener binds a listener to a transaction phase and defaults to AFTER_COMMIT. If reliable external delivery is required, use a durable approach such as an outbox.

Q52

Which design avoids losing an event when a failure occurs between an order database update and publishing to a message broker?

Answer: Save the update and an outbox row in one transaction and publish separately

A transactional outbox atomically persists business data and delivery intent. A publisher retries pending rows, while consumers use event IDs for idempotency.

Q53

When using Spring RestClient for an external API, what basic design safely handles connection failures and 5xx responses?

Answer: Configure timeouts, status-based error mapping, and retries only for idempotent calls

Bound external calls with deadlines and translate HTTP statuses and transport failures into domain errors. Limit retries with attempts, backoff, and jitter, and protect non-idempotent operations with idempotency keys.

Q54

Authorization must be enforced at service methods so calls outside controllers are also protected. Which approach is appropriate?

Answer: Enable method security and apply @PreAuthorize plus ownership checks

Authorization belongs at server-side business boundaries and must compare the authenticated principal with the target resource. Combine URL and method security as defense in depth.

Q55

What is an appropriate production policy for exposing Spring Boot Actuator?

Answer: Expose only required endpoints and protect them with authentication and authorization

Actuator provides useful health and metrics data but can expose configuration and internals. Minimize exposure and protect management access with network controls or a dedicated security chain.

Q56

After adding user IDs as tags to Micrometer HTTP request metrics, the number of time series explodes. What is the appropriate improvement?

Answer: Keep tags low-cardinality and move per-user investigation to logs or traces

High-cardinality tags increase monitoring backend memory, cost, and query latency. Use metrics for aggregate dimensions and traces or structured logs for individual requests.

Q57

A trace ID disappears from logs after work moves to an @Async method. What is the appropriate response?

Answer: Propagate the observation context to the async side with a TaskDecorator or similar

Thread-local context may not automatically cross an executor boundary. Configure Micrometer Observation context propagation so task submission captures and execution restores it.

Q58

During a service cache update, the database transaction rolls back but the cache keeps the new value. What is the appropriate improvement?

Answer: Bind cache mutation to post-commit or invalidate after database success

A cache usually does not share atomicity with the database transaction, so mutate or invalidate it according to commit outcome. Retry and bounded TTL also belong in the consistency strategy.

Q59

A Spring Boot integration test should isolate an external payment API while verifying the HTTP contract and timeout handling. Which approach is appropriate?

Answer: Use a mock HTTP server controlling responses and delays through the real client setup

A mock server such as WireMock preserves the network boundary while simulating statuses, headers, JSON, delays, and disconnects. It complements unit mocks and a small number of real integration tests.

Q60

A Spring Boot upgrade accumulated incompatibilities because library versions were pinned individually. Which dependency-management approach is appropriate?

Answer: Rely on the Spring Boot BOM versions and keep overrides minimal

Spring Boot dependency management supplies a tested version set. When an override is necessary, for example for security, inspect the dependency tree and run startup, integration, and regression tests.

Q61

A monetary CSV value "0.1" is parsed as double and passed to new BigDecimal(value), producing unexpected decimal digits. How should the original decimal value be preserved?

Answer: Pass the original decimal string directly to the BigDecimal constructor.

Parsing through double introduces a binary approximation. new BigDecimal("0.1") preserves the decimal input directly. Treat input parsing and business-defined rounding as separate steps.

Q62

Prices use BigDecimal. new BigDecimal("2.0") and new BigDecimal("2.00") must count as the same price despite different scales. Which comparison fits?

Answer: Check whether compareTo returns zero to compare numeric values.

BigDecimal.equals includes scale and is false in this example. compareTo compares numeric magnitude and returns zero here. Converting arbitrary prices to double can collapse distinct values through rounding.

Q63

Calling add on Arrays.asList("A", "B") throws UnsupportedOperationException. How can the existing values be placed in a list whose size can change?

Answer: Construct a new ArrayList from the returned list, then add elements.

Arrays.asList returns a fixed-size, array-backed list. It permits replacement but not size changes. new ArrayList<>(Arrays.asList("A", "B")) copies the elements into a resizable list.

Q64

An internal ArrayList is exposed through Collections.unmodifiableList. Later additions to the internal list become visible to the caller. What explains this behavior?

Answer: It is an unmodifiable view, so changes to the backing list remain visible.

unmodifiableList is a view rather than an independent snapshot. It blocks modification through the returned reference but still reflects backing-list changes. Copy before exposing it if later structural changes must not appear; element mutability is a separate concern.

Q65

A Stream from an unchanged List is used for count, then reused to calculate a sum and fails. How should two terminal operations be performed on the same data?

Answer: Create a fresh Stream from the original List for each terminal operation.

A Stream pipeline is single-use. For an unchanged List, call list.stream() separately for each terminal operation. Closing a Stream or changing execution mode does not rewind it.

Q66

A cache lookup returns Optional. cached.orElse(loadFromDb()) queries the database even on a cache hit. Which change performs the query only when no value is present?

Answer: Pass a database-loading Supplier to orElseGet for evaluation only if empty.

Method arguments are evaluated before the call, so loadFromDb() runs before orElse. cached.orElseGet(() -> loadFromDb()) supplies deferred work invoked only when empty. Do not compute the database result before creating the Supplier.

Q67

Thread.sleep throws InterruptedException inside a Runnable. It should honor the stop request and preserve interrupt status for surrounding code. What should the catch block do?

Answer: Call interrupt on the current thread and return from the task.

Thread.sleep clears interrupt status when throwing InterruptedException. In this design, use Thread.currentThread().interrupt() and return, with cleanup in finally as needed. Swallowing the interruption prevents cooperative task termination.

Q68

Two beans implement Notifier, one for email and one for SMS. An order service needs only email without changing defaults at other injection points. How should this be expressed?

Answer: Use a Qualifier on the constructor parameter to select the email candidate.

A constructor-parameter Qualifier matching the email bean narrows candidates at that injection point. Primary changes default candidate selection, which is different from making a local choice without affecting other injection points.

Q69

A Spring Data JPA list returns Page, and its count query is expensive. The UI needs only whether more results exist, not total elements or pages. Which redesign fits?

Answer: Return Slice so the query need not provide a total element count.

Slice provides next-slice availability without requiring Page's total count metadata. It fits this UI and avoids the need for counting all matches. It does not automatically fix deep-offset costs; inspect the fetch query separately.

Q70

Expiry logic calls Instant.now directly, making tests just before and after expiry depend on real time. How should boundaries be reproduced without changing the OS clock?

Answer: Inject Clock and supply a fixed-time Clock for each boundary test.

Use Instant.now(clock) with an injected Clock. Tests can supply Clock.fixed at instants before, at, and after expiry, while production uses a ticking system clock. This isolates time acquisition from the comparison rules.

certdrill.dev is an independent, unofficial learning site and is not affiliated with LPI Japan, IPA, AWS, Microsoft Azure, or any exam provider. Questions and explanations are original content.