Skip to content

Java Full Stack with React Interview Questions for Freshers

40 questions with answers for candidates with Freshers — 32 easy, 8 medium.

What interviewers expect: freshers

Fresher interviews focus on fundamentals and your projects. Expect core Java and OOP questions, collections, simple SQL queries, a few Spring Boot basics and basic HTML, CSS, JavaScript and React. Online tests usually include aptitude and two or three coding problems. Interviewers will ask you to explain your project architecture, the APIs you built and what you personally did, so know every line of it.

This set is weighted towards React Frontend (7), REST APIs, Security and Microservices (6), SQL and Databases (5), JavaScript, HTML and CSS (5).

Core Java and OOP Collections and simple coding problems SQL joins and grouping Explaining a full stack project
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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)

Frequently asked questions

What is asked in Java Full Stack with React interviews for Freshers?

Fresher interviews focus on fundamentals and your projects. Expect core Java and OOP questions, collections, simple SQL queries, a few Spring Boot basics and basic HTML, CSS, JavaScript and React. Online tests usually include aptitude and two or three coding problems. Interviewers will ask you to explain your project architecture, the APIs you built and what you personally did, so know every line of it.

How many questions should I practise before a Java Full Stack with React interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for Freshers?

Focus first on Core Java and OOP, Collections and simple coding problems, SQL joins and grouping, Explaining a full stack project.