Java Full Stack with React Interview Questions for 10 Years Experience
40 questions with answers for candidates with 10+ years of experience — 10 medium, 30 hard.
What interviewers expect: 10 years experience
At ten years and above, candidates interview for architect, principal engineer or engineering manager roles. Conversations centre on business impact, platform strategy, modernising legacy Java systems, security and compliance, team structure and hiring. You may still face a design round, but leaders focus on judgement, communication with stakeholders and how you have grown engineers and delivered large programmes.
This set is weighted towards JPA and Hibernate (9), Collections and Streams (7), React Frontend (6), SQL and Databases (5).
Enterprise architecture Legacy modernisation Stakeholder management Building and growing teams
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
Write a Flyway migration to add a column and index to an existing table.
-- src/main/resources/db/migration/V3__add_sku_to_products.sql
ALTER TABLE products ADD COLUMN sku VARCHAR(40);
UPDATE products SET sku = CONCAT('SKU-', id) WHERE sku IS NULL;
ALTER TABLE products ALTER COLUMN sku SET NOT NULL;
CREATE UNIQUE INDEX ux_products_sku ON products (sku);
# application.yml
# spring.jpa.hibernate.ddl-auto: validate
# Flyway runs pending V-scripts in order at startup.
02
How do code splitting and lazy loading work in React?
Code splitting breaks the JavaScript bundle into smaller chunks loaded on demand, which improves first load time. React.lazy with a dynamic import, such as const Reports = lazy(() => import('./Reports')), loads the component only when it renders, and Suspense shows a fallback while it loads. Splitting by route is the most common pattern. Bundlers like Vite create the chunks automatically from dynamic imports.
Fail-fast iterators, used by ArrayList and HashMap, track a modification count and throw ConcurrentModificationException if the collection is structurally changed during iteration, except through the iterator's own remove. Fail-safe or weakly consistent iterators, used by CopyOnWriteArrayList and ConcurrentHashMap, work on a snapshot or tolerate concurrent changes and never throw that exception, but they may not show the latest updates.
04
Describe a time you improved the performance of an application.
Situation: our dashboard API took eight seconds and users complained. Task: I was asked to bring it under one second. Action: using SQL logs and a profiler, I found N+1 queries and a missing index. I rewrote the query with a DTO projection, added a composite index and cached reference data with a short expiry. Result: response time dropped to about 400 milliseconds, and I added the query-count check to our test suite.
05
You are loading about five lakh records into an ArrayList and a HashMap and memory spikes during loading. What can you do?
Both collections resize by copying when they grow, which causes temporary memory spikes. Pre-size them, for example new ArrayList<>(500000) and HashMap with capacity of expected size divided by 0.75. Better still, avoid holding everything at once: process the data in batches or stream it from the database with pagination. Use primitive-friendly structures or IntStream where possible to avoid boxing overhead.
06
Call three APIs in parallel and handle failure of any one gracefully.
Enable SQL logging or Hibernate statistics to confirm it is the N+1 problem, usually from lazy associations accessed while mapping entities to JSON. Fetch the required associations in one query with JOIN FETCH or @EntityGraph, or select a DTO projection with only the needed columns. For collections combined with pagination, page the parent IDs first and then fetch children with an IN query, or use batch fetch size. Add a test that asserts the query count.
08
A security test shows a stored XSS vulnerability in a comments feature. How do you fix it?
Stored XSS happens when user input containing script is saved and later rendered as HTML. React escapes text by default, so look for dangerouslySetInnerHTML, direct innerHTML or unsafe URL attributes like javascript: links. If rich text is required, sanitise it with a library like DOMPurify, and validate on the server too. Add a Content Security Policy header and keep tokens out of JavaScript-readable storage to limit damage.
09
Sort a list of products by category, then by price descending, then by name.
A component re-renders when its state changes, its parent re-renders, or a context it uses changes. Props changing is not itself the trigger; parent re-render is. During reconciliation React compares element types: a different type at the same position destroys and recreates the subtree, while the same type updates props. Keys identify list children. React.memo skips a child re-render when its props are shallowly equal.
Add a numeric or timestamp field annotated with @Version. Hibernate includes it in the UPDATE where clause and increments it. If another transaction already changed the row, no rows match, and an OptimisticLockException is thrown. This prevents lost updates without holding database locks, which suits web apps with low conflict. The API can return HTTP 409 and ask the user to reload. Pessimistic locking with SELECT FOR UPDATE suits high-conflict cases like seat booking.
12
Your Spring Boot service crashes with OutOfMemoryError: Java heap space in production. How do you investigate?
First capture evidence: enable -XX:+HeapDumpOnOutOfMemoryError and check GC logs and container memory limits. Open the heap dump in Eclipse MAT or VisualVM and look at the dominator tree for the largest retained objects. Common causes are unbounded caches, loading full tables into lists, static collections that keep growing and large file reads. Fix the leak, add pagination or streaming, set a sensible -Xmx below the container limit and add memory alerts.
13
A user's JWT is stolen and you need to invalidate it before expiry. How would you design for this?
Pure JWTs cannot be revoked, so keep access tokens short-lived, around 10 to 15 minutes, and use refresh tokens stored server-side and rotated on each use. On logout or theft, revoke the refresh token. For immediate blocking, keep a denylist of token IDs or a per-user token version in Redis and check it in the filter. Send refresh tokens in HttpOnly, Secure, SameSite cookies to reduce theft through XSS.
14
Where should a React app store the JWT, and what are the trade-offs?
localStorage is simple but any XSS script can read it. In-memory storage is safer but is lost on refresh. The commonly recommended pattern is a short-lived access token kept in memory and a refresh token in an HttpOnly, Secure, SameSite cookie that JavaScript cannot read, used to get new access tokens. Cookies need CSRF protection for state-changing calls. Whatever you choose, prevent XSS with proper escaping and a Content Security Policy.
15
Under load, requests fail with a connection timeout from HikariCP. What do you check?
This means all pool connections are busy. Check for long-running queries, transactions held open during remote calls, and connection leaks from code that never closes resources; set leakDetectionThreshold to find them. Compare maximumPoolSize with the database's max connections across all instances, since a bigger pool is not always better. Monitor Hikari metrics through Actuator, fix slow queries and keep @Transactional boundaries short.
16
Two admins edit the same product price at the same time and one change is silently lost. How do you prevent this?
This is a lost update. Add a @Version column for optimistic locking, send the version to the frontend with the entity, and include it in the update request. If the version no longer matches, Hibernate throws an optimistic lock exception, and the API returns HTTP 409 Conflict so the user can reload and retry. For short, high-contention operations like stock decrement, use a pessimistic lock or an atomic UPDATE with a condition.
17
Explain transaction isolation levels and the problems each one prevents.
Read Uncommitted allows dirty reads. Read Committed, the default in PostgreSQL, Oracle and SQL Server, prevents dirty reads but allows non-repeatable reads. Repeatable Read, the default in MySQL InnoDB, keeps rows read stable within a transaction, and InnoDB also blocks most phantoms with gap locks. Serializable prevents all anomalies but reduces concurrency. Higher isolation means more locking or retries, so choose per use case and set it with @Transactional(isolation = ...).
18
An object put into a HashMap cannot be found later even though it looks equal. What could be wrong?
Most likely a field used in hashCode was changed after insertion, so the object now hashes to a different bucket and get looks in the wrong place. It can also happen when equals is overridden without hashCode. Fix it by using immutable keys, such as records, Strings or IDs, and by basing equals and hashCode on fields that never change. Never mutate an object while it is a key in a hash-based collection.
19
How does Spring Boot auto-configuration work internally?
Spring Boot reads candidate configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports inside starter jars. Each class is guarded by conditions such as @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty, so beans are created only when the right library is present and you have not defined your own. You can inspect the decisions with the --debug flag or the Actuator conditions endpoint and exclude classes with exclude attributes.
20
Add the JWT to every API call and handle 401 responses using an Axios interceptor.
Parallel streams split work across the common ForkJoinPool. They help for CPU-heavy, stateless operations on large in-memory data with cheap splitting, such as ArrayList or arrays. Avoid them for small lists, I/O or database calls, operations with shared mutable state, or inside web servers where the common pool is shared by all requests. Always measure with JMH or real load before and after, because overhead often makes them slower.
22
Your React app's home page takes 6 seconds to load on mobile. How would you improve it?
Measure with Lighthouse and the browser Performance tab, and check Core Web Vitals such as LCP and INP. Then reduce JavaScript with route-based code splitting and removing heavy libraries, compress and lazy-load images using modern formats like WebP or AVIF with proper sizes, enable gzip or Brotli and long-term caching through a CDN, and avoid render-blocking resources. Server-side rendering or pre-rendering, for example with Next.js, can improve first paint further.
23
How does @Transactional work, and why does calling it from the same class not work?
Spring wraps the bean in a proxy. When an external caller invokes a @Transactional method, the proxy starts a transaction, calls the method and commits, or rolls back on a RuntimeException or Error. If a method in the same class calls another @Transactional method through this, the call skips the proxy, so the annotation is ignored. Fix it by moving the method to another bean or restructuring the boundary. The annotation also has no effect on private methods.
24
Find the top 3 highest-paid employees in each department.
SELECT department_id, name, salary
FROM (
SELECT department_id, name, salary,
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk <= 3
ORDER BY department_id, rnk;
-- DENSE_RANK keeps ties; use ROW_NUMBER for exactly 3 rows.
25
How does the Spring Security filter chain process a request?
Every request passes through a DelegatingFilterProxy into a FilterChainProxy, which picks the matching SecurityFilterChain. Filters run in order: CORS, CSRF, authentication filters such as BearerTokenAuthenticationFilter, exception translation and finally the authorization filter. Authentication filters build an Authentication object, validate it through the AuthenticationManager and store it in the SecurityContextHolder. The authorization filter then checks rules such as hasRole("ADMIN") before the controller runs.
26
An order service and a payment service have separate databases. How do you keep data consistent when placing an order?
Avoid distributed two-phase commit. Use the saga pattern: each service performs a local transaction and publishes an event, and failures trigger compensating actions, such as cancelling the order if payment fails. Use the transactional outbox pattern so the database write and the event are saved atomically, then a relay publishes to Kafka or RabbitMQ. Make consumers idempotent because events can be delivered more than once.
27
Build a dynamic search with optional filters using JPA Specifications.
The first-level cache is the persistence context itself. It is enabled by default and scoped to a session or transaction, so loading the same entity twice returns the same object without a second query. The second-level cache is optional and shared across sessions, configured with a provider like Ehcache or Infinispan through JCache. It suits read-mostly reference data. In clustered systems many teams prefer an explicit Redis cache at the service layer instead.
29
What is the difference between lazy and eager fetching?
Lazy fetching loads an association only when it is first accessed, using a proxy. Eager fetching loads it immediately with the parent. By default, @OneToMany and @ManyToMany are lazy, while @ManyToOne and @OneToOne are eager. Best practice is to make all associations lazy and fetch what each use case needs with JOIN FETCH or entity graphs, because eager loading often pulls large object graphs and causes extra queries.
30
Paging through a large table with OFFSET becomes very slow on later pages. What is a better approach?
With OFFSET 500000, the database still reads and discards half a million rows. Use keyset or seek pagination instead: remember the last seen sort key and query WHERE (created_at, id) < (:lastDate, :lastId) ORDER BY created_at DESC, id DESC LIMIT 20, backed by a matching index. This is fast at any depth and stable when new rows arrive. The trade-off is no direct jump to page N, which suits infinite scroll and APIs.
31
What are the correct and incorrect ways to use Optional?
Use Optional as a return type when a value may be absent, and consume it with map, filter, orElse, orElseGet or orElseThrow. Avoid calling get() without checking, avoid Optional fields in entities or DTOs, avoid Optional parameters and never return null from a method that returns Optional. Prefer orElseGet over orElse when the default is expensive, because orElse always evaluates its argument.
32
A table showing 10,000 rows makes the page very slow. How would you improve it?
Rendering thousands of DOM nodes is costly. Use server-side pagination or infinite scroll so the API returns only one page. If all rows must be scrollable, use list virtualization with a library like TanStack Virtual or react-window, which renders only visible rows. Memoize row components with React.memo, keep stable keys, avoid inline heavy calculations, and debounce filters. Profile with React DevTools Profiler to confirm which components are slow.
33
Your @Transactional method threw an exception but the data was still saved. Why?
By default Spring rolls back only on unchecked exceptions and Errors, so a checked exception such as IOException commits the transaction. Use @Transactional(rollbackFor = Exception.class) or wrap it in a runtime exception. Other causes are catching the exception inside the method, calling the method from the same class so the proxy is bypassed, a non-public method, or a table engine that does not support transactions such as MyISAM.
34
In a search box, older API responses sometimes overwrite newer results. How do you fix this race condition?
Each keystroke starts a request, and responses can arrive out of order. Debounce the input by about 300 milliseconds so fewer requests are sent. In the effect, cancel the previous request with AbortController in the cleanup function, or keep an ignore flag so stale responses are discarded. Libraries like TanStack Query handle this automatically by keying queries on the search term and ignoring outdated results.
35
Inserting one lakh rows with saveAll takes many minutes. How do you speed it up?
Enable JDBC batching with hibernate.jdbc.batch_size of 50 or so, plus order_inserts and order_updates. IDENTITY ID generation disables insert batching in Hibernate, so use a SEQUENCE generator with an allocation size on PostgreSQL or Oracle. Flush and clear the persistence context every batch to keep memory low. For very large loads, use JdbcTemplate batchUpdate or the database's bulk loader like COPY or LOAD DATA, which is much faster than ORM.
36
Memory usage of a single-page app keeps growing the longer it stays open. What could cause this?
Common causes are event listeners, intervals or WebSocket subscriptions that are never removed when a component unmounts, growing global caches or arrays, and detached DOM nodes still referenced by JavaScript. In React, return cleanup functions from useEffect to remove listeners and clear timers. Use the Chrome DevTools Memory tab with heap snapshots to compare before and after navigation and find retained objects.
37
Which features from Java 17 and Java 21 are useful for a full stack developer?
Java 17 brought records for immutable data carriers, sealed classes to restrict inheritance, text blocks for multi-line JSON or SQL, and pattern matching for instanceof. Java 21, the current widely used LTS alongside 17, added virtual threads for cheap blocking concurrency, pattern matching for switch, record patterns and sequenced collections. Spring Boot 3 needs Java 17 or later, and from Boot 3.2 virtual threads can be enabled with one property.
38
A teammate replaced a simple for loop in a performance-critical path with a long stream pipeline. Is this a concern?
Streams are usually fine and readable, and the JIT optimises them well, but in very hot loops they can add allocation, boxing and lambda overhead. Check for boxing with Stream<Integer> instead of IntStream, and for repeated sorting or collecting. Measure with a JMH benchmark or profiler rather than guessing. Keep streams where readability matters and use a plain loop only where profiling proves a real bottleneck.
39
What is the circuit breaker pattern and how is it implemented in Spring?
A circuit breaker stops calling a failing downstream service so failures do not cascade. It is closed during normal operation, opens when the failure rate crosses a threshold, returns a fallback immediately while open, and moves to half-open after a wait to test recovery. In Spring Boot it is implemented with Resilience4j using @CircuitBreaker(name = "payment", fallbackMethod = "fallback"), usually combined with timeouts, retries with backoff and bulkheads.
EXPLAIN ANALYZE
SELECT o.id, o.total
FROM orders o
WHERE o.customer_id = 42
AND o.status = 'PAID'
ORDER BY o.created_at DESC
LIMIT 20;
-- Look for: Seq Scan / type=ALL (full scan), large 'rows' estimates,
-- 'Using filesort' or a Sort node, and actual time per step.
-- Fix with: CREATE INDEX ix_orders_cust_status_date
-- ON orders (customer_id, status, created_at DESC);
Frequently asked questions
What is asked in Java Full Stack with React interviews for 10+ years of experience?
At ten years and above, candidates interview for architect, principal engineer or engineering manager roles. Conversations centre on business impact, platform strategy, modernising legacy Java systems, security and compliance, team structure and hiring. You may still face a design round, but leaders focus on judgement, communication with stakeholders and how you have grown engineers and delivered large programmes.
How many questions should I practise before a Java Full Stack with React interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for 10+ years of experience?
Focus first on Enterprise architecture, Legacy modernisation, Stakeholder management, Building and growing teams.