Skip to content

Java Full Stack with React Interview Questions for 2 Years Experience

40 questions with answers for candidates with 2 years of experience — 9 easy, 30 medium, 1 hard.

What interviewers expect: 2 years experience

At two years, you are expected to deliver features independently. Interviews cover transactions, lazy loading and N+1, Spring Security with JWT, validation, pagination and API error handling. On the frontend, expect routing, forms, state management and performance basics. Scenario questions about debugging slow APIs or production errors become common, along with questions on code reviews and working with QA.

This set is weighted towards JavaScript, HTML and CSS (10), Collections and Streams (9), JPA and Hibernate (4), Spring Boot (4).

Transactions and JPA performance JWT security React state management Debugging scenarios
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

What are the options for spring.jpa.hibernate.ddl-auto and which should be used in production?

Save to ▾
Show answer
none does nothing, validate checks that the schema matches entities, update alters tables to add missing columns, create drops and recreates the schema at startup and create-drop also drops it at shutdown. update and create are fine for learning but risky in production because they cannot handle renames or data migrations safely. In production use validate or none, and manage schema changes with Flyway or Liquibase scripts.
02

What is Spring Boot Actuator used for?

Save to ▾
Show answer
Actuator adds production-ready endpoints for monitoring and management, such as /actuator/health, /actuator/info, /actuator/metrics and /actuator/prometheus. Kubernetes uses health liveness and readiness groups for probes. Metrics are collected through Micrometer and can be exported to Prometheus, Datadog or other systems. Only expose the endpoints you need with management.endpoints.web.exposure.include and secure them, because endpoints like env or heapdump can leak sensitive data.
03

The layout looks fine on desktop but breaks on mobile with horizontal scrolling. How do you debug it?

Save to ▾
Show answer
Check that the page has the viewport meta tag. Use browser device mode to find the element wider than the screen, often fixed widths in pixels, large images, long words or tables. Replace fixed widths with max-width: 100 percent, flexible units and flex-wrap, add overflow-wrap for long text and wrap wide tables in a scrollable container. Build mobile-first with media queries that add complexity for larger screens.
04

Explain the CSS box model.

Save to ▾
Show answer
Every element is a box made of content, padding, border and margin, from inside to outside. By default, width applies only to the content, so padding and border add to the final size. Setting box-sizing: border-box makes width include padding and border, which makes layouts predictable, and most projects apply it to all elements. Vertical margins between block elements can collapse into one margin.
05

When would you use the Context API and when a state library like Redux Toolkit or Zustand?

Save to ▾
Show answer
Context is good for passing low-frequency global values such as theme, language or the logged-in user without prop drilling. Every consumer re-renders when the context value changes, so it is not ideal for fast-changing data. Redux Toolkit or Zustand suit larger shared client state with many updates, selectors and dev tools. Server data like API responses is often best handled by TanStack Query, which adds caching and refetching.
06

Why does React need a key prop when rendering lists?

Save to ▾
Show answer
Keys help React match list items between renders, so it knows which items were added, removed or moved. Use a stable unique ID from the data, such as product.id. Using the array index as key causes bugs when items are reordered or deleted, because state and input values can attach to the wrong row. Keys only need to be unique among siblings, and they are not passed to the component as a prop.
07

Write global exception handling for a REST API in Spring Boot.

Save to ▾
Show answer
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ProblemDetail handleNotFound(ResourceNotFoundException ex) { return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) public ProblemDetail handleValidation(MethodArgumentNotValidException ex) { ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST); pd.setProperty("errors", ex.getBindingResult().getFieldErrors() .stream().map(e -> e.getField() + ": " + e.getDefaultMessage()).toList()); return pd; } }
08

Call three APIs in parallel and handle failure of any one gracefully.

Save to ▾
Show answer
async function loadDashboard() { const results = await Promise.allSettled([ fetch('/api/orders').then(r => r.json()), fetch('/api/stats').then(r => r.json()), fetch('/api/alerts').then(r => r.json()), ]); const [orders, stats, alerts] = results.map(r => r.status === 'fulfilled' ? r.value : null); return { orders, stats, alerts }; } // Promise.all rejects on the first failure; // allSettled lets the page show partial data.
09

Your React app gets 403 Forbidden on POST requests to Spring Boot, but GET works. What is the likely cause?

Save to ▾
Show answer
With Spring Security enabled, CSRF protection is on by default and blocks POST, PUT and DELETE that lack a CSRF token, while GET is allowed. For a stateless JWT API, disable CSRF in the SecurityFilterChain. If you use session cookies, keep CSRF and send the token with CookieCsrfTokenRepository. Also check CORS, because a rejected preflight OPTIONS request or a missing role in authorization rules can produce the same symptom.
10

Write a Flyway migration to add a column and index to an existing table.

Save to ▾
Show answer
-- 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.
11

When would you use ArrayList over LinkedList?

Save to ▾
Show answer
ArrayList is backed by a resizable array, giving O(1) random access and good cache locality, and appending is amortised O(1). LinkedList is a doubly linked list with O(1) insertion at known nodes but O(n) access by index and more memory per element. In practice ArrayList is faster for almost all workloads. For queue or stack behaviour, ArrayDeque is usually better than LinkedList.
12

Users in different countries see wrong order times. How do you handle dates and time zones in Java?

Core JavaMedium
Save to ▾
Show answer
Store timestamps in UTC using Instant or OffsetDateTime, and map them to TIMESTAMP WITH TIME ZONE or a UTC timestamp column. Convert to the user's zone only when displaying, using ZonedDateTime with ZoneId such as Asia/Kolkata. Avoid java.util.Date and SimpleDateFormat, which are mutable and not thread-safe. Use DateTimeFormatter, send ISO-8601 strings in JSON and set hibernate.jdbc.time_zone to UTC.
13

What are the correct and incorrect ways to use Optional?

Save to ▾
Show answer
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.
14

Which features from Java 17 and Java 21 are useful for a full stack developer?

Core JavaMedium
Save to ▾
Show answer
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.
15

What is React and what is the virtual DOM?

Save to ▾
Show answer
React is a JavaScript library for building user interfaces from reusable components. Components describe what the UI should look like for a given state, and React updates the browser DOM when the state changes. The virtual DOM is a lightweight in-memory tree of the UI. On each update, React compares the new tree with the previous one and applies only the minimum real DOM changes, which keeps updates efficient and the code declarative.
16

What are ACID properties?

Save to ▾
Show answer
Atomicity means a transaction fully succeeds or fully rolls back. Consistency means it moves the database from one valid state to another, respecting constraints. Isolation means concurrent transactions do not see each other's partial work. Durability means committed data survives crashes, thanks to write-ahead logs. A bank transfer that debits one account and credits another is the classic example where all four properties matter.
17

Write a query that shows daily sales with a running total for the month.

Save to ▾
Show answer
SELECT order_date, SUM(amount) AS daily_sales, SUM(SUM(amount)) OVER ( ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_total FROM orders WHERE order_date >= DATE '2026-10-01' AND order_date < DATE '2026-11-01' GROUP BY order_date ORDER BY order_date;
18

Explain the difference between map and flatMap in streams.

Save to ▾
Show answer
map transforms each element into exactly one new element, so a Stream of orders mapped to customer names gives a Stream of String. flatMap transforms each element into a stream and flattens all of them into one stream. For example, orders.stream().flatMap(o -> o.getItems().stream()) gives every item from every order. Optional also has map and flatMap with the same idea.
19

Implement pagination and sorting for a product list API.

Save to ▾
Show answer
@GetMapping("/api/products") public Page<ProductDto> list( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size, @RequestParam(defaultValue = "price") String sort) { Pageable pageable = PageRequest.of(page, Math.min(size, 100), Sort.by(sort).ascending()); return repository.findByActiveTrue(pageable).map(ProductDto::from); } // Repository: Page<Product> findByActiveTrue(Pageable pageable);
20

What roles do an API gateway and service discovery play in microservices?

Save to ▾
Show answer
An API gateway, such as Spring Cloud Gateway, is the single entry point for clients. It handles routing, authentication, rate limiting, CORS and request logging. Service discovery lets services find each other without hard-coded addresses: with Eureka or Consul, services register themselves, and clients look them up. On Kubernetes, built-in Services and DNS usually replace a separate discovery server, and an ingress or gateway handles external traffic.
21

Find the top 3 highest-paid employees in each department.

Save to ▾
Show answer
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.
22

Why should we hire you as a Java full stack developer?

Save to ▾
Show answer
I can contribute on both sides of a feature: I have built REST APIs with Spring Boot, JPA and MySQL, and responsive React screens that consume them. I write tests, use Git properly and have deployed my projects with Docker. I also learn quickly; I picked up Spring Security and JWT for my capstone in two weeks. I am looking for a team where I can grow into an engineer who owns features from design to production.
23

Explain final, finally and finalize.

Save to ▾
Show answer
final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden and a final class cannot be extended. finally is a block after try or catch that always runs, used for cleanup, although try-with-resources is now preferred. finalize() was an Object method called before garbage collection; it is deprecated for removal because its timing is unpredictable. Use Cleaner or try-with-resources instead.
24

Using streams, group employees by department and count them.

Save to ▾
Show answer
Map<String, Long> countByDept = employees.stream() .collect(Collectors.groupingBy( Employee::getDepartment, Collectors.counting())); // Average salary per department: Map<String, Double> avgSalary = employees.stream() .collect(Collectors.groupingBy( Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary))); // Use TreeMap::new as the second argument to get sorted keys.
25

How do you handle a Git merge conflict when working in a team?

Save to ▾
Show answer
Situation: two of us edited the same service class in parallel branches. Task: merge without losing either change. Action: I pulled the latest main, rebased my branch, opened the conflicted files and resolved them together with my teammate on a quick call, then ran all tests before pushing. Result: the merge was clean. To reduce conflicts, we now keep branches short-lived and pull from main daily.
26

Your team is starting a new React project. Would you use Create React App or something else?

Save to ▾
Show answer
Create React App is deprecated and no longer recommended. For a single-page app backed by a Spring Boot API, Vite is the usual choice because of its fast dev server and optimised builds. If you need server-side rendering, SEO or file-based routing, a framework like Next.js or React Router in framework mode is recommended by the React team. Choose based on SEO needs, hosting and the team's experience.
27

Bind custom properties from application.yml into a type-safe class.

Save to ▾
Show answer
# application.yml app: payment: timeout-ms: 3000 retry-count: 2 @ConfigurationProperties(prefix = "app.payment") @Validated public record PaymentProperties( @Min(500) int timeoutMs, @Max(5) int retryCount) {} @SpringBootApplication @EnableConfigurationProperties(PaymentProperties.class) public class App { } // Relaxed binding maps timeout-ms to timeoutMs automatically.
28

Sort a list of products by category, then by price descending, then by name.

Save to ▾
Show answer
products.sort( Comparator.comparing(Product::getCategory) .thenComparing(Product::getPrice, Comparator.reverseOrder()) .thenComparing(Product::getName)); // Null-safe variant for an optional field: Comparator<Product> byBrand = Comparator.comparing( Product::getBrand, Comparator.nullsLast(Comparator.naturalOrder()));
29

Write a debounce function in JavaScript.

Save to ▾
Show answer
function debounce(fn, delay = 300) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const search = debounce(term => { fetch(`/api/products?q=${encodeURIComponent(term)}`); }, 400); input.addEventListener('input', e => search(e.target.value)); // Only the last call within 400 ms actually runs.
30

Describe a time you disagreed with a teammate during a code review.

Save to ▾
Show answer
Situation: a teammate used nested loops over two large lists to match records. Task: I felt it would be slow at production volume. Action: instead of just rejecting it, I wrote a quick benchmark showing the HashMap-based approach was much faster, and explained it calmly in a call. Result: he agreed, we merged the faster version, and we added a team guideline to back performance comments with data.
31

What is the difference between lazy and eager fetching?

Save to ▾
Show answer
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.
32

Describe the main JVM memory areas.

Core JavaMedium
Save to ▾
Show answer
The heap stores objects and is shared by all threads; it is managed by the garbage collector and split into young and old generations. Each thread has its own stack holding method frames, local variables and references. Metaspace, in native memory since Java 8, stores class metadata. There is also the program counter per thread and the code cache for JIT-compiled code. Stack overflow comes from deep recursion, while OutOfMemoryError usually means heap or metaspace is full.
33

What is the difference between localStorage, sessionStorage and cookies?

Save to ▾
Show answer
localStorage keeps data with no expiry for the origin, around 5 to 10 MB, and is shared across tabs. sessionStorage is similar but cleared when the tab closes and is per tab. Cookies are small, around 4 KB, are sent automatically with every request to the server and can be marked HttpOnly, Secure and SameSite. Use cookies for auth sessions, and storage for non-sensitive UI preferences only, since scripts can read storage.
34

Compare HashMap, Hashtable and ConcurrentHashMap.

Save to ▾
Show answer
HashMap is not synchronized and allows one null key and null values. Hashtable is a legacy class where every method is synchronized, so it is slow and allows no nulls. ConcurrentHashMap is the modern thread-safe choice: reads are mostly lock-free, writes lock only a single bucket using CAS and synchronized blocks, and it offers atomic methods such as computeIfAbsent and merge. It also does not allow null keys or values.
35

You are loading about five lakh records into an ArrayList and a HashMap and memory spikes during loading. What can you do?

Save to ▾
Show answer
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.
36

What is event delegation and why is it useful?

Save to ▾
Show answer
Events bubble up from the target element to its ancestors. With event delegation you attach one listener to a parent, such as a ul, and use event.target.closest('li') to find which child was clicked. This saves memory compared with a listener on every item and automatically works for items added later. It is commonly used for dynamic tables and lists. React uses a similar idea by attaching listeners at the root.
37

In a search box, older API responses sometimes overwrite newer results. How do you fix this race condition?

Save to ▾
Show answer
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.
38

Explain the architecture of your last full stack project end to end.

Save to ▾
Show answer
In my last project, a React single-page app called a Spring Boot REST API secured with JWT. The API followed controller, service and repository layers, used Spring Data JPA with MySQL and Flyway for migrations, and exposed Swagger documentation. I deployed it with Docker on a cloud VM behind Nginx. My contribution was the order module and payment status flow, and I also wrote the unit tests and CI pipeline.
39

What are fail-fast and fail-safe iterators?

Save to ▾
Show answer
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.
40

How does the this keyword work, and how do arrow functions change it?

Save to ▾
Show answer
In a regular function, this depends on how the function is called: the object before the dot in a method call, undefined in strict mode for a plain call, the new object with new, or a value set by call, apply or bind. Arrow functions do not have their own this; they use this from the surrounding scope. That makes arrows ideal for callbacks inside methods, but unsuitable as object methods that need their own this.

Frequently asked questions

What is asked in Java Full Stack with React interviews for 2 years of experience?

At two years, you are expected to deliver features independently. Interviews cover transactions, lazy loading and N+1, Spring Security with JWT, validation, pagination and API error handling. On the frontend, expect routing, forms, state management and performance basics. Scenario questions about debugging slow APIs or production errors become common, along with questions on code reviews and working with QA.

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 2 years of experience?

Focus first on Transactions and JPA performance, JWT security, React state management, Debugging scenarios.