Skip to content

Medium Java Full Stack with React Interview Questions

95 medium questions with answers. Applied questions that check whether you can use the concepts on real work.

Topics in the medium set

Collections and Streams: 14 Spring Boot: 14 JPA and Hibernate: 13 REST APIs, Security and Microservices: 12 React Frontend: 12 SQL and Databases: 11 JavaScript, HTML and CSS: 10 Core Java: 9
Solved — mediumStart 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

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.
02

How does garbage collection work in modern Java?

Core JavaMedium
Save to ▾
Show answer
The GC frees objects that are no longer reachable from GC roots such as thread stacks and static fields. Most objects die young, so the heap is generational: minor collections clean the young generation often and survivors are promoted. G1 is the default collector since Java 9 and targets predictable pause times by collecting regions. ZGC and Shenandoah offer sub-millisecond pauses for large heaps. Tuning usually starts with -Xmx and choosing the collector, not dozens of flags.
03

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.
04

Write code that runs tasks in parallel using ExecutorService and collects results.

Core JavaMedium
Save to ▾
Show answer
ExecutorService pool = Executors.newFixedThreadPool(4); try { List<Callable<Integer>> tasks = List.of( () -> fetchCount("orders"), () -> fetchCount("users")); List<Future<Integer>> results = pool.invokeAll(tasks); for (Future<Integer> f : results) { System.out.println(f.get()); } } finally { pool.shutdown(); } // On Java 21 you can use Executors.newVirtualThreadPerTaskExecutor() // for I/O-bound tasks.
05

Write a record and use pattern matching in a switch expression.

Core JavaMedium
Save to ▾
Show answer
sealed interface Payment permits Card, Upi {} record Card(String number, double amount) implements Payment {} record Upi(String vpa, double amount) implements Payment {} static String describe(Payment p) { return switch (p) { case Card c when c.amount() > 50000 -> "High value card"; case Card c -> "Card ending " + c.number().substring(12); case Upi u -> "UPI to " + u.vpa(); }; } // Sealed types make the switch exhaustive without a default branch (Java 21).
06

Your code has frequent NullPointerExceptions from repository lookups. How would you redesign it?

Core JavaMedium
Save to ▾
Show answer
Return Optional from lookup methods so callers must handle the missing case, for example findById(id).orElseThrow(). Validate inputs at the API boundary with Bean Validation, initialise collections to empty lists instead of null and use Objects.requireNonNull in constructors. Java 17 helpful NPE messages show which variable was null, which speeds debugging. Do not use Optional for fields or method parameters; it is meant for return values.
07

You need a thread-safe singleton for a configuration loader. How do you implement it?

Core JavaMedium
Save to ▾
Show answer
The simplest safe options are an enum singleton or the holder idiom. With the holder idiom, a private static nested class holds the instance, and the JVM's class loading guarantees lazy, thread-safe initialisation without synchronization. Double-checked locking also works but needs a volatile field. In a Spring application you usually do not write singletons at all, because beans are singleton-scoped by default and the container manages them.
08

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.
09

Tell me about a difficult bug you fixed in a Java project.

Core JavaMedium
Save to ▾
Show answer
Situation: our order API sometimes returned another user's cart. Task: I had to find the root cause quickly. Action: I reproduced it with a load test, found a Spring singleton service storing the current user in an instance field, and moved that state into a method parameter. I added a concurrent test to prevent regressions. Result: the issue disappeared and I shared the learning about stateless beans with the team.
10

How does HashMap work internally?

Save to ▾
Show answer
HashMap stores entries in an array of buckets. The key's hashCode is spread and masked to find a bucket index. Collisions are kept in a linked list, and since Java 8 a bucket converts to a red-black tree after 8 entries when capacity is at least 64, giving O(log n) worst case. When size exceeds capacity times load factor 0.75, the table doubles and entries are redistributed. get uses hashCode to find the bucket and equals to find the key.
11

What is the contract between equals() and hashCode()?

Save to ▾
Show answer
If two objects are equal according to equals(), they must return the same hashCode. Unequal objects may share a hash code, but fewer collisions give better performance. If you override equals without hashCode, HashMap and HashSet will fail to find objects that are logically equal. Base both methods on the same immutable fields; records and IDE or Lombok generation create them correctly.
12

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.
13

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.
14

What are intermediate and terminal operations in Java Streams?

Save to ▾
Show answer
Intermediate operations such as filter, map, sorted and distinct return a new stream and are lazy; nothing runs until a terminal operation is called. Terminal operations such as collect, forEach, count, reduce and findFirst trigger processing and produce a result. Laziness allows short-circuiting: with findFirst, elements are processed one by one only until a match is found. A stream can be consumed only once.
15

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.
16

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.
17

Find the second highest salary from a list of employees using streams.

Save to ▾
Show answer
Optional<Double> second = employees.stream() .map(Employee::getSalary) .distinct() .sorted(Comparator.reverseOrder()) .skip(1) .findFirst(); second.ifPresentOrElse( s -> System.out.println("Second highest: " + s), () -> System.out.println("Not enough distinct salaries")); // distinct() handles ties at the top salary.
18

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()));
19

Count the frequency of each word in a sentence.

Save to ▾
Show answer
String text = "java is fun and java is fast"; Map<String, Long> freq = Arrays.stream(text.toLowerCase().split("\\s+")) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, Collectors.counting())); System.out.println(freq); // {java=2, is=2, fun=1, and=1, fast=1}
20

You get ConcurrentModificationException while removing items from a list inside a for-each loop. How do you fix it?

Save to ▾
Show answer
The for-each loop uses a fail-fast iterator, and calling list.remove changes the modification count. Use list.removeIf(item -> item.isExpired()), which is clean and efficient, or use an explicit Iterator and call iterator.remove(). Another option is to collect the items to keep into a new list with a stream filter. If several threads modify the list, use a concurrent collection instead.
21

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.
22

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.
23

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.
24

What bean scopes does Spring support?

Save to ▾
Show answer
singleton is the default: one instance per application context. prototype creates a new instance every time the bean is requested. Web applications also have request, session and application scopes, and websocket scope. Singleton beans must be stateless or thread-safe because many requests share them. If a singleton needs a prototype or request-scoped bean, inject an ObjectProvider or use a scoped proxy so each use gets the correct instance.
25

Why is constructor injection preferred over field injection?

Save to ▾
Show answer
Constructor injection makes dependencies explicit and lets fields be final, so the object is always fully initialised and immutable. It allows plain unit tests without Spring or reflection, because you can pass mocks to the constructor. A long constructor also signals that a class has too many responsibilities. Field injection with @Autowired hides dependencies and needs a container or reflection in tests. With a single constructor, @Autowired is not even needed.
26

How do profiles and application.yml work in Spring Boot?

Save to ▾
Show answer
Common settings go in application.yml, and environment-specific values go in files like application-dev.yml or application-prod.yml. You activate a profile with spring.profiles.active=prod, an environment variable SPRING_PROFILES_ACTIVE or a command-line argument. Profile files override the default values. Beans can also be limited with @Profile("dev"). Environment variables and command-line arguments have higher priority than files, which is useful in Docker and Kubernetes.
27

Mentoring: how would you help a junior developer who keeps pushing untested Spring code?

Save to ▾
Show answer
Situation: a junior on my team often broke the build with untested changes. Task: help him improve without demotivating him. Action: I paired with him for a few sessions to write JUnit and Mockito tests for his own features, shared a short checklist and set up a CI rule that blocks merges without passing tests. Result: within a month his pull requests passed review faster, and he later helped another new joiner.
28

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.
29

What changed when moving from Spring Boot 2 to Spring Boot 3?

Save to ▾
Show answer
Spring Boot 3 requires Java 17 or later and is built on Spring Framework 6. The biggest migration task is the switch from javax.* to jakarta.* packages for persistence, validation and servlet APIs. Spring Security 6 removed WebSecurityConfigurerAdapter in favour of SecurityFilterChain beans. Boot 3 also supports GraalVM native images, Micrometer observation and tracing, and from 3.2 the RestClient and virtual thread support.
30

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; } }
31

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.
32

Write a unit test for a service method using JUnit 5 and Mockito.

Save to ▾
Show answer
@ExtendWith(MockitoExtension.class) class ProductServiceTest { @Mock ProductRepository repo; @InjectMocks ProductService service; @Test void throwsWhenProductMissing() { when(repo.findById(1L)).thenReturn(Optional.empty()); assertThrows(ResourceNotFoundException.class, () -> service.getProduct(1L)); verify(repo).findById(1L); } }
33

Write a production-friendly Dockerfile for a Spring Boot application.

Save to ▾
Show answer
FROM eclipse-temurin:21-jdk AS build WORKDIR /app COPY . . RUN ./mvnw -q -DskipTests package FROM eclipse-temurin:21-jre WORKDIR /app RUN useradd -r appuser USER appuser COPY --from=build /app/target/*.jar app.jar EXPOSE 8080 ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"] # Multi-stage build keeps the image small; runs as non-root.
34

Your application fails at startup with a circular dependency error between two services. What do you do?

Save to ▾
Show answer
Spring Boot 2.6 and later forbid circular references by default. The real fix is design: two services depending on each other usually means a responsibility is in the wrong place. Extract the shared logic into a third bean, or use an application event so one service notifies the other without a direct reference. Using @Lazy or allowing circular references in properties hides the problem and should only be a temporary workaround.
35

Database passwords and API keys are committed in application.properties. How do you fix this?

Save to ▾
Show answer
Remove the secrets from the repository, rotate the exposed credentials immediately, and clean the history if needed. Replace values with placeholders such as ${DB_PASSWORD} and supply them through environment variables, Kubernetes Secrets or a vault like HashiCorp Vault or a cloud secrets manager. Add a pre-commit secret scanner, keep local values in an ignored file, and give each environment its own credentials with least privilege.
36

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.
37

Tell me about a time you delivered a feature under a tight deadline.

Save to ▾
Show answer
Situation: a client demo was moved forward by a week and the reporting module was not ready. Task: deliver the core report screens and APIs in five days. Action: I split the work into must-have and later items with my lead, reused existing query components, and wrote tests for the critical paths only. Result: the demo went well, and the remaining features shipped in the next sprint without bugs.
38

What are the entity lifecycle states in JPA?

Save to ▾
Show answer
A new or transient entity is just a Java object not known to the persistence context. A managed entity is attached to the context; changes are tracked and flushed automatically through dirty checking. A detached entity was managed but the context has closed, so changes are not tracked unless you merge it. A removed entity is scheduled for deletion on flush. Understanding these states explains why setters inside a transaction update the database without calling save.
39

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.
40

What is the N+1 select problem and how do you solve it?

Save to ▾
Show answer
It happens when one query loads N parent rows and then each lazy association fires a separate query, giving N+1 queries. For example, listing 100 orders and calling getCustomer on each. Solve it with JOIN FETCH in JPQL, @EntityGraph on the repository method, batch fetching with hibernate.default_batch_fetch_size, or DTO projections that select only the needed columns. Enable SQL logging or a statistics tool in development to catch it early.
41

What is the difference between persist and merge, and between save and saveAndFlush?

Save to ▾
Show answer
persist makes a new entity managed and assigns its ID; it fails for detached entities. merge copies the state of a detached entity onto a managed copy and returns that copy. Spring Data save calls persist for new entities and merge otherwise. saveAndFlush also calls flush, pushing pending SQL to the database immediately, which helps when you need a constraint error or trigger result now. The commit still happens at the end of the transaction.
42

In a bidirectional @OneToMany relationship, what does mappedBy mean?

Save to ▾
Show answer
mappedBy marks the inverse side and names the field on the other entity that owns the relationship. The owning side, usually the @ManyToOne with the foreign key column, is the one Hibernate uses to write the join column. For example, Order has @OneToMany(mappedBy = "order") and OrderItem has @ManyToOne @JoinColumn(name = "order_id"). Always update both sides in helper methods such as addItem to keep the object graph consistent.
43

What causes LazyInitializationException and how do you fix it properly?

Save to ▾
Show answer
It occurs when a lazy association is accessed after the persistence context has closed, for example in a controller or during JSON serialisation outside the transaction. The proper fix is to fetch the data inside the service transaction using JOIN FETCH or @EntityGraph and map it to a DTO. Avoid enabling spring.jpa.open-in-view as a crutch, and avoid switching associations to eager, because both hide performance problems.
44

Write a repository query that loads orders with their items in one query.

Save to ▾
Show answer
public interface OrderRepository extends JpaRepository<Order, Long> { @Query(""" select distinct o from Order o join fetch o.items i where o.customer.id = :customerId """) List<Order> findWithItems(@Param("customerId") Long customerId); @EntityGraph(attributePaths = {"items", "customer"}) Optional<Order> findWithGraphById(Long id); }
45

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);
46

Return only a few columns using an interface-based projection.

Save to ▾
Show answer
public interface ProductSummary { Long getId(); String getName(); BigDecimal getPrice(); } public interface ProductRepository extends JpaRepository<Product, Long> { List<ProductSummary> findByCategoryName(String category); @Query("select new com.shop.dto.PriceDto(p.name, p.price) from Product p where p.price < :max") List<PriceDto> cheaperThan(@Param("max") BigDecimal max); } // Projections select fewer columns and avoid loading full entities.
47

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.
48

Returning an entity from a REST API causes infinite recursion in JSON. Why, and how do you fix it?

Save to ▾
Show answer
Bidirectional relationships, such as Order having items and each item referencing its order, make Jackson serialise back and forth endlessly, leading to StackOverflowError. The cleanest fix is to return DTOs instead of entities, so you control exactly what is exposed. Quick fixes include @JsonManagedReference with @JsonBackReference or @JsonIgnore on one side. DTOs also stop lazy loading during serialisation and avoid leaking internal fields.
49

The business wants deleted customers to be recoverable. How would you implement soft delete with JPA?

Save to ▾
Show answer
Add a deleted flag or deleted_at timestamp column. With Hibernate 6.4 and later you can annotate the entity with @SoftDelete, or use @SQLDelete to turn delete into an UPDATE and @SQLRestriction to filter deleted rows from queries. Unique constraints must account for deleted rows, for example a partial index on email where deleted is false. Provide an admin restore endpoint and a scheduled job to purge old records for data retention.
50

What are cascade types and orphanRemoval in JPA?

Save to ▾
Show answer
Cascade propagates operations from a parent to its children: PERSIST, MERGE, REMOVE, REFRESH, DETACH or ALL. For example, saving an Order with CascadeType.ALL also saves its items. orphanRemoval = true deletes a child row when it is removed from the parent's collection. Use them for true parent-child aggregates like order and items, but never cascade REMOVE on @ManyToOne or shared references like Category, or deleting one product could delete the category.
51

How does JWT-based authentication work?

Save to ▾
Show answer
After a successful login, the server issues a JSON Web Token containing a header, a payload of claims such as user ID, roles and expiry, and a signature made with a secret or private key. The client sends it in the Authorization: Bearer header with each request. The server verifies the signature and expiry without a session lookup, which suits stateless APIs. Keep access tokens short-lived, do not store sensitive data in the payload because it is only encoded, and use refresh tokens for renewal.
52

What is CORS and how do you configure it for a React frontend?

Save to ▾
Show answer
CORS is a browser rule that blocks JavaScript from calling a different origin unless the server allows it with response headers like Access-Control-Allow-Origin. A React app on localhost:5173 calling an API on localhost:8080 is cross-origin. In Spring, define a CorsConfigurationSource bean with the allowed origins, methods and headers, and enable http.cors() in the security chain so preflight OPTIONS requests pass. Never use a wildcard origin together with credentials.
53

Compare monolithic and microservices architecture.

Save to ▾
Show answer
A monolith is one deployable application. It is simpler to build, test and debug, and suits small teams and early products. Microservices split the system into independently deployable services owned by separate teams, such as orders, payments and inventory, each with its own database. They allow independent scaling and releases but add network latency, distributed data, monitoring and deployment complexity. Many teams start with a modular monolith and split only when needed.
54

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.
55

Add request validation to a registration API.

Save to ▾
Show answer
public record RegisterRequest( @NotBlank @Size(max = 60) String name, @NotBlank @Email String email, @Pattern(regexp = "^[6-9]\\d{9}$", message = "Invalid mobile") String mobile, @Size(min = 8, max = 64) String password) {} @PostMapping("/api/auth/register") public ResponseEntity<Void> register(@Valid @RequestBody RegisterRequest req) { authService.register(req); return ResponseEntity.status(HttpStatus.CREATED).build(); } // Needs spring-boot-starter-validation. Errors raise // MethodArgumentNotValidException, mapped to 400 by the advice.
56

Call another microservice from Spring Boot using RestClient with a timeout.

Save to ▾
Show answer
@Bean RestClient inventoryClient(RestClient.Builder builder) { var factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(2000); factory.setReadTimeout(3000); return builder.baseUrl("http://inventory-service") .requestFactory(factory).build(); } public StockDto getStock(String sku) { return inventoryClient.get() .uri("/api/stock/{sku}", sku) .retrieve() .body(StockDto.class); } // RestClient (Boot 3.2+) replaces RestTemplate for new code; // use WebClient for reactive stacks.
57

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.
58

Your public API is being hit by too many requests from a few clients. How do you add rate limiting?

Save to ▾
Show answer
Apply rate limiting at the edge first, in the API gateway, Nginx or the cloud load balancer, keyed by API key, user ID or IP. In Spring Cloud Gateway use the Redis rate limiter, or inside a service use Bucket4j with a token bucket backed by Redis so limits work across instances. Return 429 Too Many Requests with a Retry-After header. Different plans or endpoints like login can have stricter limits.
59

Users must upload files up to 200 MB. How do you design the upload API?

Save to ▾
Show answer
Avoid streaming large files through the application server. Generate a pre-signed URL for object storage like S3 or Azure Blob so the browser uploads directly, then the client calls the API to confirm and save the metadata. If uploads must go through Spring, raise spring.servlet.multipart.max-file-size, stream the input to storage instead of loading it into memory, validate type and size, and scan files for malware before use.
60

How do you version a REST API?

Save to ▾
Show answer
The most common approach is URI versioning, like /api/v1/orders and /api/v2/orders, because it is visible and easy to route and cache. Other options are a custom header or the Accept media type. Spring Framework 7 adds first-class API versioning support. Version only for breaking changes; adding optional fields is backward compatible. Keep old versions running for a published deprecation period, and document every version with OpenAPI.
61

Tell me about a production incident you handled.

Save to ▾
Show answer
Situation: after a release, our login API started returning 500 errors at peak time. Task: as the on-call developer I had to restore service fast. Action: I checked logs and metrics, found the new connection pool settings were too small, rolled back the config and informed stakeholders. Then I led the root cause review and added a load test to the pipeline. Result: service recovered in 20 minutes and the issue never repeated.
62

How do you handle a requirement that is unclear or keeps changing?

Save to ▾
Show answer
Situation: a product manager asked for a discount feature with vague rules. Task: build it without wasting effort. Action: I wrote down my understanding with examples, asked specific questions about edge cases like stacking coupons, and built the rules as configurable data instead of hard-coded logic. I shared a small demo early for feedback. Result: two rule changes later in the sprint needed only configuration updates, not code changes.
63

What is normalization? Explain 1NF, 2NF and 3NF.

Save to ▾
Show answer
Normalization organises tables to reduce redundancy and update anomalies. 1NF requires atomic values with no repeating groups. 2NF requires 1NF and that every non-key column depends on the whole primary key, not part of a composite key. 3NF requires 2NF and no transitive dependency, so non-key columns depend only on the key. For example, store customer city in the customers table, not in every order row. Reporting systems sometimes denormalize for speed.
64

How do indexes improve performance, and when can they hurt?

Save to ▾
Show answer
An index, usually a B-tree, lets the database find rows without scanning the whole table, which speeds up WHERE, JOIN and ORDER BY on indexed columns. Indexes cost disk space and slow down INSERT, UPDATE and DELETE because each index must also be updated. They help little on low-selectivity columns like a boolean flag. Functions on the column, such as WHERE LOWER(email) = ?, or a leading wildcard in LIKE also prevent normal index use.
65

What are window functions and how are they different from GROUP BY?

Save to ▾
Show answer
Window functions compute a value over a set of related rows while keeping every row in the result, unlike GROUP BY which collapses rows into one per group. They use the OVER clause with optional PARTITION BY and ORDER BY. Examples are ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD and running SUM. For instance, you can show each employee with their department's average salary in the same row.
66

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.
67

Find employees who earn more than their managers.

Save to ▾
Show answer
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary FROM employees e JOIN employees m ON e.manager_id = m.id WHERE e.salary > m.salary; -- A self join treats the same table as two roles.
68

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;
69

A search query that used to take milliseconds now takes 10 seconds as data grew. How do you troubleshoot?

Save to ▾
Show answer
Get the exact SQL from logs or the slow query log and run EXPLAIN ANALYZE to see whether it does a full scan, a bad join order or a big sort. Check for missing or unused indexes, functions on indexed columns, implicit type conversions and outdated statistics. Add the right composite index, rewrite the query, select fewer columns and paginate. For text search, use a full-text index or a search engine instead of LIKE '%term%'.
70

You are designing a new feature. When would you choose a relational database and when a NoSQL database?

Save to ▾
Show answer
Choose a relational database like PostgreSQL or MySQL when data is structured, relationships matter and you need transactions and joins, such as orders, payments and inventory. Choose NoSQL when you need a flexible schema or huge horizontal scale for simple access patterns: MongoDB for documents, Redis for caching and sessions, Cassandra for high-write time series and Elasticsearch for search. Many systems use both, with SQL as the source of truth.
71

Tell me about a mistake you made with production data and how you handled it.

Save to ▾
Show answer
Situation: I ran an update script on production that missed a condition and changed status for more orders than intended. Task: correct it quickly and honestly. Action: I informed my lead immediately, stopped further jobs, used the audit table and a backup to restore the correct values and verified with the business team. Result: data was fixed within an hour. Since then, I always run scripts in a transaction with a row-count check first.
72

Explain the database design of a project you have worked on.

Save to ▾
Show answer
In my e-commerce project I designed tables for users, addresses, products, categories, orders, order_items and payments. Orders had a foreign key to users, and order_items linked orders and products with quantity and price at purchase time, so later price changes did not affect old orders. I added unique constraints on email and SKU, indexes on order status and date, and used Flyway for version-controlled changes.
73

What is the difference between a clustered and a non-clustered index?

Save to ▾
Show answer
A clustered index defines the physical order of rows, so the table data itself is stored in the index and there can be only one. In MySQL InnoDB the primary key is the clustered index. A non-clustered or secondary index is a separate structure holding the indexed columns and a pointer, or the primary key in InnoDB, to the row. That is why a short primary key keeps every secondary index smaller.
74

How does the useEffect dependency array work?

Save to ▾
Show answer
useEffect runs after the component renders. With no dependency array it runs after every render, with an empty array it runs once after mount, and with values like [userId] it runs again whenever those values change. Return a cleanup function to cancel subscriptions, timers or requests before the next run or on unmount. Missing dependencies cause stale data, so follow the exhaustive-deps lint rule. Effects are for syncing with external systems, not for computing derived values.
75

What is the difference between controlled and uncontrolled components?

Save to ▾
Show answer
In a controlled component, form input values live in React state and change through onChange, so React is the single source of truth, which makes validation and conditional UI easy. In an uncontrolled component, the DOM keeps the value and you read it through a ref when needed, which needs less code and suits simple forms or file inputs. Libraries like React Hook Form use uncontrolled inputs for better performance in large forms.
76

When should you use useMemo and useCallback?

Save to ▾
Show answer
useMemo caches the result of an expensive calculation until its dependencies change, such as filtering and sorting a big list. useCallback caches a function reference, which matters when passing callbacks to children wrapped in React.memo or used in effect dependencies. Do not wrap everything, because memoization itself has a cost. The React Compiler, released as stable in 2025, can add much of this memoization automatically in supported projects.
77

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.
78

What is a custom hook and why would you write one?

Save to ▾
Show answer
A custom hook is a function whose name starts with use and which calls other hooks, letting you reuse stateful logic across components. Examples are useFetch for loading data, useDebounce for search input and useAuth for the current user. Each component calling the hook gets its own independent state. Custom hooks keep components focused on rendering and make logic easier to test, much like extracting a service in backend code.
79

How do code splitting and lazy loading work in React?

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

Fetch a list of products from an API and show loading and error states.

Save to ▾
Show answer
function ProductList() { const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const controller = new AbortController(); fetch('/api/products', { signal: controller.signal }) .then(res => { if (!res.ok) throw new Error('HTTP ' + res.status); return res.json(); }) .then(data => setProducts(data.content)) .catch(err => { if (err.name !== 'AbortError') setError(err.message); }) .finally(() => setLoading(false)); return () => controller.abort(); }, []); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error}</p>; return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>; }
81

Write a reusable useFetch custom hook.

Save to ▾
Show answer
export function useFetch(url) { const [state, setState] = useState({ data: null, loading: true, error: null }); useEffect(() => { let ignore = false; setState(s => ({ ...s, loading: true })); fetch(url) .then(r => r.ok ? r.json() : Promise.reject(new Error(r.statusText))) .then(data => { if (!ignore) setState({ data, loading: false, error: null }); }) .catch(error => { if (!ignore) setState({ data: null, loading: false, error }); }); return () => { ignore = true; }; }, [url]); return state; } // Usage: const { data, loading, error } = useFetch(`/api/orders/${id}`);
82

Build a login form with basic validation in React.

Save to ▾
Show answer
function LoginForm({ onLogin }) { const [form, setForm] = useState({ email: '', password: '' }); const [errors, setErrors] = useState({}); const handleChange = e => setForm({ ...form, [e.target.name]: e.target.value }); const handleSubmit = e => { e.preventDefault(); const errs = {}; if (!/^\S+@\S+\.\S+$/.test(form.email)) errs.email = 'Enter a valid email'; if (form.password.length < 8) errs.password = 'Minimum 8 characters'; setErrors(errs); if (Object.keys(errs).length === 0) onLogin(form); }; return ( <form onSubmit={handleSubmit}> <input name="email" value={form.email} onChange={handleChange} /> {errors.email && <span>{errors.email}</span>} <input name="password" type="password" value={form.password} onChange={handleChange} /> {errors.password && <span>{errors.password}</span>} <button type="submit">Login</button> </form> ); }
83

Your component keeps re-rendering in an infinite loop after calling an API. What is wrong?

Save to ▾
Show answer
Usually useEffect sets state and has a dependency that changes on every render, or has no dependency array at all. A common case is an object or function created inside the component and listed as a dependency, so it is new each time. Fix it by using a correct dependency array, moving the object outside the component, or memoizing it with useMemo or useCallback. Also check that you are not calling setState directly during render.
84

After calling setCount(count + 1), console.log(count) still shows the old value. Why?

Save to ▾
Show answer
State updates are scheduled, not applied immediately. The count variable in the current render is a constant snapshot, so logging right after setState shows the old value; the new value appears in the next render. React also batches multiple updates. When the next state depends on the previous one, use the updater form setCount(c => c + 1), which works correctly even when called several times. Use useEffect to react to the updated value.
85

What is the biggest full stack project you have built?

Save to ▾
Show answer
I built a job portal using React with Vite, Spring Boot 3, Spring Security with JWT and MySQL. Recruiters could post jobs and candidates could apply and track status. I designed the REST APIs, implemented role-based access, added pagination and search, and used TanStack Query on the frontend. I deployed it with Docker and a CI pipeline. The hardest part was file upload for resumes, which I solved with pre-signed object storage URLs.
86

What is a closure in JavaScript? Give a practical use.

Save to ▾
Show answer
A closure is a function that remembers variables from the scope where it was created, even after that outer function has returned. For example, function counter() { let n = 0; return () => ++n; } returns a function that keeps its own private n. Closures are used for data privacy, function factories, event handlers, debounce and memoization, and React hooks rely on them. Stale closures in effects are a common bug when dependencies are missing.
87

Compare promises and async/await.

Save to ▾
Show answer
A promise represents a value that will be available later, handled with then, catch and finally. async/await is syntax built on promises: an async function always returns a promise, and await pauses that function until the promise settles, so asynchronous code reads like synchronous code. Errors are handled with try/catch. Awaiting calls one by one is sequential, so use Promise.all for independent calls to run them in parallel.
88

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.
89

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.
90

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.
91

How do you deep clone an object in JavaScript?

Save to ▾
Show answer
const original = { user: { name: 'Asha' }, tags: ['a'], joined: new Date() }; // Modern built-in (handles Date, Map, Set, cycles): const copy = structuredClone(original); // Spread is only a shallow copy: const shallow = { ...original }; shallow.user.name = 'Ravi'; // also changes original.user.name // JSON.parse(JSON.stringify(obj)) loses Dates, functions, // undefined and fails on circular references.
92

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.
93

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.
94

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.
95

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.

Frequently asked questions

Who should practise medium Java Full Stack with React questions?

Anyone with some hands-on practice: most real interview time is spent on medium questions like these.

How should I practise these?

Answer each question aloud before opening the answer, mark it as solved only when your answer matches the key idea, and save misses to Last-Minute Revision.

Other difficulty levels