100 Java Full Stack Interview Questions and Answers

100 Java Full Stack Interview Questions and Answers

Interview Preparation Guide

100 Java Full Stack Interview Questions & Answers

From Core Java fundamentals to microservices and system design — a complete, interview-ready walkthrough of Java, Spring Boot, Spring MVC, Hibernate, JPA, SQL and Next.js.

100Questions
14Core Levels
190Code Examples
3Difficulty Levels

What You’ll Cover

Level: Beginner → Intermediate → Advanced

Technologies covered:

Core JavaOOPStringsExceptionsCollectionsGenericsJava 8+ featuresStreams & LambdasMultithreading & ConcurrencyJVM & MemoryJDBCServletsJSP fundamentalsSpring FrameworkSpring BootSpring MVCHibernateJPAREST APISpring SecurityJWTSQLTestingHTML/CSS/JavaScript fundamentalsThymeleafReact fundamentalsNext.jsMicroservicesDockerPerformanceDeploymentSystem Design
Level 1

Core Java Fundamentals

15 Questions
1

What is Java and why is it platform independent?

Java source code is compiled into bytecode rather than directly into machine-specific instructions.

Java Source
    ↓
javac
    ↓
Bytecode
    ↓
JVM
    ↓
Operating System

A JVM implementation for Windows, Linux or macOS executes the same bytecode.

This is the basis of:

> Write Once, Run Anywhere.

2

What is the difference between JDK, JRE and JVM?

JVM

Executes Java bytecode.

JRE

Traditionally refers to the runtime environment containing the JVM and libraries needed to run Java applications.

JDK

Contains development tools such as:

javac
java
javadoc
jdb
jar

For development, you install a JDK.

3

What are the four pillars of OOP?

The four major object-oriented concepts are:

Encapsulation

Keep data and behavior together and control access.

Inheritance

A class can inherit behavior from another class.

Polymorphism

The same interface or method call can have different implementations.

Abstraction

Expose necessary behavior while hiding implementation details.

4

What is the difference between a class and an object?

A class defines structure and behavior.

class Employee {
    String name;

    void work() {
        System.out.println("Working");
    }
}

An object is an instance of that class.

Employee employee = new Employee();

You can create multiple objects from the same class.

5

What is method overloading?

Method overloading means having multiple methods with the same name but different parameter lists.

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

It is resolved primarily at compile time.

6

What is method overriding?

Method overriding happens when a subclass provides its own implementation of an inherited method.

class Animal {
    void sound() {
        System.out.println("Animal");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

This is an example of runtime polymorphism.

7

Overloading vs overriding?

Overloading

Same method name, different parameter list.

Usually resolved at compile time.

Overriding

Subclass replaces an inherited method implementation.

Runtime dispatch determines which implementation executes.

8

What is an interface?

An interface defines a contract.

interface PaymentService {

    void pay(double amount);
}

Different implementations can provide different behavior.

class CardPayment implements PaymentService {

    public void pay(double amount) {
        // card payment
    }
}

Interfaces are heavily used in Spring because they encourage loose coupling and testability.

9

Abstract class vs interface?

An abstract class can contain:

  • instance state
  • constructors
  • concrete methods
  • abstract methods

An interface primarily defines a contract, although modern Java interfaces can also contain:

  • default methods
  • static methods
  • private helper methods

Use an interface when unrelated implementations should satisfy the same contract.

Use an abstract class when classes share substantial common state or implementation.

10

What is encapsulation?

Encapsulation restricts direct access to an object’s internal state.

Instead of:

public double balance;

use:

private double balance;

public double getBalance() {
    return balance;
}

The class controls how its data can be modified.

11

What is a constructor?

A constructor initializes an object.

class User {

    private String name;

    User(String name) {
        this.name = name;
    }
}

It has the same name as the class and no return type.

12

What is the static keyword?

A static member belongs to the class rather than an individual object.

class Counter {

    static int count = 0;
}

Access:

Counter.count;

Static methods cannot directly access instance variables without an object.

13

What is the difference between final , finally and finalize ?

final

Used to restrict modification.

final int MAX = 100;

A final method cannot be overridden.

A final class cannot be extended.

finally

Used with exception handling.

try {

} finally {

}

finalize()

Was historically associated with garbage collection cleanup but should not be used for resource-management design and has been deprecated.

14

What is the difference between == and .equals() ?

For objects:

== compares references.

.equals() normally compares logical equality when properly implemented.

String a = new String("Java");
String b = new String("Java");

System.out.println(a == b);       // false
System.out.println(a.equals(b));  // true

This question becomes particularly important with HashMap and HashSet.

15

Why must equals() and hashCode() usually be overridden together?

Hash-based collections use both.

If:

a.equals(b) == true

then the contract requires:

a.hashCode() == b.hashCode()

Otherwise collections such as:

HashMap
HashSet

may behave incorrectly.

Level 2

Strings, Exceptions & Collections

15 Questions
16

Why is String immutable in Java?

After a String object is created, its contents cannot change.

String name = "Java";

name.concat(" Developer");

The original String is unchanged.

Immutability helps with:

  • thread safety
  • String pool reuse
  • predictable hashing
  • security-sensitive values
  • caching
17

String vs StringBuilder vs StringBuffer?

String

Immutable.

StringBuilder

Mutable and normally preferred for repeated string manipulation in single-threaded code.

StringBuilder sb = new StringBuilder();
sb.append("Java");
sb.append(" Spring");

StringBuffer

Mutable and synchronized.

It has more synchronization overhead than StringBuilder.

18

What is the String Pool?

Java maintains a special pool for String literals.

String a = "Java";
String b = "Java";

Both may refer to the same pooled String object.

But:

String c = new String("Java");

explicitly creates another String object.

19

Checked vs unchecked exceptions?

Checked exceptions

Compiler requires them to be handled or declared.

Example:

IOException

Unchecked exceptions

Extend RuntimeException.

Examples:

NullPointerException
IllegalArgumentException
ArithmeticException

Unchecked exceptions commonly represent programming errors or invalid application state.

20

throw vs throws ?

throw actually throws an exception.

throw new IllegalArgumentException("Invalid age");

throws declares that a method may propagate an exception.

void readFile() throws IOException {
}
21

What is try-with-resources?

It automatically closes resources implementing AutoCloseable.

try (Connection connection =
         dataSource.getConnection()) {

    // database work
}

It is preferred over manually closing resources in many cases.

22

What is the Java Collections Framework?

It provides standard data structures and algorithms.

Major interfaces include:

Collection
 ├── List
 ├── Set
 └── Queue

Map

Common implementations include:

ArrayList
LinkedList
HashSet
TreeSet
HashMap
LinkedHashMap
TreeMap
PriorityQueue
23

ArrayList vs LinkedList?

ArrayList uses a dynamic array.

It provides efficient indexed access:

list.get(500);

LinkedList stores linked nodes.

Although LinkedList can perform certain insertions efficiently once a position/node is known, finding arbitrary positions requires traversal.

For most general application workloads, ArrayList is the more common default.

24

List vs Set?

List

Allows duplicates and maintains positional ordering.

ArrayList
LinkedList

Set

Does not allow duplicate elements according to its equality rules.

HashSet
LinkedHashSet
TreeSet
25

How does HashMap work internally?

A HashMap uses the key’s hash to locate a bucket.

Conceptually:

key
 ↓
hashCode()
 ↓
hash
 ↓
bucket
 ↓
equals() check
 ↓
value

Collisions can occur when multiple keys map to the same bucket.

Modern Java HashMap implementations can transform heavily collided buckets into tree-based structures under appropriate conditions.

Understanding HashMap internals remains one of the most common Collections topics in Java interviews.

26

HashMap vs Hashtable?

HashMap is not synchronized by default.

Hashtable is an older synchronized collection.

Modern concurrent applications usually prefer more appropriate alternatives such as:

ConcurrentHashMap

rather than Hashtable.

27

HashMap vs ConcurrentHashMap?

HashMap is not designed for concurrent modification by multiple threads without external synchronization.

ConcurrentHashMap is designed for concurrent access.

Example:

Map<String, Integer> cache =
    new ConcurrentHashMap<>();

It provides significantly better concurrent access than synchronizing an entire ordinary map for many workloads.

28

HashSet vs TreeSet?

HashSet is hash-based and does not provide sorted iteration.

TreeSet maintains sorted order.

Typical operation complexity:

HashSet → average O(1) lookup
TreeSet → O(log n)

Use TreeSet when sorted-set behavior is required.

29

Comparable vs Comparator?

Comparable defines a class’s natural ordering.

class Employee
    implements Comparable<Employee> {

    public int compareTo(Employee other) {
        return this.id - other.id;
    }
}

Comparator defines external or alternative ordering.

Comparator<Employee> byName =
    Comparator.comparing(Employee::getName);

Comparator is preferable when multiple sorting strategies are needed.

30

What is a fail-fast iterator?

Many ordinary collection iterators detect structural modification outside the iterator while iteration is occurring.

Example:

for (String value : list) {
    list.remove(value);
}

This can result in:

ConcurrentModificationException

Correct removal may instead use the iterator’s supported removal operation or another appropriate collection strategy.

Level 3

Java 8+, Streams & Functional Programming

9 Questions
31

What is a lambda expression?

A lambda provides a concise way to represent behavior for a functional interface.

Instead of:

Runnable r = new Runnable() {
    public void run() {
        System.out.println("Running");
    }
};

you can write:

Runnable r =
    () -> System.out.println("Running");
32

What is a functional interface?

A functional interface has one abstract method.

Examples include:

Runnable
Predicate
Function
Consumer
Supplier

Example:

@FunctionalInterface
interface Calculator {

    int calculate(int a, int b);
}
33

What is the Stream API?

Streams provide declarative processing over a data source.

Example:

List<String> names =
    users.stream()
         .filter(User::isActive)
         .map(User::getName)
         .toList();

A Stream does not itself store the collection.

It represents a processing pipeline.

Modern Java interviews frequently test stream laziness, map vs flatMap, collectors and parallel-stream trade-offs.

34

Intermediate vs terminal stream operations?

Intermediate operations include:

filter
map
flatMap
sorted
distinct

They typically build the pipeline lazily.

Terminal operations trigger execution.

Examples:

collect
toList
reduce
forEach
count
findFirst
35

map() vs flatMap() ?

map() transforms one element into another.

users.stream()
     .map(User::getName);

flatMap() transforms an element into another stream/collection and flattens the nested result.

Example:

students.stream()
        .flatMap(
            student ->
                student.getCourses().stream()
        );
36

What is Optional?

Optional represents the possible absence of a value.

Optional<User> user =
    repository.findById(id);

Example:

User user = repository
    .findById(id)
    .orElseThrow(
        () -> new UserNotFoundException()
    );

It can make absence explicit instead of returning null in certain APIs.

37

What does reduce() do?

reduce() combines stream elements into a single result.

Example:

int total =
    numbers.stream()
           .reduce(
               0,
               Integer::sum
           );

Possible uses include:

  • totals
  • multiplication
  • minimum/maximum
  • combining values
38

What are method references?

Method references provide shorter syntax when a lambda simply invokes an existing method.

Instead of:

users.forEach(
    user -> System.out.println(user)
);

write:

users.forEach(System.out::println);

Another example:

.map(User::getName)
39

When should parallel streams be avoided?

Do not automatically replace:

stream()

with:

parallelStream()

Parallel streams can hurt performance when:

  • dataset is small
  • tasks are cheap
  • operations block on I/O
  • ordering is important
  • shared mutable state exists
  • common-pool contention matters

Measure performance before using them.

Level 4

Multithreading, Concurrency & JVM

10 Questions
40

Process vs thread?

A process is an executing program with its own process resources.

Threads are execution units inside a process.

Threads usually share resources such as heap memory within the process.

41

How can you create concurrent tasks in Java?

Historically:

new Thread(() -> {
    // work
}).start();

Production code often uses executors:

ExecutorService executor =
    Executors.newFixedThreadPool(10);

Modern Java also provides virtual threads, which are useful for many blocking I/O-oriented workloads.

42

synchronized vs volatile ?

volatile provides visibility guarantees for a variable between threads.

private volatile boolean running;

It does not make compound operations such as:

count++;

atomic.

synchronized provides mutual exclusion and visibility around a critical section.

43

What is a race condition?

A race condition occurs when multiple threads access shared mutable state and the outcome depends on timing.

Example:

count++;

is not a single atomic operation.

Conceptually:

read
increment
write

Two threads can interfere with each other.

44

What is deadlock?

Deadlock can occur when threads wait forever for locks held by each other.

Example:

Thread A:
owns Lock 1
waits for Lock 2

Thread B:
owns Lock 2
waits for Lock 1

Common prevention techniques include consistent lock ordering and minimizing nested locks.

45

What is ExecutorService?

ExecutorService separates task submission from thread management.

ExecutorService executor =
    Executors.newFixedThreadPool(5);

executor.submit(() -> {
    processOrder();
});

It is generally preferable to manually creating unbounded numbers of Threads.

46

What is CompletableFuture?

CompletableFuture helps compose asynchronous operations.

CompletableFuture
    .supplyAsync(this::getUser)
    .thenApply(this::enrichUser)
    .thenAccept(System.out::println);

It supports chaining, combining tasks and error handling.

47

Stack vs Heap memory?

Conceptually:

Stack

Contains per-thread call frames, local variables and execution state.

Heap

Stores objects and arrays shared through references.

Example:

User user = new User();

The local reference is associated with the current method frame while the User object itself resides on the heap.

48

What is garbage collection?

Garbage collection automatically identifies objects that are no longer reachable and reclaims associated heap memory.

Developers do not manually call free() as in some lower-level languages.

But Java can still suffer memory problems when an application unintentionally retains references to objects.

49

Can Java have memory leaks?

Yes.

A Java memory leak generally means objects are still reachable but are no longer useful.

Example:

static List<Object> cache =
    new ArrayList<>();

If objects are continually added and never removed, they cannot be garbage collected.

Typical causes include:

  • unbounded caches
  • static collections
  • listener registrations
  • ThreadLocal misuse
  • unreleased resources
Level 5

JDBC & Servlets

8 Questions
50

What is JDBC?

JDBC is Java’s standard database connectivity API.

Typical flow:

Java
 ↓
JDBC API
 ↓
JDBC Driver
 ↓
Database

Example:

Connection connection =
    DriverManager.getConnection(url, user, password);
51

Statement vs PreparedStatement?

Statement can execute SQL strings directly.

PreparedStatement supports parameterized SQL.

PreparedStatement ps =
    connection.prepareStatement(
        "SELECT * FROM users WHERE email = ?"
    );

ps.setString(1, email);

Prepared statements improve parameter handling and are a core defense against SQL injection.

52

What is connection pooling?

Opening a new database connection for every request is expensive.

A connection pool maintains reusable connections.

Typical architecture:

Spring Boot
   ↓
Connection Pool
   ↓
Database

Spring Boot commonly uses HikariCP as a connection-pool implementation.

53

What is a Servlet?

A Servlet is a Java server-side component designed to handle HTTP requests and responses.

Example concept:

@WebServlet("/users")
public class UserServlet
       extends HttpServlet {

    protected void doGet(
        HttpServletRequest request,
        HttpServletResponse response
    ) {

    }
}

Spring MVC abstracts much of the direct Servlet work developers previously wrote manually.

54

What is the Servlet lifecycle?

Important lifecycle methods include:

init()
service()
destroy()

For HTTP servlets, service() dispatches requests to methods such as:

doGet()
doPost()
doPut()
doDelete()
55

GET vs POST?

GET normally retrieves a resource.

GET /products/10

POST commonly creates a resource or triggers processing.

POST /products

Request semantics should follow HTTP conventions rather than choosing methods arbitrarily.

56

Forward vs redirect?

Forward

The server internally transfers processing to another resource.

The browser generally does not make a new externally visible navigation request for the forwarded target.

Redirect

The server sends a redirect response and the browser makes another request.

Example:

response.sendRedirect("/login");
57

Session vs cookie?

A cookie is stored by the browser and sent according to cookie rules.

A server-side session stores user-specific state on the server, often associating the browser with that session using a session identifier cookie.

Never store plain sensitive passwords inside cookies.

Level 6

Spring Framework

6 Questions
58

What is the Spring Framework?

Spring is an application framework and ecosystem widely used for enterprise Java development.

Important concepts include:

  • IoC
  • dependency injection
  • Spring MVC
  • transaction management
  • data access
  • security
  • testing

Spring Boot builds on the Spring ecosystem to simplify application setup and production configuration.

59

What is IoC?

IoC stands for Inversion of Control.

Instead of application code creating every dependency manually:

PaymentService service =
    new PaymentServiceImpl();

the Spring container creates and manages application objects.

These managed objects are called beans.

60

What is Dependency Injection?

Dependency Injection provides an object’s dependencies from outside the object.

Example:

@Service
public class OrderService {

    private final PaymentService paymentService;

    public OrderService(
        PaymentService paymentService
    ) {
        this.paymentService = paymentService;
    }
}

Spring injects the appropriate PaymentService implementation.

61

Constructor injection vs field injection?

Constructor injection is generally preferred.

private final UserRepository repository;

public UserService(
    UserRepository repository
) {
    this.repository = repository;
}

Benefits include:

  • explicit dependencies
  • easier unit testing
  • immutable dependency references
  • easier construction outside Spring
62

@Component , @Service , @Repository and @Controller ?

All can register classes as Spring-managed components, but they communicate different roles.

@Component  → generic Spring component
@Service    → service/business layer
@Repository → persistence layer
@Controller → MVC controller

@RestController is used for REST-oriented controllers.

63

What is bean scope?

The default Spring bean scope is usually:

singleton

One bean instance exists per Spring application context.

Other scopes include:

prototype
request
session

depending on application type.

Level 7

Spring Boot & Spring MVC

8 Questions
64

Spring vs Spring Boot?

Spring provides the underlying application framework.

Spring Boot simplifies creation of Spring applications through features such as:

  • auto-configuration
  • starter dependencies
  • embedded web servers
  • production-oriented configuration
  • Actuator support

Spring Boot is not a replacement for Spring; it builds on it.

65

What does @SpringBootApplication do?

It combines several major Spring Boot annotations conceptually including:

@Configuration
@EnableAutoConfiguration
@ComponentScan

Example:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(
            Application.class,
            args
        );
    }
}
66

What is Spring Boot auto-configuration?

Spring Boot examines:

  • available dependencies
  • existing beans
  • configuration properties

and conditionally configures common infrastructure.

For example, adding appropriate web dependencies can cause Spring Boot to configure the MVC web application infrastructure automatically.

You can still override configuration when necessary.

67

What is a REST controller?

Example:

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping
    public List<UserDto> getUsers() {
        return userService.getUsers();
    }
}

@RestController is effectively:

@Controller
+
@ResponseBody

for handler methods by default.

68

@PathVariable vs @RequestParam ?

Path variable:

GET /users/10
@GetMapping("/{id}")
public User getUser(
    @PathVariable Long id
) {
}

Request parameter:

GET /users?page=2&size=20
@RequestParam int page

Use path variables for resource identity and query parameters for filtering, pagination and optional modifiers.

69

What is @RequestBody ?

It maps an HTTP request body to a Java object.

@PostMapping
public UserDto create(
    @RequestBody CreateUserRequest request
) {
}

JSON:

{
  "name": "Rahul",
  "email": "rahul@example.com"
}

Spring commonly uses Jackson to perform JSON serialization/deserialization.

70

How do you validate incoming requests?

Use Jakarta Bean Validation annotations.

Example:

public class CreateUserRequest {

    @NotBlank
    private String name;

    @Email
    @NotBlank
    private String email;
}

Controller:

public ResponseEntity<?> create(
    @Valid @RequestBody CreateUserRequest request
) {
}

Validation must still be backed by appropriate business rules and database constraints.

71

How do you implement global exception handling?

Use:

@RestControllerAdvice

with:

@ExceptionHandler

Example:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(
        UserNotFoundException.class
    )
    public ResponseEntity<?> handleNotFound(
        UserNotFoundException ex
    ) {

        return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(
                Map.of(
                    "message",
                    ex.getMessage()
                )
            );
    }
}

This keeps controllers cleaner and error responses consistent.

Level 8

Hibernate & JPA

9 Questions
72

What is ORM?

ORM means Object Relational Mapping.

It maps objects to relational database structures.

Example:

Java Class → Table
Object     → Row
Field      → Column

Hibernate is a popular Java ORM implementation.

73

JPA vs Hibernate?

JPA/Jakarta Persistence defines a standard persistence API/specification.

Hibernate is one of its major implementations.

Think:

JPA → contract/API
Hibernate → implementation/provider

This distinction is frequently misunderstood by beginners.

74

What does @Entity do?

It marks a class as a persistent JPA entity.

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String name;
}

An entity typically maps to a database table.

75

What are JPA entity states?

Common states are:

Transient
Managed/Persistent
Detached
Removed

Transient

New object not associated with persistence context.

Managed

Tracked by persistence context.

Detached

Was managed but no longer tracked.

Removed

Scheduled for deletion.

76

Lazy loading vs eager loading?

Lazy loading postpones retrieval of related data until it is needed.

Eager loading requests related data immediately.

Blindly making every association eager can create extremely heavy queries and memory usage.

Likewise, careless lazy loading can cause extra queries.

Fetch strategy should follow the application’s access pattern.

77

What is the N+1 query problem?

Imagine retrieving 100 orders:

SELECT * FROM orders;

and then one additional query runs for each order’s customer.

1 initial query
+
100 related queries
=
101 queries

This is the N+1 problem.

Possible solutions include:

  • fetch joins
  • entity graphs
  • projections
  • carefully designed queries
  • batching

depending on the scenario.

78

What is the persistence context?

The persistence context tracks managed entities.

Within the same persistence context:

User a = entityManager.find(User.class, 1L);
User b = entityManager.find(User.class, 1L);

the provider can return the same managed entity instance.

It also enables features such as dirty checking.

79

What is dirty checking?

For managed entities, Hibernate can detect property changes and generate an update when the transaction is flushed/committed.

Example:

User user =
    repository.findById(id).orElseThrow();

user.setName("Aman");

Inside an appropriate transactional context, an explicit save() may not always be necessary merely to update an already managed entity.

80

What does @Transactional do?

It defines transactional boundaries.

Example:

@Transactional
public void placeOrder(...) {

    saveOrder();

    updateStock();

    savePayment();
}

If an appropriate failure occurs, the transaction can roll back so related operations do not leave the database in an inconsistent partial state.

A strong interview answer should also mention that Spring commonly applies transaction behavior through proxies and that self-invocation can therefore surprise developers.

Level 9

Database & SQL

4 Questions
81

INNER JOIN vs LEFT JOIN?

INNER JOIN

Returns records where the join condition matches in both sides.

LEFT JOIN

Returns every row from the left table plus matching rows from the right.

Example:

SELECT u.name, o.id
FROM users u
LEFT JOIN orders o
ON u.id = o.user_id;

Users without orders still appear.

82

What is an index?

A database index helps locate records efficiently for supported query patterns.

Example:

CREATE INDEX idx_users_email
ON users(email);

Indexes improve many reads but add storage and write-maintenance cost.

Do not create an index on every column without understanding queries.

83

What is a transaction and what does ACID mean?

ACID means:

Atomicity

All or nothing.

Consistency

Database invariants remain valid.

Isolation

Concurrent transactions interact according to defined isolation behavior.

Durability

Committed changes survive expected failures.

Order/payment/inventory workflows often make transactional behavior important.

84

What are transaction isolation levels?

Common SQL isolation levels include:

READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE

Higher isolation can prevent more anomalies but often reduces concurrency.

The correct choice depends on application requirements and database implementation.

Level 10

Spring Security & JWT

4 Questions
85

Authentication vs authorization?

Authentication answers:

> Who are you? Authorization answers:

> What are you allowed to do? Example:

User logs in
        ↓
Authentication

User accesses /admin
        ↓
Authorization
86

Explain a JWT authentication flow.

Typical flow:

1. Client sends credentials
2. Server verifies them
3. Server issues token/session credentials
4. Client sends authentication credential
5. Security filter validates it
6. Security context identifies user
7. Authorization rules are evaluated

A JWT commonly contains:

header.payload.signature

JWT payloads are normally encoded rather than automatically encrypted, so secrets should not simply be placed inside them.

87

What is Spring Security’s filter chain?

Security processing occurs before a controller executes.

Conceptually:

HTTP Request
    ↓
Security Filters
    ↓
Authentication
    ↓
Authorization
    ↓
Controller

A custom JWT authentication filter may inspect a bearer token and establish authentication for valid requests.

88

How do you secure passwords?

Never store plain passwords.

Use an adaptive password-hashing algorithm.

In Spring applications, BCrypt is commonly used:

PasswordEncoder encoder =
    new BCryptPasswordEncoder();

String hash =
    encoder.encode(password);

Then verify using:

encoder.matches(rawPassword, hash);
Level 11

HTML, CSS, JavaScript & Thymeleaf

3 Questions
89

Why must a Java full-stack developer understand HTML, CSS and JavaScript?

Even when using Thymeleaf or Next.js, the browser ultimately works with:

HTML
CSS
JavaScript
HTTP
DOM

A full-stack developer should understand:

  • semantic HTML
  • forms
  • accessibility
  • CSS layout
  • Flexbox/Grid
  • responsive design
  • JavaScript events
  • promises
  • fetch
  • browser storage
  • cookies
  • CORS

Framework knowledge without browser fundamentals creates debugging difficulties.

90

What is Thymeleaf?

Thymeleaf is a server-side Java template engine frequently integrated with Spring MVC.

Example controller:

@GetMapping("/users")
public String users(Model model) {

    model.addAttribute(
        "users",
        userService.findAll()
    );

    return "users";
}

Template:

<tr th:each="user : ${users}">
    <td th:text="${user.name}"></td>
</tr>

The Spring Boot application renders HTML on the server.

91

Thymeleaf vs Next.js?

With Thymeleaf:

Browser
   ↓
Spring MVC
   ↓
Service
   ↓
Database
   ↓
Server renders HTML

With a separate Next.js frontend:

Next.js
   ↓
HTTP API
   ↓
Spring Boot
   ↓
Service
   ↓
Database

Thymeleaf is excellent for many traditional server-rendered applications, internal systems and simpler integrated architectures.

Next.js is useful when you need a richer React-based frontend and want independent frontend/backend architecture.

Level 12

Next.js Frontend

4 Questions
92

What is Next.js and how can it work with Spring Boot?

Next.js is a React framework.

Spring Boot can expose APIs such as:

GET /api/products
POST /api/orders
GET /api/users/10

Next.js consumes them:

const response =
    await fetch(
        "https://api.example.com/api/products"
    );

const products =
    await response.json();

Architecture:

Next.js
   ↓
Spring Boot REST API
   ↓
Service Layer
   ↓
JPA/Hibernate
   ↓
Database
93

Server Component vs Client Component in modern Next.js?

In the App Router, pages and layouts are Server Components by default.

Server Components are appropriate for many data-fetching and non-interactive UI tasks.

A Client Component is required when you need features such as:

  • useState
  • event handlers
  • useEffect
  • browser APIs
  • interactive client-side behavior

Example:

"use client";

import { useState } from "react";

export default function Counter() {

    const [count, setCount] =
        useState(0);

    return (
        <button
          onClick={() =>
            setCount(count + 1)
          }
        >
          {count}
        </button>
    );
}

Current Next.js documentation explicitly describes this Server/Client split and recommends keeping client-only boundaries where interactivity is actually required.

94

What is hydration?

The server can initially send HTML to the browser.

React then attaches the necessary client-side behavior to interactive Client Components.

This process is called hydration.

Conceptually:

Server HTML
    ↓
Browser displays page
    ↓
Client JavaScript loads
    ↓
React hydrates interactive parts

Current Next.js documentation describes hydration as React attaching event handlers to make initially rendered HTML interactive.

95

Explain routing in the Next.js App Router.

Next.js uses file-system routing.

Example:

app/
 ├── page.tsx
 ├── products/
 │     ├── page.tsx
 │     └── [id]/
 │          └── page.tsx
 └── dashboard/
       └── page.tsx

Results:

/
/products
/products/10
/dashboard

The modern App Router is built around Server Components and supports layouts, nested routes, loading/error handling and related React features.

Level 13

Testing

1 Questions
96

How would you test a Spring Boot application?

Use different test levels.

Unit testing

JUnit
Mockito

Example:

@Test
void shouldCreateOrder() {

    when(repository.save(any()))
        .thenReturn(order);

    Order result =
        service.createOrder(request);

    assertNotNull(result);
}

Controller testing

Use tools such as:

MockMvc
WebTestClient

depending on the application stack.

Integration testing

Test actual Spring configuration and application integrations.

Database integration testing

Testcontainers can start real database containers for more realistic tests.

Do not replace every dependency with mocks automatically.

Level 14

Microservices, Deployment & System Design

4 Questions
97

Monolith vs microservices?

Monolith

One deployable application.

Possible advantages:

  • simpler development
  • easier local setup
  • easier transactions
  • simpler deployment

Microservices

Application is divided into independently deployable services.

Example:

User Service
Order Service
Payment Service
Inventory Service
Notification Service

Possible benefits:

  • independent deployment
  • independent scaling
  • team autonomy
  • stronger domain boundaries

But microservices introduce:

  • network failures
  • distributed transactions
  • observability requirements
  • deployment complexity
  • data-consistency complexity

Do not choose microservices simply because the application may become large.

98

What is Docker and why use it with Spring Boot?

Docker packages an application and its runtime dependencies into an image.

Example:

FROM eclipse-temurin:21-jre

COPY target/app.jar app.jar

ENTRYPOINT [
  "java",
  "-jar",
  "/app.jar"
]

Deployment can then look like:

Spring Boot Container
PostgreSQL Container
Redis Container
Next.js Container

Containers improve environment consistency and deployment portability.

99

Your Spring Boot API becomes slow under production traffic. How do you debug it?

Do not immediately increase server size.

Investigate systematically.

Step 1 — Measure API latency

Check:

p50
p95
p99
error rate
requests/sec

Step 2 — Check database behavior

Look for:

slow SQL
missing indexes
N+1 queries
large result sets
long transactions
connection-pool exhaustion

Step 3 — Check JVM

Investigate:

CPU
heap
GC activity
thread count
blocked threads
thread dumps
memory usage

Step 4 — Check application code

Look for:

synchronized bottlenecks
blocking external calls
heavy object creation
slow serialization
unbounded processing

Step 5 — Check external dependencies

Examples:

payment gateway
email API
third-party API
Redis
database
message broker

Step 6 — Optimize architecture

Possible improvements:

indexes
pagination
caching
Redis
asynchronous processing
connection-pool tuning
batch processing
horizontal scaling
load balancing
CDN
queues

The strongest answer is:

> Measure first, identify the bottleneck, then optimize. Not:

> Add more RAM.

100

SYSTEM DESIGN: Design a production e-commerce platform using Java Full Stack.

This is the type of question that distinguishes a developer who knows Spring annotations from a developer who understands software architecture.

Frontend

Use Next.js for a rich customer application.

Home
Products
Categories
Search
Product Detail
Cart
Checkout
Orders
Account
Admin

Thymeleaf could alternatively be used for an integrated server-rendered admin portal or simpler application.

Frontend architecture

Next.js
    |
    | HTTPS
    ↓
Spring Boot API

Next.js Server Components can be used where server-side data rendering is appropriate, while Client Components are introduced for interactive behavior. Modern Next.js specifically encourages this server/client separation.

Backend architecture

Controller
    ↓
Service
    ↓
Repository
    ↓
JPA / Hibernate
    ↓
Database

Example packages:

controller/
service/
repository/
entity/
dto/
mapper/
exception/
security/
configuration/

API endpoints

Authentication

POST /api/auth/register
POST /api/auth/login
POST /api/auth/refresh
POST /api/auth/logout

Products

GET    /api/products
GET    /api/products/{id}
POST   /api/products
PATCH  /api/products/{id}
DELETE /api/products/{id}

Orders

POST /api/orders
GET  /api/orders/{id}
GET  /api/users/me/orders

Entity design

Possible tables:

users
roles
products
categories
inventory
orders
order_items
payments
addresses
reviews
coupons

DTO layer

Do not expose JPA entities blindly.

Use DTOs:

public record ProductResponse(
    Long id,
    String name,
    BigDecimal price
) {}

Benefits include:

  • controlling API structure
  • preventing accidental entity exposure
  • reducing serialization problems
  • separating persistence design from API design

Database

Use:

PostgreSQL
or
MySQL

depending on system requirements.

Important indexes could include:

CREATE UNIQUE INDEX
idx_user_email
ON users(email);

CREATE INDEX
idx_product_category
ON products(category_id);

CREATE INDEX
idx_order_user_created
ON orders(user_id, created_at);

Indexes should reflect actual query patterns.

Product listing

Never return hundreds of thousands of products at once.

Use:

pagination
filtering
sorting
search

Example:

GET /api/products?page=0&size=20&category=5

Authentication

Possible architecture:

Browser
    ↓
Login
    ↓
Spring Security
    ↓
Authentication
    ↓
Access credential/session

Use:

  • secure password hashing
  • HTTPS
  • secure cookies or properly designed authorization headers
  • token/session expiration
  • role-based authorization
  • refresh/session rotation where required

Authorization

For example:

CUSTOMER
SELLER
ADMIN

A CUSTOMER must not be able to execute:

DELETE /api/admin/products/10

simply by manually calling the endpoint.

Backend authorization is mandatory.

Inventory concurrency

Suppose stock is:

1 item

Two users purchase simultaneously.

Bad logic:

read stock = 1

request A → purchase
request B → purchase

Both may succeed.

Better approaches can include atomic conditional updates, locking or another concurrency strategy suitable for the database and business requirements.

Example conceptual SQL:

UPDATE inventory
SET quantity = quantity - 1
WHERE product_id = ?
AND quantity > 0;

Then inspect affected rows.

Payment architecture

Never trust:

Frontend says payment successful.

Correct conceptual flow:

Browser
  ↓
Payment Provider
  ↓
Provider webhook/callback
  ↓
Spring Boot
  ↓
Verify signature/event
  ↓
Update payment/order

Server-side verification is essential.

Transactions

Order creation might involve:

Create order
Reserve inventory
Create payment record

Use appropriate transactional boundaries.

Do not keep a database transaction open while waiting several seconds for an external payment provider.

Redis

Possible uses:

product caching
sessions
rate limiting
OTP
temporary tokens
distributed locks where justified

Do not cache everything by default.

Queue

Secondary operations should not unnecessarily delay the checkout response.

Example:

Order Created
     ↓
Message Queue
     ↓
---------------------
|         |         |
Email   Invoice  Notification
Worker  Worker    Worker

Possible technologies:

Kafka
RabbitMQ
cloud queues

depending on requirements.

Search

Initially:

database search

At larger scale, consider dedicated search capability such as:

Elasticsearch/OpenSearch

when justified by search requirements.

File storage

Do not store large product images directly inside ordinary database rows unless there is a specific reason.

Possible architecture:

Browser
   ↓
Object Storage
   ↓
CDN

Store references/URLs in the product data.

Performance

Consider:

database indexes
pagination
connection pooling
Redis caching
CDN
lazy image loading
Next.js code splitting
server rendering
gzip/Brotli
query optimization
async/background jobs

Observability

Monitor:

request rate
error rate
API latency
p95/p99
CPU
memory
heap
GC
DB latency
connection pools
slow queries
queue lag
payment failures
authentication failures

Use structured logs and distributed tracing when architecture requires it.

Deployment architecture

A more mature architecture may look like:

                   CDN
                    |
                 Next.js
                    |
              Load Balancer
                    |
        -------------------------
        |           |           |
   Spring Boot  Spring Boot  Spring Boot
        |           |           |
        ---------- Redis --------
                    |
              PostgreSQL
                    |
            Message Broker
                    |
      -------------------------
      |           |           |
    Email       Invoice    Notification
    Worker      Worker        Worker

If the system grows

You do not immediately rewrite everything as microservices.

Start with a well-structured modular application.

Extract services when justified by factors such as:

independent scaling
team ownership
different release cycles
clear domain boundaries
resource isolation

Potential future services:

Auth Service
Product Service
Order Service
Inventory Service
Payment Service
Notification Service
Bonus

20 Project Questions Interviewers May Ask

Students should prepare these even after learning the 100 questions.

1. Explain your Java project architecture from browser to database.

2. Why did you choose Spring Boot?

3. Why did you choose Hibernate instead of writing SQL everywhere?

4. Where did you use transactions?

5. How did you implement authentication?

6. How did you implement authorization?

7. Why did you create a service layer?

8. Why shouldn’t controllers directly access repositories everywhere?

9. What was the most difficult bug in your project?

10. How did you solve an N+1 problem?

11. Which database indexes did you create and why?

12. How does your application handle two users updating the same data?

13. What happens when the database becomes unavailable?

14. What happens if an external API takes 30 seconds to respond?

15. How are passwords stored?

16. How are production secrets stored?

17. How do you deploy the application?

18. How would you support ten times more users?

19. What would you change if you rebuilt the project today?

20. Show me one feature that demonstrates your full-stack skills from frontend to database.

Roadmap

Recommended Interview Learning Order

Students should not study Spring Boot before understanding Java itself.

Use this sequence.

Stage 1 — Core Java

Syntax
OOP
Classes
Objects
Inheritance
Interfaces
Exceptions
Strings
Collections
Generics

Stage 2 — Modern Java

Lambda
Functional interfaces
Streams
Optional
Method references
Records
Modern Java features

Stage 3 — Advanced Java

Threads
Concurrency
ExecutorService
CompletableFuture
JVM
Heap
Stack
Garbage Collection
Memory problems

Stage 4 — Database

SQL
joins
indexes
transactions
normalization
JDBC
connection pooling

Stage 5 — Traditional Java Web Fundamentals

HTTP
Servlet
Request
Response
Session
Cookie
Filter
JSP fundamentals
MVC

Even if the student will ultimately use Spring Boot, Servlet knowledge explains what Spring MVC is abstracting.

Stage 6 — Spring

IoC
DI
Beans
Component scanning
Configuration
Spring MVC

Stage 7 — Spring Boot

Auto configuration
REST controllers
Configuration
Validation
Exception handling
Profiles
Actuator

Stage 8 — Hibernate/JPA

Entities
Relationships
Persistence Context
Lazy/Eager Loading
N+1
Transactions
JPQL
Pagination
Projections
Optimistic locking

Stage 9 — Security

Spring Security
Authentication
Authorization
JWT/session
Password hashing
CORS
CSRF
Roles
Permissions

Stage 10 — Frontend Fundamentals

HTML5
CSS
Flexbox
Grid
Responsive design
JavaScript
DOM
Promises
fetch
async/await
HTTP
cookies
CORS

Stage 11 — Thymeleaf

Templates
Model
Forms
Validation
Fragments
Layouts
Spring integration

Stage 12 — React + Next.js

Components
Props
State
Hooks
Rendering
App Router
Layouts
Server Components
Client Components
Dynamic Routes
Data Fetching
Caching
Forms
Authentication
Spring Boot API integration

Modern Next.js interviews now particularly emphasize App Router, Server Components, server/client boundaries, caching and rendering choices, rather than only older Pages Router concepts.

Stage 13 — Testing

JUnit
Mockito
Spring Boot Test
MockMvc
Integration Tests
Testcontainers
Frontend testing

Stage 14 — Production Engineering

Git
Maven/Gradle
Linux basics
Docker
CI/CD
logging
monitoring
Redis
queues
microservices
performance
system design

Avoid

What Students Must Not Do in an Interview

Do not memorize answers such as:

> Spring Boot is a framework used to make Java applications. That answer is technically weak.

A much better response is:

> We used Spring Boot for our REST backend because it simplified dependency configuration, embedded server setup and Spring integration. Our controllers handled HTTP requests, services contained business logic, repositories used Spring Data JPA, and PostgreSQL stored the data. Then continue with an actual feature from the project.

Formula

The Ideal Interview Answer Formula

For almost every technical question, use:

1. What is it?

Give the definition.

2. Why do we need it?

Explain the problem it solves.

3. How does it work?

Explain briefly.

4. Give an example.

Show code or architecture.

5. Mention a real project use.

Example:

> In my e-commerce project, I used @Transactional while placing an order because inventory and order creation had to remain consistent.

6. Mention a problem or trade-off.

Example:

> I would not make every relationship EAGER because that could retrieve much more data than required and create performance problems. That final point frequently separates a beginner from an industry-ready candidate.

Goal

Final Skill Target

A Java Full Stack student should eventually be able to explain this entire request flow without confusion:

User
 ↓
Browser / Next.js / Thymeleaf
 ↓
HTTP Request
 ↓
Spring Security Filter Chain
 ↓
Spring MVC Controller
 ↓
Validation
 ↓
Service Layer
 ↓
@Transactional
 ↓
Repository
 ↓
JPA
 ↓
Hibernate
 ↓
Connection Pool
 ↓
JDBC
 ↓
PostgreSQL / MySQL
 ↓
Response DTO
 ↓
JSON / Rendered HTML
 ↓
Browser

If the student can explain every layer in this flow, what can fail at each layer, and how they would debug it, they are approaching genuine Java full-stack interview readiness rather than merely completing a Spring Boot tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *