Skip to content

Full Stack Java Developer Interview Questions & Answers

40 questions for Full Stack Java Developer interviews — 18 easy, 22 medium.

About the Full Stack Java Developer role

A full stack Java developer builds both the Spring Boot backend and a web frontend, usually in React or Angular. The role covers database design, REST APIs, UI screens, authentication and deployment. It suits startups and services firms that want one engineer to deliver complete features, and freshers with good project portfolios often enter through this path. Good knowledge of HTML, CSS and JavaScript is expected as well.

Java Spring Boot React or Angular MySQL REST APIs
Solved for this roleStart 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

Implement equals() and hashCode() for an Employee class with id and email.

Save to ▾
Show answer
Use the same fields in both methods. @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Employee e)) return false; return id == e.id && Objects.equals(email, e.email); } @Override public int hashCode() { return Objects.hash(id, email); } Pattern matching for instanceof (Java 16) avoids an explicit cast.
02

Can you override a static or private method in Java?

Save to ▾
Show answer
No. Private methods are not visible to subclasses, so a method with the same name in a child is a new method. Static methods belong to the class; a static method with the same signature in a child hides the parent one, and which one runs depends on the reference type, not the object. The @Override annotation on such methods gives a compile error.
03

Explain the entity lifecycle states in JPA.

Save to ▾
Show answer
Transient: a new object not yet linked to a persistence context. Managed (persistent): attached to the context, so changes are tracked and flushed automatically through dirty checking. Detached: was managed but the context closed or it was evicted; changes are not tracked until merge(). Removed: scheduled for deletion on flush. persist, merge, detach and remove move entities between these states.
04

A team member compares two Integer values with == and the check fails only for large numbers. Explain.

Save to ▾
Show answer
Integer.valueOf caches objects for values from -128 to 127, so autoboxed small numbers share the same object and == returns true. Larger values create new Integer objects, so == compares two different references and returns false. The fix is to use equals() or compare unboxed int values. Static analysis tools like SonarQube flag this pattern.
05

What is the N+1 select problem in Hibernate and how do you fix it?

Save to ▾
Show answer
N+1 happens when you load N parent entities with one query and then a lazy association triggers one extra query per parent, giving N+1 queries. Fix it with a JOIN FETCH in JPQL, an @EntityGraph on the repository method, or batch fetching with @BatchSize or hibernate.default_batch_fetch_size. Detect it by enabling SQL logging or using a query count assertion in tests.
06

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

Save to ▾
Show answer
Mock the repository and verify behaviour. @ExtendWith(MockitoExtension.class) class ProductServiceTest { @Mock ProductRepository repo; @InjectMocks ProductService service; @Test void throwsWhenMissing() { when(repo.findById(1L)).thenReturn(Optional.empty()); assertThrows(NotFoundException.class, () -> service.get(1L)); verify(repo).findById(1L); } } No Spring context starts, so the test runs in milliseconds.
07

How do you make a class immutable in Java?

Save to ▾
Show answer
Declare the class final, make all fields private and final, set them only in the constructor, and provide no setters. For mutable fields like a List or Date, make defensive copies in the constructor and in getters, or use List.copyOf. Immutable objects are thread safe and make good map keys. Java records give a concise way to create shallowly immutable data classes.
08

Write a record with validation in its compact constructor.

Save to ▾
Show answer
A compact constructor runs before fields are assigned. public record Money(String currency, long paise) { public Money { Objects.requireNonNull(currency); if (paise < 0) { throw new IllegalArgumentException("negative amount"); } } public Money add(Money o) { return new Money(currency, paise + o.paise); } } Storing money in paise as long avoids floating point errors.
09

What is the difference between HashMap, LinkedHashMap and TreeMap?

Save to ▾
Show answer
HashMap gives O(1) average operations with no ordering guarantee. LinkedHashMap keeps insertion order, or access order if configured, which helps build an LRU cache. TreeMap keeps keys sorted by natural order or a Comparator with O(log n) operations and supports range methods like floorKey and headMap. HashMap allows one null key; TreeMap does not allow null keys with natural ordering.
10

Why should we hire you as a Java backend developer?

Save to ▾
Show answer
Situation: in my current role I build Spring Boot services for a payments product. Task: show impact beyond writing code. Action: I improved API latency by 60 percent through query tuning and caching, raised test coverage from 40 to 80 percent and handled on-call calmly. Result: I bring solid Java, Spring and SQL skills, ownership of production and a habit of measuring results, which fits this role.
11

Compare String, StringBuilder and StringBuffer.

Save to ▾
Show answer
String is immutable and thread safe by design. StringBuilder is mutable and not synchronized, so it is the fastest choice for building strings in a single thread, such as in loops. StringBuffer is mutable and synchronized, so it is thread safe but slower, and is rarely needed today. The compiler already optimises simple + concatenation outside loops.
12

What are the primitive data types in Java and their sizes?

Save to ▾
Show answer
Java has eight primitives: byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2 bytes, UTF-16 code unit) and boolean (true or false, size JVM dependent). Primitives store values directly and have default values when used as fields, for example 0 for int and false for boolean. Each has a wrapper class such as Integer.
13

How do you explain OOP concepts to a junior developer who is new to Java?

Save to ▾
Show answer
Situation: I mentored two interns who struggled with OOP. Task: help them design classes for a library app. Action: I used real objects they knew, like Book and Member, showed encapsulation with private fields, then wrote one interface with two implementations to show polymorphism, and reviewed their code daily. Result: within two weeks they designed modules on their own and their pull requests needed fewer review comments.
14

Tell me about a time a production incident happened because of your code.

Save to ▾
Show answer
Situation: a release I made caused failed payments for some users. Task: restore service and find the cause fast. Action: I rolled back within ten minutes, then found I had not handled a null bank code from one partner, which threw an exception. I fixed it, added validation and a test with that partner's data and shared a short write-up. Result: no repeat and the team added null checks to our review checklist.
15

Write a Java program to check whether a number is prime.

Save to ▾
Show answer
Check divisibility only up to the square root, which makes it O(sqrt n). public static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (int i = 3; (long) i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } The long cast avoids overflow for large n.
16

Explain the main memory areas of the JVM.

Save to ▾
Show answer
The heap stores all objects and is shared by threads; it is managed by the garbage collector. Each thread has its own stack holding frames with local variables and partial results. Metaspace (native memory since Java 8) stores class metadata. There are also the program counter register and native method stacks. StackOverflowError comes from the stack and OutOfMemoryError usually from heap or metaspace.
17

What are the four pillars of OOP? Explain with Java examples.

Save to ▾
Show answer
Encapsulation hides data behind methods, for example private fields with getters and setters in a BankAccount class. Abstraction exposes only what is needed through abstract classes or interfaces, like a Payment interface. Inheritance lets a class reuse another, such as SavingsAccount extends Account. Polymorphism lets one reference behave differently, like a Payment variable calling pay() on a UpiPayment or CardPayment.
18

Sort a list of employees by department, then by salary descending.

Save to ▾
Show answer
Chain comparators. employees.sort( Comparator.comparing(Employee::department) .thenComparing(Employee::salary, Comparator.reverseOrder())); // Streams version returning a new list List<Employee> sorted = employees.stream() .sorted(Comparator.comparing(Employee::department) .thenComparing(Employee::salary, Comparator.reverseOrder())) .toList(); List.sort is stable, so equal keys keep their order.
19

Users get LazyInitializationException when the API returns an entity. What is happening?

Save to ▾
Show answer
The entity was loaded inside a transaction, the session closed, and then Jackson touched a lazy association outside it. Do not fix it by turning on open-session-in-view or making everything eager. Instead, map the entity to a DTO inside the service transaction and fetch needed associations explicitly with JOIN FETCH or an entity graph. Spring Boot logs a warning because open-in-view is on by default.
20

What is the difference between start() and run()?

Save to ▾
Show answer
start() asks the JVM to create a new thread and then calls run() on that new thread, so the code executes concurrently. Calling run() directly is just a normal method call on the current thread, so no new thread is created. Calling start() twice on the same Thread throws IllegalThreadStateException.
21

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

Save to ▾
Show answer
If two objects are equal by equals(), they must return the same hashCode(). Unequal objects may share a hash code, but fewer collisions give better performance. If you override equals() but not hashCode(), HashMap and HashSet break: an equal key lands in a different bucket and cannot be found. Use the same fields in both methods, or use records, which generate both.
22

Why does Java not support multiple inheritance of classes?

Save to ▾
Show answer
Multiple inheritance of classes creates the diamond problem: if two parents have the same method with different code, the child cannot know which one to use, and state duplication becomes messy. Java avoids this by allowing one superclass but many interfaces. If two interfaces provide the same default method, the class must override it and can call a specific one with InterfaceName.super.method().
23

What is the difference between method overloading and method overriding?

Save to ▾
Show answer
Overloading means several methods in the same class share a name but differ in parameter list; it is resolved at compile time. Overriding means a subclass provides its own version of a parent method with the same signature; it is resolved at runtime through dynamic dispatch. Return type alone cannot overload a method, while overriding allows a covariant return type.
24

Explain the SOLID principles briefly.

Save to ▾
Show answer
Single Responsibility: a class has one reason to change. Open/Closed: open for extension, closed for modification. Liskov Substitution: subclasses must work wherever the parent is expected. Interface Segregation: prefer small, focused interfaces. Dependency Inversion: depend on abstractions, not concrete classes. Spring dependency injection is a practical example of dependency inversion.
25

What is the difference between static and dynamic binding?

Save to ▾
Show answer
Static binding is resolved at compile time and applies to private, static and final methods and to overloaded methods, because the compiler knows exactly which method to call. Dynamic binding is resolved at runtime based on the actual object type and applies to overridden instance methods. Static methods are hidden, not overridden, so the reference type decides which one runs.
26

What is constructor chaining?

Save to ▾
Show answer
Constructor chaining is calling one constructor from another. this(...) calls another constructor in the same class and super(...) calls a parent class constructor; either must be the first statement. If you write neither, the compiler inserts super() automatically. Chaining avoids duplicate initialisation code, for example a no-arg constructor calling this("default", 0).
27

Map a one-to-many relation between Order and OrderItem in JPA.

Save to ▾
Show answer
Make the child own the foreign key and keep both sides in sync. @Entity class Order { @Id @GeneratedValue Long id; @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) List<OrderItem> items = new ArrayList<>(); void addItem(OrderItem i) { items.add(i); i.setOrder(this); } } @Entity class OrderItem { @Id @GeneratedValue Long id; @ManyToOne(fetch = FetchType.LAZY) Order order; }
28

Clients report duplicate orders when they retry after a timeout. How do you prevent it?

Save to ▾
Show answer
Make the create order API idempotent. The client sends an Idempotency-Key header; the server stores the key with the result in a table with a unique constraint or in Redis. A retry with the same key returns the saved response instead of creating a new order. Database unique constraints on business keys add another safety net.
29

Objects used as HashMap keys cannot be found after insertion. What could be wrong?

Save to ▾
Show answer
Most likely the class overrides equals() but not hashCode(), or neither, so equal keys land in different buckets. Another cause is a mutable key: a field used in hashCode() was changed after insertion, so the lookup goes to a different bucket. The fix is to implement both methods on the same fields and use immutable keys such as String, records or final classes.
30

Count the frequency of each character in a string using Java.

Save to ▾
Show answer
A map with merge() is simple; streams also work. Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.merge(c, 1, Integer::sum); } // Streams version Map<Character, Long> f = s.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting())); LinkedHashMap keeps first-seen order.
31

Write a simple REST controller in Spring Boot for creating and fetching products.

Save to ▾
Show answer
Use constructor injection and validation. @RestController @RequestMapping("/api/products") class ProductController { private final ProductService service; ProductController(ProductService service) { this.service = service; } @PostMapping ResponseEntity<Product> create(@Valid @RequestBody ProductRequest req) { Product p = service.create(req); return ResponseEntity.created(URI.create("/api/products/" + p.id())).body(p); } @GetMapping("/{id}") Product get(@PathVariable Long id) { return service.get(id); } }
32

Write a Spring Data JPA repository method that fetches orders with items to avoid N+1.

Save to ▾
Show answer
Use JOIN FETCH or an entity graph. public interface OrderRepository extends JpaRepository<Order, Long> { @Query("select distinct o from Order o join fetch o.items where o.customerId = :cid") List<Order> findWithItems(@Param("cid") Long customerId); @EntityGraph(attributePaths = "items") List<Order> findByStatus(String status); } Both load orders and items in one query.
33

What are records in Java and when should you use them?

Save to ▾
Show answer
Records, final in Java 16, are concise classes for immutable data. record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors, equals(), hashCode() and toString(). You can add validation in a compact constructor and add methods. Use them for DTOs, API responses and map keys. They cannot extend another class and are not suited to JPA entities, which need mutability.
34

What is the difference between @Component, @Service, @Repository and @Controller?

Save to ▾
Show answer
All four mark a class as a Spring bean for component scanning. @Service and @Component are functionally the same, with @Service showing business logic intent. @Repository also enables translation of persistence exceptions into Spring DataAccessException. @Controller handles web requests and returns views, and @RestController adds @ResponseBody so return values are written as JSON.
35

A query is fast in development but takes 8 seconds in production. How do you investigate?

Save to ▾
Show answer
Production has more data, so check the execution plan with EXPLAIN ANALYZE on production-like data. Look for full table scans, missing indexes on filter or join columns, functions on indexed columns and poor statistics. Check if Hibernate generates the SQL you expect. Add a suitable composite index, rewrite the query or paginate, and verify the plan improves before release.
36

What is the difference between an abstract class and an interface in modern Java?

Save to ▾
Show answer
An abstract class can have state (instance fields), constructors and any access modifier, and a class can extend only one. An interface has no instance state but, since Java 8, can have default and static methods, and since Java 9 private methods; a class can implement many. Use an interface for a capability contract and an abstract class to share code and state among closely related classes.
37

What is Spring Boot Actuator used for?

Save to ▾
Show answer
Actuator adds production endpoints such as /actuator/health for liveness and readiness probes, /actuator/metrics and /actuator/prometheus for Micrometer metrics, plus info, loggers and thread dumps. Expose only what you need with management.endpoints.web.exposure.include and secure sensitive endpoints with Spring Security. Kubernetes uses the health groups to decide restarts and traffic routing.
38

Why did you choose Java for your career?

Save to ▾
Show answer
Situation: in college I tried several languages for projects. Task: I wanted one that leads to stable, well paid work. Action: I found Java powers banking, ecommerce and enterprise backends, has strong tooling and a huge job market, so I built two Spring Boot projects and practised DSA in Java. Result: I am confident in the language and keen to keep learning modern features like records and virtual threads.
39

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

Save to ▾
Show answer
Sort distinct salaries in descending order and skip one. Optional<Integer> second = employees.stream() .map(Employee::salary) .distinct() .sorted(Comparator.reverseOrder()) .skip(1) .findFirst(); This returns empty if fewer than two distinct salaries exist. For huge data a single pass tracking top two is O(n).
40

You need to add a new payment method to a system that has a big if-else on payment type. How would you redesign it?

Save to ▾
Show answer
This breaks the Open/Closed principle. I would create a PaymentProcessor interface with a pay() method and one implementation per type, such as UpiProcessor and CardProcessor. A factory or a Spring map of beans keyed by type picks the right one. Adding a new method then means adding one new class without touching existing tested code, and each processor can be unit tested alone.

Frequently asked questions

What does a Full Stack Java Developer do?

A full stack Java developer builds both the Spring Boot backend and a web frontend, usually in React or Angular. The role covers database design, REST APIs, UI screens, authentication and deployment. It suits startups and services firms that want one engineer to deliver complete features, and freshers with good project portfolios often enter through this path. Good knowledge of HTML, CSS and JavaScript is expected as well.

Which skills are tested in a Full Stack Java Developer interview?

Expect questions on Java, Spring Boot, React or Angular, MySQL, REST APIs. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Full Stack Java Developer interview?

Revise Spring Boot and Microservices, OOP in Java, JDBC, Hibernate and JPA first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.