Skip to content

Java Full Stack with React Interview Questions & Answers

All 200 unique questions in one place — 63 easy, 95 medium, 42 hard — grouped by topic.

Practise by topic

Solved overallStart 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 is the difference between JDK, JRE and JVM?

Save to ▾
Show answer
The JVM runs Java bytecode and handles memory, garbage collection and JIT compilation. The JRE is the JVM plus core class libraries needed to run programs. The JDK is the JRE plus development tools such as javac, jar, jshell and jdb. Since Java 11 a separate JRE is no longer shipped by Oracle, so developers install a JDK such as Temurin or Oracle JDK 17 or 21 and build smaller runtimes with jlink if needed.
02

Why is String immutable in Java?

Save to ▾
Show answer
Once created, a String object cannot change. This allows the String pool to safely share literals, makes strings thread-safe without locking, lets hashCode be cached for fast HashMap keys, and protects security-sensitive values like file paths, class names and URLs from being changed after validation. Any operation such as concat or replace returns a new String, which is why heavy modification should use StringBuilder.
03

What is the difference between == and equals() in Java?

Save to ▾
Show answer
The == operator compares references for objects, meaning it checks whether two variables point to the same object in memory. equals() compares logical content when a class overrides it, as String, Integer and most collections do. For example, new String("a") == new String("a") is false but equals() returns true. For primitives, == compares values. Always use equals() for objects and Objects.equals(a, b) to stay null-safe.
04

Compare String, StringBuilder and StringBuffer.

Save to ▾
Show answer
String is immutable, so every change creates a new object. StringBuilder is mutable and fast but not thread-safe, which makes it the default choice for building strings inside a method or loop. StringBuffer is mutable and synchronized, so it is thread-safe but slower, and it is rarely needed today because strings are seldom shared across threads while being built. The compiler already uses optimized concatenation for simple + expressions outside loops.
05

What is the difference between checked and unchecked exceptions?

Save to ▾
Show answer
Checked exceptions extend Exception (but not RuntimeException) and must be caught or declared with throws, for example IOException or SQLException. Unchecked exceptions extend RuntimeException, such as NullPointerException or IllegalArgumentException, and the compiler does not force handling. Use checked exceptions for recoverable conditions the caller should handle, and unchecked ones for programming errors. Spring prefers unchecked exceptions, for example DataAccessException, to keep service code clean.
06

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

What does the static keyword mean in Java?

Save to ▾
Show answer
static members belong to the class, not to an instance. A static variable has one copy shared by all objects, a static method can be called without creating an object and cannot use this, and a static block runs once when the class loads. Static nested classes do not hold a reference to the outer object. Common examples are utility methods like Math.max and constants declared as public static final.
08

Show how to read a file safely using try-with-resources.

Save to ▾
Show answer
Path path = Path.of("data.txt"); try (BufferedReader reader = Files.newBufferedReader(path)) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { log.error("Could not read file", e); } // The reader is closed automatically, even if an exception occurs, // because BufferedReader implements AutoCloseable.
09

Create a custom unchecked exception and throw it from a service method.

Save to ▾
Show answer
public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } public Product getProduct(Long id) { return repository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Product not found: " + id)); } // A @RestControllerAdvice can map this exception to HTTP 404.
10

Write a Java method to check whether a string is a palindrome, ignoring case and spaces.

Save to ▾
Show answer
static boolean isPalindrome(String s) { String clean = s.replaceAll("\\s+", "").toLowerCase(); int i = 0, j = clean.length() - 1; while (i < j) { if (clean.charAt(i++) != clean.charAt(j--)) { return false; } } return true; } // Two pointers give O(n) time and O(n) space for the cleaned copy. // isPalindrome("Nurses Run") returns true.
11

A report job builds a large string with + inside a loop and is very slow. What do you change?

Save to ▾
Show answer
Each + inside a loop creates a new String and copies the old content, giving roughly O(n squared) work. Replace it with one StringBuilder created before the loop, optionally with an initial capacity, and call append inside the loop. For joining collections, use String.join or Collectors.joining. For very large output, write directly to a BufferedWriter or stream instead of holding everything in memory.
12

Why do you want to become a Java full stack developer?

Save to ▾
Show answer
I enjoy building a feature end to end, from the database table to the screen the user clicks. Java and Spring Boot are used widely in Indian banking, product and services companies, so the skills stay in demand, and React lets me build modern interfaces. In my capstone project I built an inventory app with Spring Boot, MySQL and React, and owning the full flow taught me how each layer affects the user experience.
13

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

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

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

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

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).
18

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

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

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

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

What is the difference between volatile and synchronized?

Save to ▾
Show answer
volatile guarantees visibility: a write by one thread is immediately visible to others and reordering around it is restricted, but it does not make compound operations like count++ atomic. synchronized gives both mutual exclusion and visibility by acquiring a monitor lock, so only one thread runs the block at a time. Use volatile for simple flags such as a shutdown signal, synchronized or locks for check-then-act logic, and AtomicInteger or LongAdder for counters.
23

Use CompletableFuture to call two services in parallel and combine the results.

Save to ▾
Show answer
CompletableFuture<User> userF = CompletableFuture.supplyAsync(() -> userClient.get(id), executor); CompletableFuture<List<Order>> ordersF = CompletableFuture.supplyAsync(() -> orderClient.byUser(id), executor); Profile profile = userF .thenCombine(ordersF, Profile::new) .orTimeout(2, TimeUnit.SECONDS) .exceptionally(ex -> Profile.empty()) .join(); // Pass a dedicated executor instead of the common pool for blocking I/O.
24

Your Spring Boot service crashes with OutOfMemoryError: Java heap space in production. How do you investigate?

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

CPU is at 100 percent and requests are hanging. How would you find the cause in a Java application?

Save to ▾
Show answer
Take several thread dumps a few seconds apart using jstack, jcmd Thread.print or the Actuator threaddump endpoint. Threads stuck in the same RUNNABLE frame point to a hot loop or heavy regex, while threads BLOCKED on each other's locks show a deadlock, which jstack reports directly. Match native thread IDs from top -H to the dump. Profilers such as async-profiler or Java Flight Recorder confirm hot methods before you fix the code.
26

What is the difference between List, Set and Map?

Save to ▾
Show answer
A List is an ordered collection that allows duplicates and index access, such as ArrayList. A Set holds unique elements; HashSet has no order, LinkedHashSet keeps insertion order and TreeSet keeps elements sorted. A Map stores key-value pairs with unique keys, such as HashMap or TreeMap, and is not part of the Collection interface. Choose based on whether you need duplicates, ordering or lookup by key.
27

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

What is the difference between Comparable and Comparator?

Save to ▾
Show answer
Comparable defines a class's natural ordering through compareTo, implemented inside the class itself, such as String or Integer. Comparator is a separate object with compare, so you can define many orderings without changing the class. Since Java 8, Comparator.comparing, thenComparing and reversed make multi-field sorting concise. Use Comparable for one obvious order and Comparator for business-specific sorting like price then rating.
29

What is a functional interface and how do lambdas relate to it?

Save to ▾
Show answer
A functional interface has exactly one abstract method, such as Runnable, Comparator, Function, Predicate, Supplier or Consumer, and can be marked with @FunctionalInterface. A lambda expression is a short implementation of that single method, for example Predicate<String> empty = s -> s.isBlank(). Method references like String::toUpperCase are an even shorter form. Lambdas power the Streams API and callback-style code.
30

Find duplicate elements in a list of integers.

Save to ▾
Show answer
List<Integer> nums = List.of(4, 2, 7, 2, 4, 9); Set<Integer> seen = new HashSet<>(); Set<Integer> duplicates = nums.stream() .filter(n -> !seen.add(n)) .collect(Collectors.toSet()); System.out.println(duplicates); // [2, 4] // Stateless alternative using counts: // nums.stream().collect(groupingBy(identity(), counting())) // .entrySet().stream().filter(e -> e.getValue() > 1)
31

You need to store unique usernames and always display them in alphabetical order. Which collection do you pick?

Save to ▾
Show answer
A TreeSet fits because it rejects duplicates and keeps elements sorted using natural order or a Comparator, with O(log n) add and lookup. Use String.CASE_INSENSITIVE_ORDER as the comparator if Rahul and rahul should be treated as the same. If you only need sorting once at display time, a HashSet followed by sorting may be faster. For concurrent access, ConcurrentSkipListSet is the thread-safe sorted alternative.
32

How do you keep yourself updated with new Java versions and features?

Save to ▾
Show answer
I follow the six-monthly Java release notes and JEP summaries, and I try new features in small jshell experiments or side projects. For example, when Java 21 became LTS I rewrote a small file-processing tool using virtual threads and pattern matching to understand the benefits. I also read Spring release blogs and watch conference talks, and I share short notes with my team so we upgrade with confidence.
33

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

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

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

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

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

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

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

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

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

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}
43

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

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

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

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

When should you use parallel streams and when should you avoid them?

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

Implement a simple LRU cache in Java.

Save to ▾
Show answer
class LruCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; LruCache(int capacity) { super(16, 0.75f, true); // true = access order this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } } // Not thread-safe: wrap with Collections.synchronizedMap // or use Caffeine in production.
49

An object put into a HashMap cannot be found later even though it looks equal. What could be wrong?

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

A teammate replaced a simple for loop in a performance-critical path with a long stream pipeline. Is this a concern?

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

What is Spring Boot and how is it different from the Spring Framework?

Save to ▾
Show answer
Spring Framework provides dependency injection, MVC, data access and transactions, but traditionally needed a lot of manual configuration and an external server. Spring Boot sits on top of Spring and adds auto-configuration, starter dependencies, an embedded Tomcat, Jetty or Undertow server, externalised configuration and production features like Actuator. You can run an application as a single executable jar with java -jar, which makes it ideal for microservices and containers.
52

Explain Inversion of Control and Dependency Injection.

Save to ▾
Show answer
Inversion of Control means the framework, not your code, creates and wires objects. Dependency Injection is how Spring does it: a class declares what it needs, usually through its constructor, and the container supplies the beans. For example, OrderService receives an OrderRepository instead of creating one with new. This reduces coupling, makes it easy to swap implementations and lets you pass mocks in unit tests.
53

What does @SpringBootApplication do?

Save to ▾
Show answer
It is a convenience annotation combining three annotations. @SpringBootConfiguration marks the class as a configuration source. @EnableAutoConfiguration tells Boot to configure beans based on the classpath and properties, for example a DataSource when a JDBC driver is present. @ComponentScan scans the package of the main class and its sub-packages for components. That is why the main class should sit in the root package of your project.
54

Create a scheduled job that runs every night at 2 AM in Spring Boot.

Save to ▾
Show answer
@SpringBootApplication @EnableScheduling public class App { } @Component public class CleanupJob { private final SessionRepository repo; public CleanupJob(SessionRepository repo) { this.repo = repo; } @Scheduled(cron = "0 0 2 * * *", zone = "Asia/Kolkata") public void removeExpiredSessions() { repo.deleteByExpiresAtBefore(Instant.now()); } } // With several instances, use ShedLock so only one runs the job.
55

You need H2 for local development, MySQL for testing and PostgreSQL in production. How do you configure this?

Save to ▾
Show answer
Create application-dev.yml, application-test.yml and application-prod.yml, each with its own spring.datasource URL, username and driver. Keep shared settings in application.yml. Activate the right one with SPRING_PROFILES_ACTIVE in each environment. Read production credentials from environment variables, for example url: ${DB_URL}, instead of hard-coding them. For realistic integration tests, Testcontainers can start the same database engine used in production.
56

The application fails with NoSuchBeanDefinitionException for a service. How do you debug it?

Save to ▾
Show answer
Check that the class has @Service or @Component, or is created by a @Bean method. Make sure it is inside the package of the main @SpringBootApplication class or a scanned sub-package. If there are several implementations, use @Qualifier or @Primary. Also check @Profile or @Conditional annotations that may disable it in the current environment. Running with --debug prints the condition report that shows why a bean was not created.
57

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

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

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

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

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

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

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

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

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); } }
66

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

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

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

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

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

How does Spring Boot auto-configuration work internally?

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

How does @Transactional work, and why does calling it from the same class not work?

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

Write a controller slice test with @WebMvcTest and MockMvc.

Save to ▾
Show answer
@WebMvcTest(ProductController.class) class ProductControllerTest { @Autowired MockMvc mvc; @MockitoBean ProductService service; // @MockBean before Boot 3.4 @Test void returnsProduct() throws Exception { when(service.getProduct(1L)).thenReturn(new ProductDto(1L, "Pen", 20.0)); mvc.perform(get("/api/products/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("Pen")); } }
74

A Spring Boot service takes nearly a minute to start. How would you speed it up?

Save to ▾
Show answer
Measure first with the startup Actuator endpoint or ApplicationStartup to see which beans are slow. Common causes are heavy component scanning, eager database or remote calls in @PostConstruct, Hibernate validating a large schema and unneeded auto-configurations. Narrow scan packages, defer work with lazy initialisation or ApplicationReadyEvent, exclude unused starters and use Class Data Sharing. For serverless workloads, consider GraalVM native images or CRaC.
75

Your @Transactional method threw an exception but the data was still saved. Why?

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

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

Save to ▾
Show answer
JPA, now Jakarta Persistence, is a specification that defines annotations and the EntityManager API for object-relational mapping. Hibernate is the most widely used implementation of that specification and adds extra features. Spring Data JPA is a layer above JPA that generates repository implementations from interfaces, so methods like findByEmail are created automatically. In a Spring Boot app you write against Spring Data, which uses JPA, which is implemented by Hibernate.
77

How do derived query methods work in Spring Data JPA?

Save to ▾
Show answer
Spring Data parses the method name in a repository interface and builds the query. For example, findByEmailAndActiveTrue(String email) or findTop5ByCategoryOrderByPriceDesc(String category). Supported keywords include And, Or, Between, LessThan, Like, In, IsNull and OrderBy. Return types can be Optional, List, Page or Stream. For complex logic, use @Query with JPQL or native SQL, because very long method names become hard to read.
78

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

Write a JPA entity for a Product with an auto-generated ID and basic constraints.

Save to ▾
Show answer
@Entity @Table(name = "products") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 120) private String name; @Column(nullable = false, precision = 10, scale = 2) private BigDecimal price; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "category_id") private Category category; protected Product() {} // required by JPA }
80

How do you learn a new framework or library quickly when a project needs it?

Save to ▾
Show answer
I start with the official getting-started guide and build a tiny working example, then read how it is used in our codebase. For example, when our team adopted Flyway, I created a sample project, tried failure cases like a bad migration and wrote a one-page guide for the team. Within a week I was handling migrations in the main project. I also note questions and clarify them with seniors early instead of guessing.
81

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

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

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

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

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

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

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); }
88

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

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

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

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

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

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

Explain the first-level and second-level cache in Hibernate.

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

How does optimistic locking work with @Version?

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

Build a dynamic search with optional filters using JPA Specifications.

Save to ▾
Show answer
public class ProductSpecs { public static Specification<Product> hasCategory(String c) { return (root, q, cb) -> c == null ? null : cb.equal(root.get("category").get("name"), c); } public static Specification<Product> priceBetween(BigDecimal min, BigDecimal max) { return (root, q, cb) -> (min == null || max == null) ? null : cb.between(root.get("price"), min, max); } } // Repository extends JpaSpecificationExecutor<Product> repo.findAll(Specification.where(hasCategory(cat)) .and(priceBetween(min, max)), pageable);
97

A product listing page fires hundreds of SQL queries for one request. How do you fix it?

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

Two admins edit the same product price at the same time and one change is silently lost. How do you prevent this?

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

Inserting one lakh rows with saveAll takes many minutes. How do you speed it up?

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

Describe a time you improved the performance of an application.

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

What are the key principles of a RESTful API?

Save to ▾
Show answer
REST treats everything as a resource identified by a URL, such as /api/orders/42, and uses standard HTTP methods to act on it. Requests are stateless, so each one carries all the information needed, including the auth token. Responses use proper status codes and representations, usually JSON, and can be cacheable. Good REST design uses nouns in URLs, plural resource names, nested paths for relations and query parameters for filtering and pagination.
102

Which HTTP methods are safe and which are idempotent?

Save to ▾
Show answer
Safe methods do not change server state: GET, HEAD and OPTIONS. Idempotent methods give the same result if repeated: GET, PUT, DELETE, HEAD and OPTIONS. POST is neither, so retrying a POST can create duplicate orders, which is why payment APIs use an idempotency key header. PATCH is not guaranteed idempotent. Knowing this matters for retries in clients, gateways and message consumers.
103

Explain the common HTTP status codes a REST API should return.

Save to ▾
Show answer
200 OK for successful reads and updates, 201 Created with a Location header after creating a resource, and 204 No Content for successful deletes. 400 Bad Request for validation errors, 401 Unauthorized when authentication is missing or invalid, 403 Forbidden when the user is authenticated but not allowed, 404 Not Found, 409 Conflict for version or duplicate conflicts, and 429 Too Many Requests for rate limits. 500 means an unexpected server error and 503 means temporarily unavailable.
104

What is the difference between authentication and authorization?

Save to ▾
Show answer
Authentication verifies who the user is, for example by checking a password, OTP or token. Authorization decides what that authenticated user is allowed to do, for example only admins can delete products. In Spring Security, authentication produces an Authentication object with granted authorities, and authorization uses those authorities in URL rules or annotations like @PreAuthorize("hasRole('ADMIN')"). A failed authentication gives 401 and a failed authorization gives 403.
105

Write a basic CRUD REST controller in Spring Boot.

Save to ▾
Show answer
@RestController @RequestMapping("/api/products") public class ProductController { private final ProductService service; public ProductController(ProductService service) { this.service = service; } @GetMapping("/{id}") public ProductDto get(@PathVariable Long id) { return service.get(id); } @PostMapping public ResponseEntity<ProductDto> create(@Valid @RequestBody ProductRequest req) { ProductDto saved = service.create(req); return ResponseEntity.created(URI.create("/api/products/" + saved.id())).body(saved); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable Long id) { service.delete(id); } }
106

How do you store user passwords securely in Spring Boot? Show the code.

Save to ▾
Show answer
@Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12); } public void register(RegisterRequest req) { User user = new User(req.email(), encoder.encode(req.password())); userRepository.save(user); } public boolean checkLogin(String raw, User user) { return encoder.matches(raw, user.getPasswordHash()); } // BCrypt adds a random salt and is deliberately slow. // Never store plain text or use MD5/SHA-1 for passwords.
107

How do you work with frontend developers and testers on API changes?

Save to ▾
Show answer
I agree on the API contract first using an OpenAPI spec or Swagger UI, so frontend and QA can start in parallel with mock data. I share example requests and error responses, and I tell the team early if a field must change. For example, in my last sprint I gave QA a Postman collection with test cases for every endpoint. This reduced back-and-forth and our feature passed testing on the first cycle.
108

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

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

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

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

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

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

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

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

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

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

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

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

How does the Spring Security filter chain process a request?

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

What is the circuit breaker pattern and how is it implemented in Spring?

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

Configure Spring Security 6 for a stateless JWT-secured REST API.

Save to ▾
Show answer
@Configuration @EnableMethodSecurity public class SecurityConfig { @Bean SecurityFilterChain api(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .cors(Customizer.withDefaults()) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth .requestMatchers("/api/auth/**", "/actuator/health").permitAll() .requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN") .anyRequest().authenticated()) .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())); return http.build(); } }
123

A user's JWT is stolen and you need to invalidate it before expiry. How would you design for this?

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

An order service and a payment service have separate databases. How do you keep data consistent when placing an order?

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

A downstream service is slow, and your API threads are all stuck waiting. What do you do?

Save to ▾
Show answer
Set connection and read timeouts on every client call, because the defaults can wait far too long. Add a Resilience4j circuit breaker with a fallback and a bulkhead to limit concurrent calls to that service, plus retries only with backoff and only for idempotent requests. Consider caching the downstream data or making the call asynchronous through a queue. Monitor latency percentiles and thread pool usage with Micrometer to confirm the fix.
126

What is the difference between a primary key and a unique key?

Save to ▾
Show answer
A primary key uniquely identifies each row, cannot be null, and a table has only one, although it may span several columns. A unique key also enforces uniqueness but a table can have many, and most databases allow null values in it. Both create an index automatically. For example, id is the primary key of a users table while email and mobile have unique constraints.
127

Explain the different types of SQL joins.

Save to ▾
Show answer
INNER JOIN returns only rows that match in both tables. LEFT JOIN returns all rows from the left table plus matches from the right, with nulls where there is no match. RIGHT JOIN is the reverse. FULL OUTER JOIN returns all rows from both sides, which MySQL does not support directly. CROSS JOIN returns every combination. A self join joins a table to itself, such as employees and their managers.
128

What is the difference between WHERE and HAVING?

Save to ▾
Show answer
WHERE filters individual rows before grouping and cannot use aggregate functions. HAVING filters groups after GROUP BY and can use aggregates like COUNT or SUM. For example, SELECT dept, COUNT(*) FROM employees WHERE active = true GROUP BY dept HAVING COUNT(*) > 10. Put conditions in WHERE whenever possible because filtering earlier reduces the rows the database must group.
129

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

What is the difference between DELETE, TRUNCATE and DROP?

Save to ▾
Show answer
DELETE removes selected rows using a WHERE clause, logs each row, fires triggers and can be rolled back. TRUNCATE removes all rows quickly by deallocating pages, resets identity counters in most databases and is treated as DDL, so rollback support depends on the database. DROP removes the whole table, including its structure, indexes and constraints. Use DELETE for business data and TRUNCATE for staging tables.
131

Write a query to find the second highest salary from an employees table.

Save to ▾
Show answer
-- Using a subquery SELECT MAX(salary) AS second_highest FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); -- Using DISTINCT with OFFSET SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1; -- The first query returns NULL when there is no second salary.
132

Write a query to find duplicate email addresses in a users table and delete the extra rows.

Save to ▾
Show answer
-- Find duplicates SELECT email, COUNT(*) AS cnt FROM users GROUP BY email HAVING COUNT(*) > 1; -- Keep the lowest id, delete the rest (MySQL / PostgreSQL) DELETE FROM users u USING users k WHERE u.email = k.email AND u.id > k.id; -- PostgreSQL syntax -- Then add: ALTER TABLE users ADD CONSTRAINT ux_email UNIQUE (email);
133

A security review found a login query built by string concatenation. What is the risk and the fix?

Save to ▾
Show answer
Concatenating user input into SQL allows SQL injection, where input like ' OR '1'='1 changes the query and can bypass login or dump data. Use parameterised queries: PreparedStatement with ? placeholders, Spring Data method queries, or @Query with named parameters, which send values separately from the SQL. Also validate input, use a database user with least privilege and never show raw SQL errors to users.
134

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

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

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

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

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

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

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%'.
141

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

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

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

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

Explain transaction isolation levels and the problems each one prevents.

Save to ▾
Show answer
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 = ...).
146

How does column order matter in a composite index?

Save to ▾
Show answer
A composite B-tree index on (customer_id, status, created_at) is sorted by the first column, then the second, and so on. It can serve queries filtering on customer_id, on customer_id and status, or all three, following the leftmost prefix rule, but it cannot efficiently serve a filter on status alone. Put equality columns first and range or sort columns last. A covering index includes all selected columns so the table need not be read.
147

How do you use EXPLAIN to analyse a slow query?

Save to ▾
Show answer
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);
148

Your application logs show database deadlock errors during peak hours. How do you resolve them?

Save to ▾
Show answer
A deadlock happens when two transactions lock rows in opposite order and wait for each other; the database kills one. Read the deadlock report, such as SHOW ENGINE INNODB STATUS, to find the statements. Fix by updating rows in a consistent order, keeping transactions short, avoiding user interaction or remote calls inside transactions and adding indexes so updates lock fewer rows. Also add a retry for the deadlock error because occasional ones are normal.
149

Under load, requests fail with a connection timeout from HikariCP. What do you check?

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

Paging through a large table with OFFSET becomes very slow on later pages. What is a better approach?

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

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

What is the difference between props and state?

Save to ▾
Show answer
Props are inputs passed from a parent component and are read-only inside the child. State is data owned by a component that can change over time, managed with useState or useReducer, and changing it triggers a re-render. For example, a ProductCard receives a product as props, while a cart counter keeps its quantity in state. When two components need the same state, lift it up to their common parent.
153

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

How do you take feedback from a senior on your React code?

Save to ▾
Show answer
Situation: in my first month, a senior reviewer left many comments about large components and duplicated fetch logic. Task: improve the code and learn from it. Action: I thanked him, asked for a short call to understand the reasoning, split the component, and wrote a custom hook for data fetching. Result: the pull request was approved, and the hook was reused in three other screens. I now self-review using his checklist.
155

Implement a cart counter using useReducer.

Save to ▾
Show answer
function cartReducer(state, action) { switch (action.type) { case 'add': return { count: state.count + 1 }; case 'remove': return { count: Math.max(0, state.count - 1) }; case 'reset': return { count: 0 }; default: throw new Error('Unknown action ' + action.type); } } function Cart() { const [state, dispatch] = useReducer(cartReducer, { count: 0 }); return ( <div> <span>Items: {state.count}</span> <button onClick={() => dispatch({ type: 'add' })}>+</button> <button onClick={() => dispatch({ type: 'remove' })}>-</button> </div> ); }
156

You are passing the same user prop through five levels of components. What would you do?

Save to ▾
Show answer
This is prop drilling, which makes intermediate components depend on data they do not use. For global, rarely changing data like the logged-in user or theme, create a context with a provider at the top and read it with useContext through a custom hook such as useAuth. Alternatively, use component composition, passing ready-made elements as children. For complex shared state, a store like Zustand or Redux Toolkit is suitable.
157

How do you handle a disagreement with a UI designer about a screen?

Save to ▾
Show answer
Situation: a designer wanted a complex animated table that would be slow on low-end phones. Task: protect performance without dismissing the design. Action: I built a quick prototype, showed the lag on a budget Android device and proposed a lighter animation with the same feel. Result: the designer agreed, the page stayed fast, and we started reviewing performance impact together during design discussions.
158

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

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

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

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

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

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

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

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}`);
166

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> ); }
167

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

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

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

What triggers a re-render in React, and how does reconciliation decide what to update?

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

Create a protected route in React Router that redirects unauthenticated users to login.

Save to ▾
Show answer
function ProtectedRoute({ roles }) { const { user } = useAuth(); const location = useLocation(); if (!user) { return <Navigate to="/login" replace state={{ from: location }} />; } if (roles && !roles.includes(user.role)) { return <Navigate to="/unauthorized" replace />; } return <Outlet />; } // Routes <Route element={<ProtectedRoute roles={['ADMIN']} />}> <Route path="/admin" element={<AdminDashboard />} /> </Route> // The backend must still enforce authorization on every API.
172

Add the JWT to every API call and handle 401 responses using an Axios interceptor.

Save to ▾
Show answer
const api = axios.create({ baseURL: import.meta.env.VITE_API_URL }); api.interceptors.request.use(config => { const token = getAccessToken(); if (token) config.headers.Authorization = `Bearer ${token}`; return config; }); api.interceptors.response.use( res => res, async error => { const original = error.config; if (error.response?.status === 401 && !original._retry) { original._retry = true; await refreshToken(); // calls /api/auth/refresh with cookie return api(original); } return Promise.reject(error); });
173

A table showing 10,000 rows makes the page very slow. How would you improve it?

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

Where should a React app store the JWT, and what are the trade-offs?

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

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

What is the difference between var, let and const?

Save to ▾
Show answer
var is function-scoped, hoisted and initialised as undefined, and can be redeclared, which causes bugs in loops and blocks. let and const are block-scoped and stay in the temporal dead zone until declared, so using them early throws an error. let allows reassignment and const does not, although a const object or array can still be mutated. Use const by default, let when reassignment is needed and avoid var.
177

What is the difference between == and === in JavaScript?

Save to ▾
Show answer
== compares after type coercion, so 0 == '0' and null == undefined are true, which leads to surprising results. === compares both type and value without coercion, so 0 === '0' is false. Always use === and !== in application code. The only common exception is value == null, which checks for both null and undefined in one expression.
178

What is hoisting in JavaScript?

Save to ▾
Show answer
During compilation, declarations are moved to the top of their scope. Function declarations are hoisted fully, so they can be called before they appear. var declarations are hoisted and initialised to undefined. let, const and class declarations are hoisted but stay uninitialised in the temporal dead zone, so accessing them early throws a ReferenceError. Function expressions assigned to variables follow the variable's rules.
179

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

When would you use Flexbox and when CSS Grid?

Save to ▾
Show answer
Flexbox is one-dimensional: it arranges items in a row or a column and is great for navbars, button groups, centring and card rows that wrap. Grid is two-dimensional: it controls rows and columns together, ideal for page layouts, dashboards and galleries with grid-template-areas. They work well together, for example a Grid page layout with Flexbox inside each card. Both reduce the need for floats and positioning hacks.
181

Why are semantic HTML and accessibility important?

Save to ▾
Show answer
Semantic elements like header, nav, main, article, button and label describe meaning, so screen readers, search engines and browsers understand the page. Use a real button instead of a clickable div so keyboard and focus work automatically. Add alt text to images, link labels to inputs, keep heading order logical and ensure enough colour contrast. Accessibility follows WCAG guidelines and improves SEO and usability for everyone.
182

Use map, filter and reduce to get the total value of in-stock products.

Save to ▾
Show answer
const products = [ { name: 'Pen', price: 20, qty: 10, inStock: true }, { name: 'Bag', price: 900, qty: 0, inStock: false }, { name: 'Book', price: 250, qty: 4, inStock: true }, ]; const total = products .filter(p => p.inStock) .map(p => p.price * p.qty) .reduce((sum, value) => sum + value, 0); console.log(total); // 1200
183

Centre a div horizontally and vertically using CSS.

Save to ▾
Show answer
.container { display: flex; justify-content: center; /* horizontal */ align-items: center; /* vertical */ min-height: 100vh; } /* Grid alternative */ .container { display: grid; place-items: center; min-height: 100vh; }
184

Write CSS for a product grid that shows 1 column on mobile, 2 on tablet and 4 on desktop.

Save to ▾
Show answer
.grid { display: grid; grid-template-columns: 1fr; gap: 16px; padding: 0 16px; } @media (min-width: 640px) { .grid { grid-template-columns: repeat(2, 1fr); } } @media (min-width: 1024px) { .grid { grid-template-columns: repeat(4, 1fr); } } /* Mobile-first: base styles for small screens, then widen. */
185

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

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

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

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

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

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

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

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

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

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

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

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

Explain the JavaScript event loop, including microtasks and macrotasks.

Save to ▾
Show answer
JavaScript runs on a single thread with a call stack. Asynchronous work is handled by the browser or Node, and callbacks wait in queues. After the stack empties, the event loop runs all microtasks first, such as promise callbacks and queueMicrotask, then one macrotask, such as setTimeout or an I/O callback, then renders if needed. So Promise.resolve().then(a) runs before setTimeout(b, 0). Long synchronous code blocks everything, including UI updates.
198

Your React app's home page takes 6 seconds to load on mobile. How would you improve it?

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

A security test shows a stored XSS vulnerability in a comments feature. How do you fix it?

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

Memory usage of a single-page app keeps growing the longer it stays open. What could cause this?

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

Frequently asked questions

What jobs can I get after learning Java full stack with React?

You can apply for roles such as Java full stack developer, Spring Boot backend developer, React frontend developer, software engineer and associate software engineer. These roles exist in IT services companies, banks and fintech firms, global capability centres and startups across Bengaluru, Hyderabad, Pune, Noida, Gurugram and Chennai. With experience, you can grow into senior engineer, technical lead or solution architect roles. A strong project portfolio and good fundamentals matter more than the course title.

Who is eligible to learn Java full stack development?

Anyone with basic computer knowledge and logical thinking can start. B.Tech, BCA, MCA, B.Sc and diploma students are common learners, and working professionals from testing, support or non-IT backgrounds also switch successfully. Prior coding experience helps but is not required, because the course starts with Java fundamentals. Recruiters for fresher roles usually check graduation status and percentage cut-offs, so confirm those for the companies you target.

How long does it take to become job-ready in Java full stack?

With consistent study of 2 to 3 hours a day, most learners become job-ready in about 6 months. Core Java and SQL take around two months, web basics and React about two months, and Spring Boot, security and deployment about two more. The timeline depends on daily practice, coding problem solving and building two or three complete projects. Working professionals studying part-time may need 7 to 9 months.

Is Java full stack still in demand in 2026?

Yes. Java remains one of the most used languages for enterprise backends, especially in banking, insurance, telecom, retail and government projects, and Spring Boot is the default framework for new Java services. React is the most popular frontend library. Companies value developers who can work on both layers and understand cloud deployment. AI coding tools speed up routine work, so strong fundamentals, debugging and system design skills are what set candidates apart.

Which certifications help a Java full stack developer?

Certifications are optional but can strengthen a fresher's resume. Useful ones include Oracle Certified Professional Java SE 17 or 21 Developer, the Spring Certified Professional, and a cloud certification such as AWS Certified Developer Associate or Azure Developer Associate. A course completion certificate shows training, but interviewers mainly judge projects, GitHub activity and how well you answer technical questions, so treat certifications as a supplement.

Do I need to learn data structures and algorithms for Java full stack interviews?

Yes, at least the basics. Service companies test arrays, strings, hashing, sorting and simple recursion in online assessments, while product companies and banks also ask linked lists, trees, graphs and dynamic programming. Practise in Java so you also strengthen your collections knowledge. Aim to solve around 150 to 200 well-chosen problems alongside your projects, focusing on understanding patterns rather than memorising solutions.