Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 119 ยท Practice and Review

Advanced Java Interview Questions

50 Advanced Java interview questions with concise answers on JDBC, JPA and Hibernate, Spring, Spring Boot, REST, testing, microservices and security.

Backend Java interviews rarely ask you to recite an API. They ask you to explain what happens: what a PreparedStatement protects you from, why a lazy collection blows up outside a transaction, why @Transactional sometimes does nothing, and how two services stay consistent without a shared database. This page collects 50 questions that come up again and again, grouped by level and then by topic, with short, accurate answers you can expand in your own words.

Try to answer each question out loud before you open it. If you can't explain an idea in two or three sentences, follow the link to its lesson and review it. Four questions ask you to read a program and predict its output; make your guess first, then press Run.

Tip: a strong answer has three parts: the definition, a tiny concrete example, and a trade-off or pitfall ("this fixes N+1, but you can't combine it with paging"). The trade-off is what moves an answer from junior to senior.

Junior level

JDBC and SQL

What is JDBC, and what does a JDBC driver do?

JDBC is the JDK's standard API for relational databases (java.sql and javax.sql). Your code talks only to interfaces such as Connection, PreparedStatement and ResultSet; a vendor driver JAR (PostgreSQL, MySQL, H2) implements them and speaks the database's network protocol. Swapping databases is mostly a matter of changing the driver and the URL. Drivers register themselves through the service loader, so Class.forName(...) is no longer needed. Every higher-level tool, including Hibernate and Spring Data, runs on JDBC underneath. See JDBC Introduction.

What is the difference between Statement and PreparedStatement?

A Statement sends a finished SQL string, so any value has to be glued into the text. A PreparedStatement is created from SQL with ? placeholders, and values are bound separately with setString, setLong and friends. That has three benefits: values can never change the structure of the query (no SQL injection), quotes and dates are handled correctly (O'Reilly just works), and the database can reuse the parsed statement. Use PreparedStatement for every statement that contains a value; plain Statement is only for fixed DDL. See CRUD with JDBC.

Why should JDBC objects be opened in try-with-resources?

Connections, statements and result sets hold resources in the driver and on the database server. If you forget to close them, especially on an exception path, a connection pool slowly runs dry and the application hangs waiting for connections. Try-with-resources closes them automatically, in reverse order, whether the block finishes normally or throws. With a pool, close() doesn't end the physical connection; it returns it to the pool. See Connection Pooling and DataSource.

What is SQL injection, and how do you prevent it?

SQL injection happens when user input becomes part of a statement's structure. A login query built as "... where name = '" + name + "'" lets someone type admin' -- and comment out the password check, or append UNION SELECT to read other tables. The fix is to bind every value with PreparedStatement parameters (or named parameters in JPQL). Parts that can't be parameters, such as column names or ASC/DESC in ORDER BY, must come from an allow-list of fragments you wrote. Least-privilege database accounts are defense in depth, not the fix. See PreparedStatement and SQL Injection.

Code reading: NULL in a ResultSet

The table has one player with a score of 0 and one with no score at all. What does the program print? Decide before you run it.

Java Code reading - getInt and NULL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Explain the output of the getInt and NULL example.

It prints Ana 0 false 0 and then Ben 0 true null. Primitive getters such as getInt can't return null, so SQL NULL comes back as 0, and you can't tell "zero" from "unknown" by the value alone. wasNull() reports whether the last column read was NULL, and getObject(column, Integer.class) returns a real null. Map nullable columns to boxed types (Integer, Long) in your records.

HTTP and REST

What is REST?

REST is an architectural style for APIs over HTTP. You model the system as resources identified by URLs (/orders/42), manipulate them with the standard HTTP methods instead of inventing verbs in URLs (DELETE /orders/42, not POST /deleteOrder), exchange representations such as JSON, and report outcomes with status codes. Requests are stateless: each one carries everything the server needs, such as the auth token. Responses can be cacheable. Most "REST APIs" in practice follow these rules loosely, and that's fine as long as they're consistent. See REST API Design.

What do "safe" and "idempotent" mean for HTTP methods?

A safe method doesn't change server state: GET, HEAD and OPTIONS. An idempotent method has the same effect whether you send it once or five times: all safe methods plus PUT (replace the resource with this) and DELETE (the resource is gone either way). POST is neither, so sending it twice can create two orders, and PATCH isn't guaranteed to be idempotent. This matters for retries: clients and proxies may safely retry idempotent requests after a timeout, while POST needs an idempotency key. See How HTTP Works.

What is the difference between PUT, PATCH and POST?

POST usually creates a new resource in a collection (POST /books) and answers 201 Created with a Location header; it's also used for actions that don't fit other methods. PUT replaces the whole resource at a known URL with the representation you send; fields you leave out are reset. PATCH changes only the fields you send, for example with JSON Merge Patch, where an absent field means "unchanged" and null means "clear".

What is the difference between 401 and 403?

401 Unauthorized means the request isn't authenticated: no credentials, an expired token or a bad signature. The client should log in or get a new token, and the response carries a WWW-Authenticate header. 403 Forbidden means the server knows who you are, but you're not allowed to do this: you're missing a role or scope, or the resource belongs to someone else. Some APIs return 404 instead of 403 to avoid revealing that a resource exists. See Web Security Basics.

Spring basics

What are inversion of control and dependency injection?

Without IoC, a class creates its own collaborators (new JdbcOrderRepository(...)), which hard-wires it to one implementation and makes it hard to test. With dependency injection, the class declares what it needs, normally as constructor parameters typed by interfaces, and something else supplies them. Inversion of control is the broader idea: the framework, not your code, creates objects and controls their lifecycle. Spring's container builds the object graph at startup, and in tests you pass fakes into the same constructor. See Dependency Injection and Inversion of Control.

What is a Spring bean, and when do you use @Component versus @Bean?

A bean is an object created and managed by the Spring container. Annotate your own classes with @Component or one of its specializations (@Service, @Repository, @Controller) so component scanning finds them. Use a @Bean method inside a @Configuration class when you can't annotate the class (a third-party Clock, ObjectMapper or DataSource) or when building the object takes code. Both produce the same kind of bean. See Beans, Configuration and Component Scanning.

What does @SpringBootApplication do?

It combines three annotations. @SpringBootConfiguration marks the class as a configuration class. @EnableAutoConfiguration turns on Boot's auto-configuration, which creates beans based on the classpath and properties. @ComponentScan scans the main class's package and all packages below it, so put the main class in your root package; classes outside it are not found. SpringApplication.run(App.class, args) then creates the context and starts the embedded server. See Spring Boot Introduction.

Testing basics

What is the difference between a unit test and an integration test?

A unit test checks one class or a small group of classes in isolation, with collaborators replaced by fakes or stubs; it runs in milliseconds and needs no infrastructure. An integration test runs your code against real infrastructure: a database, an HTTP server, a message broker or the Spring context. It catches SQL mistakes, mapping errors and wiring problems that unit tests can't see, but it's slower. The test pyramid recommends many unit tests, fewer integration tests and very few end-to-end tests. See Integration Testing.

Mid level

Transactions and connection pools

What is autocommit, and how do you run several statements in one transaction with JDBC?

A new JDBC connection is in autocommit mode: each statement is its own transaction and commits immediately. To group statements, call setAutoCommit(false), run them, then commit(). If anything fails, call rollback() and rethrow, and restore autocommit in finally (important with pooled connections). In Spring you write @Transactional instead, and Spring binds one connection to the current thread for the duration of the method, so several repositories share the same transaction. See Transactions with JDBC.

What are the transaction isolation levels, and which anomalies do they prevent?

Read uncommitted allows dirty reads (seeing other transactions' uncommitted changes). Read committed, the default in PostgreSQL, Oracle and SQL Server, prevents dirty reads, but re-reading a row can give a different value (non-repeatable read). Repeatable read, the default in MySQL's InnoDB, keeps rows you read stable; the standard still allows phantoms (new rows matching your query), though PostgreSQL and InnoDB prevent most of them. Serializable behaves as if transactions ran one after another, at the cost of more blocking or retries. None of the lower levels stops a lost update by itself; use SELECT ... FOR UPDATE or optimistic locking.

Why use a connection pool, and what happens when it runs out?

Opening a database connection takes a TCP handshake, TLS and authentication, often several milliseconds. A pool such as HikariCP keeps a few connections open and lends them out, so getting one is nearly free. The pool also limits load on the database: when all connections are busy, the next request waits up to connectionTimeout and then fails, which is far better than overwhelming the database. Pools should be small (often 10 to 20, divided among app instances); slow queries and leaked connections, not a small pool, are the usual causes of exhaustion.

JPA and Hibernate

What is the difference between JPA, Hibernate and Spring Data JPA?

JPA (Jakarta Persistence) is a specification: annotations like @Entity, the EntityManager API and JPQL. Hibernate is the most popular implementation of it; it generates the SQL and adds features beyond the spec. Spring Data JPA sits on top and generates repository implementations from interfaces such as interface BookRepository extends JpaRepository<Book, Long>, including queries derived from method names. All three end up sending SQL through JDBC. See ORM and JPA Introduction.

What are the states of a JPA entity?

Transient: created with new, unknown to JPA. Managed: attached to a persistence context (after persist, find or a query); changes are tracked. Detached: was managed, but the persistence context closed or the entity was evicted; changes are no longer tracked. Removed: scheduled for deletion with remove(), deleted at flush. Most surprises in JPA come from not knowing which state an object is in. See Entity Lifecycle and Transactions.

What is dirty checking, and when does Hibernate flush?

When an entity becomes managed, Hibernate keeps a snapshot of its state. At flush time it compares each managed entity with its snapshot and writes UPDATE statements for the ones that changed, so inside a transaction book.setPrice(...) is enough and no save() call is needed. Flushing happens before commit, before queries whose results could be affected, and when you call flush(). Flushing sends SQL; only commit makes it permanent.

What is the difference between persist() and merge()?

persist(entity) makes a new (transient) object managed; the same instance is then tracked, and the insert happens at flush (immediately with IDENTITY ids). merge(entity) copies the state of a detached object onto a managed instance, loading it if needed, and returns that managed instance; the object you passed in stays detached. The classic bug is to keep using the argument after merge() and wonder why later changes aren't saved. Spring Data's save() calls persist for new entities and merge for others.

What is the difference between lazy and eager loading, and what causes LazyInitializationException?

Eager associations are loaded together with the entity; lazy ones are loaded on first access through a proxy or a smart collection. By default @ManyToOne and @OneToOne are eager and collections are lazy; the usual advice is to make everything lazy and fetch what each use case needs. LazyInitializationException happens when you touch a lazy association after its persistence context is closed, typically in a controller or a JSON serializer after the transaction ended. Fix it by fetching the data inside the transaction (join fetch, an entity graph) or by returning DTOs, not by switching to eager or leaving Open Session in View on. See Fetching Strategies and the N+1 Problem.

What is the N+1 query problem?

You run one query to load a list (N authors), then the code touches a lazy association on each element, which fires one more query per element: N + 1 queries in total. It's invisible in code and fine with 3 rows, but with 500 rows a page needs 501 round trips. Detect it by logging SQL or counting queries in tests. Fix it with a join fetch or an entity graph (one query), batch fetching (@BatchSize, a few IN queries) or a DTO projection. The next example reproduces the pattern with plain JDBC.

Java Code reading - counting the queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Explain the output of the query-counting example.

The loop prints Lazy loop: 5 queries: one for the four authors plus one per author. The join prints Join fetch: 1 query followed by every author with their books. With N authors, the first version always needs N + 1 queries, while the join needs one, however many authors there are. A LEFT JOIN keeps authors without books; Hibernate's left join fetch does the same assembly into entity collections for you.

What are the owning side and mappedBy in a bidirectional relationship?

In a bidirectional @OneToMany/@ManyToOne, both Java classes point at each other, but the database has one foreign key, in the book table. The side that maps that column (Book.author with @ManyToOne) is the owning side; Hibernate writes the relationship only from it. The other side declares @OneToMany(mappedBy = "author") and is just a view. If you add a book only to author.getBooks() without setting book.setAuthor(author), nothing is saved, so use helper methods that update both ends. See Entity Relationships.

Spring

Why is constructor injection preferred over field injection?

With constructor injection, dependencies are explicit in the signature, fields can be final, an object can never exist half-initialized, and tests just call new OrderService(fakeRepository, fixedClock) without Spring or reflection. A constructor with ten parameters is also an honest signal that the class does too much. Field injection (@Autowired on a private field) hides dependencies, needs reflection to test, and allows null fields. With a single constructor, Spring injects it without @Autowired.

What bean scopes exist, and what does "singleton" imply for your code?

singleton (the default) means one instance per application context; prototype creates a new instance on every lookup; web applications add request and session. Because a singleton serves all requests at the same time, it must be thread-safe: keep request data in local variables or parameters, and make fields immutable dependencies or thread-safe objects. To use a shorter-lived bean inside a singleton, inject an ObjectProvider<T> or a scoped proxy; otherwise you get one instance forever.

Two beans implement the same interface. How does Spring choose which one to inject?

Injection by type fails at startup with NoUniqueBeanDefinitionException if there are several candidates and nothing tells Spring which to use. Mark one as the default with @Primary, or ask for a specific one with @Qualifier("fast") at the injection point (a qualifier beats @Primary). If the parameter name matches a bean name, Spring uses that as a fallback. To get all of them, for example a chain of validators, inject List<PaymentValidator>.

How does @Transactional work, and why does it sometimes do nothing?

Spring wraps the bean in a proxy. Calls from other beans go through the proxy, which opens a transaction, calls your method and commits or rolls back. A call from one method to another in the same object (this.saveAuditEntry()) goes straight to the target and skips the proxy, so an annotation on the inner method is ignored. The same applies to private methods and objects you created with new, and to @Cacheable, @Async and @PreAuthorize. The next example builds such a proxy with java.lang.reflect.Proxy. See Aspect-Oriented Programming.

Java Code reading - self-invocation and proxies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Explain the output of the self-invocation example.

It prints BEGIN placeOrder, placing book, auditing book, COMMIT placeOrder. There's only one BEGIN/COMMIT pair: the proxy saw the outside call to placeOrder, but saveAuditEntry was called on this, the real object, so the proxy never knew. In Spring, @Transactional(propagation = REQUIRES_NEW) on saveAuditEntry would therefore be silently ignored. Fixes: move the method to another bean, or call it through the proxy (an injected self-reference); restructuring is usually cleanest.

When does @Transactional roll back?

By default it rolls back for unchecked exceptions (RuntimeException and its subclasses) and Error, and commits when a checked exception such as IOException escapes, which surprises many developers. Change it with @Transactional(rollbackFor = Exception.class). Catching an exception inside the method means the proxy never sees it, so the transaction commits. You can also mark it for rollback explicitly with TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(). readOnly = true is a hint that lets Hibernate skip dirty checking.

How does Spring Boot auto-configuration work?

Boot ships auto-configuration classes, listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Each one is a @Configuration guarded by conditions: @ConditionalOnClass (is HikariCP on the classpath?), @ConditionalOnMissingBean (did the user define their own DataSource?) and @ConditionalOnProperty (is a feature switched on?). So adding a starter adds classes, the conditions match, and beans appear; defining your own bean makes Boot back off. Run with --debug to see the condition evaluation report, and exclude a configuration with @SpringBootApplication(exclude = ...).

Spring Boot web and testing

What is the difference between @Controller and @RestController, and when do you return ResponseEntity?

A @Controller method usually returns a view name that a template engine such as Thymeleaf renders into HTML. @RestController is @Controller plus @ResponseBody: return values are written straight to the response body, as JSON through Jackson. Return a plain object when 200 OK is right; return ResponseEntity when you need another status or headers, such as ResponseEntity.created(location).body(dto) or noContent(). See Building REST APIs with Spring Boot.

How do you validate request bodies and return consistent errors in Spring Boot?

Add spring-boot-starter-validation, put Jakarta Bean Validation annotations on the input DTO (@NotBlank, @Size(max = 200), @Positive), and annotate the parameter with @Valid @RequestBody. Invalid input throws MethodArgumentNotValidException, which becomes 400. Handle errors in one place with a @RestControllerAdvice whose @ExceptionHandler methods map exceptions (including your domain exceptions such as BookNotFoundException) to ProblemDetail responses in RFC 9457 format. Log unexpected errors in full but return a generic 500. See Validation and Error Handling.

When do you use @WebMvcTest, @DataJpaTest and @SpringBootTest?

@WebMvcTest(BookController.class) starts only the MVC layer and gives you MockMvc; it's for routing, JSON, validation and status codes, with services replaced by @MockitoBean. @DataJpaTest starts JPA with an embedded database (or a Testcontainers one) and rolls back after each test; it's for repositories and queries. @SpringBootTest starts the whole application, optionally on a random port; keep these few because they're the slowest. Most business logic needs no Spring at all: plain JUnit tests with constructor injection. See Testing Spring Boot Applications.

What is the difference between a mock, a stub and a fake?

A stub returns canned answers (findById always returns this book) and lets you check the result, not the calls. A fake is a simple working implementation, such as an in-memory repository backed by a HashMap. A mock is programmed with expectations and verifies that certain calls happened (verify(mailer).send(...)). Prefer stubs and fakes for queries, and use mocks for side effects you can't observe otherwise, such as sending email or charging a card. Over-mocking ties tests to implementation details. See Test Doubles and Mockito.

Senior level

Data consistency and performance

What is the difference between optimistic and pessimistic locking?

Pessimistic locking takes a database lock up front (SELECT ... FOR UPDATE, LockModeType.PESSIMISTIC_WRITE), so other writers wait; it's simple and right for hot rows with frequent conflicts, but locks reduce throughput and can deadlock. Optimistic locking takes no lock: each row has a version column, and the update only succeeds if the version is still the one you read (where id = ? and version = ?). In JPA, @Version does this and throws OptimisticLockException on conflict; you reload and retry or report 409. It suits typical web apps where conflicts are rare. The next example shows the mechanism.

Java Code reading - optimistic locking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Explain the output of the optimistic locking example.

Alice's update matches version = 1, so it prints saved and bumps the version to 2. Bob's update still says version = 1, matches zero rows and prints conflict, reload and retry. The final line is Final: stock 7, version 2. Without the version check, Bob's write would set the stock to 6 and silently lose Alice's sale: a lost update. Bob's code should re-read (stock 7), apply his sale (3) and save again.

How would you find out why an endpoint has become slow?

Measure before guessing. Start with metrics and traces (Micrometer, OpenTelemetry) to see whether the time goes to the database, a downstream call or the JVM itself. For the database, turn on SQL logging or look at query counts per request (N+1 is the classic culprit), then use EXPLAIN to check for missing indexes. Check pool metrics: threads waiting for connections mean slow queries or leaks. For CPU or memory, take thread dumps with jcmd <pid> Thread.print, record a Java Flight Recorder profile, and check GC logs. Fix the biggest cost, then measure again. See Debugging and Profiling Tools and Actuator, Metrics and Observability.

Microservices and messaging

When would you choose microservices over a monolith?

Microservices split a system by business capability into services that are deployed independently and own their data. They pay off when several teams need to ship independently, when parts have very different scaling or reliability needs, and when boundaries are well understood. The cost is real: network calls instead of method calls, no cross-service ACID transactions, distributed debugging, and much more infrastructure. For a small team or an unclear domain, a modular monolith with strict package boundaries is usually the better start, and it can be split later along those boundaries. See Microservices.

How do you keep data consistent across services without distributed transactions?

Accept eventual consistency and coordinate with events. A saga breaks a business process into local transactions, one per service, each publishing an event that triggers the next; when a step fails, compensating actions undo earlier ones (refund the payment, release the stock). To publish events reliably, use the transactional outbox: write the business change and the event into the same database transaction, and let a relay send outbox rows to the broker afterward. That avoids "saved the order but lost the event". Two-phase commit across services is rarely used because it couples availability. See Messaging with Kafka and RabbitMQ.

Explain timeouts, retries and circuit breakers.

Timeouts on every remote call stop one slow dependency from tying up all your threads. Retries handle transient failures, but only for idempotent operations, with exponential backoff and jitter and a small limit, or they multiply load on a struggling service. A circuit breaker counts failures; when they cross a threshold it opens and fails fast without calling the dependency, after a pause it goes half-open and lets a few trial calls through, and on success it closes again. Add bulkheads (separate limits per dependency) and fallbacks. Resilience4j provides all of these, and Spring Framework 7 adds @Retryable and @ConcurrencyLimit.

What does at-least-once delivery mean, and how do you build idempotent consumers?

Most brokers guarantee that a message is delivered at least once: if a consumer crashes after processing but before acknowledging, the message comes again. Exactly-once end to end is very hard, so consumers must be idempotent: processing the same event twice must have the same effect as once. Give each event a unique id and record processed ids in the same transaction as the side effect (a unique constraint makes duplicates fail harmlessly), or make the operation naturally idempotent ("set status to PAID" instead of "add 10 euros"). The same idea applies to APIs with idempotency keys on POST.

What is the difference between Kafka and RabbitMQ?

RabbitMQ is a message broker: producers publish to exchanges, which route messages into queues; consumers acknowledge messages and they're removed. It's great for task distribution and flexible routing. Kafka is a distributed, partitioned log: records are appended and kept for a retention period, consumers track their own offsets and can replay history, and several consumer groups read the same topic independently. Order is guaranteed per partition (chosen by the record key). Choose RabbitMQ for work queues and routing, Kafka for high-volume event streams, replay and event sourcing.

When would you use reactive programming instead of virtual threads?

Both aim to serve many concurrent I/O-bound requests with few OS threads. Virtual threads (Java 21+) let you keep ordinary blocking code (JDBC, RestClient), which is far easier to write, debug and profile; since Java 24, synchronized blocks no longer pin them to carrier threads. Reactive stacks (Project Reactor, WebFlux, R2DBC) shine when you process true streams with backpressure, such as live feeds or large streaming pipelines, but every library in the call chain must be non-blocking. For typical request/response services, virtual threads are now the simpler default. See Reactive Programming.

Security

How should an application store passwords?

Never store them in plain text or with a fast hash like SHA-256. Use a slow, salted, adaptive algorithm: Argon2id, scrypt, bcrypt, or PBKDF2 with a high iteration count (around 600,000 for PBKDF2-HMAC-SHA256). The salt makes every hash unique, and the cost factor makes brute force expensive and can be raised over time. In Spring Security, PasswordEncoderFactories.createDelegatingPasswordEncoder() stores the algorithm with each hash (...) so you can migrate old hashes on login. Compare in constant time and never log passwords. See Spring Security.

Sessions or JWTs: which would you choose for authentication?

A server-side session stores state on the server and gives the browser a random id in an HttpOnly, Secure, SameSite cookie; it's simple, easy to revoke and ideal for classic web apps. A JWT is a signed, self-contained token that any service can verify without a lookup, which suits APIs and microservices, but it can't be revoked before it expires, so keep access tokens short-lived (minutes) and use rotating refresh tokens. Its payload is only Base64URL-encoded: signed means tamper-proof, not secret. Many systems use sessions for the browser and tokens between services.

What must a server check when it receives a JWT?

Parse the header but don't trust it: accept only the algorithms you expect (never none, never let alg switch from RS256 to HS256). Verify the signature with the right key (a shared secret for HS256, the issuer's public key from its JWK Set for RS256, picked by kid). Then check exp and nbf with a small clock-skew leeway, iss (the expected issuer) and aud (this API), and finally the scopes or roles for the operation. Missing or invalid tokens get 401; valid tokens without the right scope get 403. In Spring Boot, oauth2ResourceServer(jwt) with an issuer-uri does all of this. See JWT and OAuth 2.

What is the difference between OAuth 2 and OpenID Connect?

OAuth 2 is an authorization framework: it lets a client obtain an access token to call an API on a user's behalf (or on its own, with Client Credentials), without seeing the user's password. It doesn't define who the user is. OpenID Connect is an identity layer on top of OAuth 2: it adds the ID token (a JWT describing the authenticated user), a userinfo endpoint and standard claims, so it's what you use for "log in with...". For user-facing apps, use the Authorization Code flow with PKCE; the implicit and password flows are deprecated.

When do you need CSRF protection, and how is CORS different?

CSRF is an attack where another site makes the victim's browser send a request to your app, and the browser attaches your cookies automatically. You need protection whenever authentication is ambient (session cookies, HTTP Basic): use SameSite cookies, CSRF tokens on state-changing requests, and never change state on GET. APIs authenticated with a bearer token in the Authorization header aren't vulnerable, because browsers don't add that header by themselves. CORS is unrelated: it's a browser mechanism that lets listed origins read your responses from JavaScript. It isn't access control, and enabling it never protects anything.

Running Java in production

What should you know about running the JVM in a container?

Modern JVMs read the container's memory and CPU limits. By default the maximum heap is only 25% of the memory limit, so set -XX:MaxRAMPercentage (often around 75) and leave room for metaspace, thread stacks, direct buffers and the code cache; exit code 137 means the kernel killed the process for exceeding the limit. The CPU limit affects GC choice and default pool sizes. Use the exec form ENTRYPOINT ["java", ...] so the JVM receives SIGTERM and Spring Boot can shut down gracefully, run as a non-root user, and build with a multi-stage Dockerfile on a JRE base image. See Docker for Java Developers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A service method calls this.audit(), and audit() is annotated with @Transactional(propagation = REQUIRES_NEW). What happens?

    Spring's transactional behavior lives in a proxy around the bean. A call on this goes directly to the target object, so audit() simply joins whatever the caller is doing.
  2. 2. A page lists 200 orders and shows each order's customer name through a lazy association. How many queries run without any fetch tuning?

    One query loads the orders, then each lazy association fires its own query (assuming every order has a different customer). That's the N+1 problem.
  3. 3. Which statement about JWT access tokens is true?

    Standard signed JWTs are only Base64URL-encoded. Revocation needs short lifetimes or a deny list, and the server must enforce the algorithms it expects.
  4. 4. Two requests read a row with version 4. Both try update ... set version = 5 where id = 1 and version = 4. What happens?

    After the first update, the version is 5, so the second WHERE clause no longer matches. The zero row count is the conflict signal.
  5. 5. Why must message consumers usually be idempotent?

    A consumer that crashes after processing but before acknowledging gets the message again. Processing it twice must not charge a customer twice.

Summary

  • Junior questions check the foundations: JDBC and PreparedStatement, SQL injection, HTTP methods and status codes, REST, dependency injection, beans, Spring Boot basics and unit versus integration tests.
  • Mid-level questions focus on how the frameworks behave: transactions and isolation, connection pools, entity states, dirty checking, lazy loading and N+1, owning sides, proxies behind @Transactional, auto-configuration and test slices.
  • Senior questions are about trade-offs: locking strategies, diagnosing performance, microservice boundaries, sagas and the outbox, resilience patterns, messaging guarantees, virtual threads versus reactive, token security and running the JVM in containers.
  • Strong answers combine a definition, a small example and a pitfall, which is exactly what the live examples on this page practice.

You've reached the end of the Advanced Java course. Keep the cheat sheet handy, rebuild the projects such as A REST API from Scratch from memory, and come back to the Advanced Java course overview whenever you want to review a topic. Happy coding!