Skip to content

Java Full Stack with React Online Assessment Questions & Answers

40 questions for the online assessment stage — 20 easy, 20 medium.

About the online assessment round

Most companies start with an online test: aptitude and reasoning, a few MCQs on core Java Full Stack with React concepts, and one or two short hands-on tasks. It filters a large number of applicants, so speed and accuracy both count.

Tips for the online assessment round

  • Practise under a timer: about one minute per MCQ and 15-20 minutes per hands-on task.
  • Read every option before answering; tests often include two nearly correct choices.
  • Use a stable internet connection, keep your camera on and avoid switching tabs in proctored tests.
  • Attempt the questions you are sure about first, then return to the harder ones.
Solved — online assessmentStart 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Frequently asked questions

What happens in the Java Full Stack with React online assessment round?

Most companies start with an online test: aptitude and reasoning, a few MCQs on core Java Full Stack with React concepts, and one or two short hands-on tasks. It filters a large number of applicants, so speed and accuracy both count.

How do I clear the online assessment round?

Practise under a timer: about one minute per MCQ and 15-20 minutes per hands-on task. Read every option before answering; tests often include two nearly correct choices. Use a stable internet connection, keep your camera on and avoid switching tabs in proctored tests.

Which round comes next?

A typical order is online assessment, telephonic screening, one or two technical rounds, a managerial round and HR. Use the other round pages to practise each stage.