Practical Java & Spring Boot Practice Questions & Quiz

40 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 (40 questions)

Q1

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

Answer: Implement both from the same immutable fields so objects equal by equals() return the same hashCode()

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 AutoCloseable 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 choose an absence policy such as orElseThrow()

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 standard Collector or an associative reduce operation

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: Use 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 the two futures with thenCombine() and define failure handling such as exceptionally()

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: List<? super Integer>

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 with 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 can race and leak across requests

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-specific settings, selecting the profile and supplying secrets through external configuration

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 normally bypasses the Spring proxy, so B's new transaction semantics may not be applied

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: An unhandled RuntimeException normally triggers rollback; checked-exception policy can be declared with rollbackFor when needed

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, publish asynchronously through an outbox, and apply the result in another transaction

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 annotate the controller argument with @Valid

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 as a group with @ConfigurationProperties and apply validation 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: Make repeated PUTs of the same representation produce the same final state through replacement or deterministic update

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 checking job status

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: @RestControllerAdvice with @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 when handler metadata is needed

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 on state-changing requests

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 in Spring MVC or Spring Security 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 trusted issuer's 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: Structurally log correlation ID, route, outcome, and duration while masking or excluding credentials and sensitive bodies

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 required relationships in bulk using a fetch join, EntityGraph, or DTO projection

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 required 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: Optimistic locking with @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: Define a stable unique order and use keyset pagination based on the last retrieved 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 with a suitable batch size 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 choose dynamic 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 roll out backward-compatible changes 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 controller 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: Run integration tests against the target PostgreSQL version with 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 behavior that occurs only 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: Use separate Actuator liveness and readiness probes, considering dependencies in readiness when removing traffic

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, then use graceful shutdown with enough termination grace to finish in-flight work

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 connection and response timeouts, bounded retries, a circuit breaker, and isolation

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, TTL jitter, and proactive refresh where appropriate

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 both the business result and processed-event record in one database 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 when sizing heap, and monitor GC, RSS, and OOM kills

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.

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.