Skip to main content

Chapter 8: "What is...?" — The 40 Most Asked Interview Concepts

Objective

This chapter gathers questions like "What is a DTO?", "What is MVC?" — the vocabulary and concept questions that every interviewer asks first. If you can only review one chapter, this is the one.


1. What is a DTO (Data Transfer Object)?​

A DTO is a simple object used to transport data between application layers, without business logic.

Why not use the Entity directly?​

EntityDTO
Mapped to the databaseJust a data container
Contains JPA relations (lazy loading)Contains only necessary fields
Can expose sensitive data (password, role)We choose exactly what to expose
Changing the DB = changing the APIAPI independent of the DB

Concrete example​

// ENTITY (linked to the DB)
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
private String email;
private String password; // ← should NEVER be exposed!
private String role;

@OneToMany(mappedBy = "user")
private List<Order> orders; // ← lazy loading, can cause N+1
}

// DTO (what the client receives)
public record UserDTO(
Long id,
String name,
String email
// no password, no role, no orders
) {}

// Conversion in the Service
@Service
public class UserService {
public UserDTO toDto(User user) {
return new UserDTO(user.getId(), user.getName(), user.getEmail());
}
}
Interview phrase

"A DTO is a simple object used to transfer data between layers. I use DTOs to avoid exposing JPA entities in the API — this prevents leaking sensitive fields like passwords and avoids lazy-loading issues."


2. What is MVC (Model-View-Controller)?​

An architectural pattern that separates the application into 3 responsibilities:

ComponentRoleIn Spring Boot
ModelData and business logicEntity, Service, Repository
ViewDisplay (what the user sees)JSON (REST API) or Thymeleaf (HTML)
ControllerThe orchestrator that receives requests and coordinates@Controller or @RestController

In Spring Boot REST, the "View" is the JSON​

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

@GetMapping("/{id}")
public UserDTO getUser(@PathVariable Long id) {
return userService.findById(id); // Model → converted to JSON (View)
}
}
Interview phrase

"MVC separates the application into Model (data/logic), View (presentation), and Controller (request handling). In a REST API, the View is the JSON response automatically serialized by Jackson."


3. What is a REST API?​

API = Application Programming Interface (interface for two programs to communicate)

REST = Representational State Transfer (architectural style for web APIs)

The 6 REST rules​

RuleMeaning
Client-ServerThe client and server are separate
StatelessEach request contains all necessary information
CacheResponses can be cached
Uniform InterfaceConsistent URLs, standard HTTP methods
Layered SystemThe client doesn't know if it's talking to the final server
Code on Demand (optional)The server can send executable code

HTTP methods​

MethodActionExampleReturn code
GETReadGET /api/users/1200 OK
POSTCreatePOST /api/users201 Created
PUTReplace entirelyPUT /api/users/1200 OK
PATCHModify partiallyPATCH /api/users/1200 OK
DELETEDeleteDELETE /api/users/1204 No Content
Interview phrase

"REST is an architectural style for web APIs. It uses HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations on resources identified by URLs. It's stateless — each request is independent."


4. What is CRUD?​

The 4 basic operations on data:

LetterOperationSQLHTTPSpring Data
CCreateINSERTPOSTsave()
RReadSELECTGETfindById(), findAll()
UUpdateUPDATEPUT/PATCHsave()
DDeleteDELETEDELETEdeleteById()

5. What is a POJO?​

POJO = Plain Old Java Object

A simple Java object, without any dependency on a framework:

// This is a POJO — just fields, getters, setters
public class User {
private String name;
private String email;

public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}

A Java Bean is a POJO that follows conventions: no-argument constructor, getters/setters, serializable.

A Spring Bean is an object managed by the Spring container (can be a POJO annotated @Component, @Service, etc.).


6. What is a Spring Bean?​

An object created and managed by the Spring container (ApplicationContext).

// This is a Spring Bean — Spring creates and manages it
@Service
public class UserService {
// Spring automatically instantiates it at startup
// Spring injects it where needed
// Spring manages its lifecycle
}

// This is NOT a Bean — created manually
UserService service = new UserService();

How to create a Bean?​

MethodExample
Stereotype annotations@Component, @Service, @Repository, @Controller
@Bean in @ConfigurationMethod that returns an object
@ImportImport a configuration class
Interview phrase

"A Spring Bean is an object managed by the Spring IoC container. Spring creates it, injects its dependencies, and manages its lifecycle. By default, beans are singletons."


7. What is IoC (Inversion of Control)?​

Without IoC: the code creates its own dependencies.

With IoC: the container creates the dependencies and provides them to the code.

// WITHOUT IoC — the code controls creation
public class OrderService {
private UserRepository repo = new UserRepository(); // Creates itself
private EmailService email = new EmailService(); // Creates itself
}

// WITH IoC — Spring controls creation
@Service
public class OrderService {
private final UserRepository repo; // Provided by Spring
private final EmailService email; // Provided by Spring

public OrderService(UserRepository repo, EmailService email) {
this.repo = repo; // Injected by Spring
this.email = email; // Injected by Spring
}
}

Dependency Injection (DI) is the concrete mechanism that implements IoC.


8. What is ORM and JPA and Hibernate?​

TermDefinitionAnalogy
ORMObject-Relational Mapping — technique that maps Java objects to SQL tablesThe translator between Java and SQL
JPAJakarta Persistence API — the specification (interface) of ORM in JavaThe contract / the standard
HibernateThe most popular implementation of JPAThe software that does the work
JPA (specification)    →  Hibernate (implementation)
↓ ↓
"here's how it should "here's the code that
work" makes it work"
// JPA Annotations (standard)
@Entity // JPA says: "this class is an entity"
@Table(name = "users") // JPA says: "mapped to the users table"
public class User {
@Id // JPA says: "this is the primary key"
@GeneratedValue // JPA says: "auto-incremented"
private Long id;

@Column(name = "full_name") // JPA says: "mapped to this column"
private String name;
}

// Hibernate does the work behind: generates SQL queries,
// manages cache, lazy loading, transactions...
Interview phrase

"JPA is the specification that defines how Java objects map to database tables. Hibernate is the most popular implementation of JPA. I use JPA annotations so my code isn't tied to Hibernate specifically."


9. What is Maven?​

A build and dependency management tool for Java projects.

FeatureDescription
DependenciesAutomatically downloads libraries (from Maven Central)
BuildCompiles, tests, packages the application (.jar)
Lifecyclemvn clean → mvn compile → mvn test → mvn package
pom.xmlThe project's configuration file
<!-- pom.xml — the heart of Maven -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

Maven vs Gradle: Maven uses XML (verbose but standard), Gradle uses Groovy/Kotlin (more concise but learning curve).


10. What is Tomcat?​

A web server / servlet container that runs Java applications.

Spring Boot embeds Tomcat directly:

java -jar myapp.jar
↓
┌──────────────────────┐
│ Spring Boot │
│ ┌──────────────────┐ │
│ │ Embedded Tomcat │ │ ← listens on port 8080
│ │ (embedded) │ │
│ └──────────────────┘ │
│ ┌──────────────────┐ │
│ │ Your code │ │
│ │ Controllers │ │
│ │ Services │ │
│ └──────────────────┘ │
└──────────────────────┘

No need to install Tomcat separately — Spring Boot embeds it in the .jar.


11. What is JSON?​

JSON = JavaScript Object Notation — a lightweight and readable data format.

{
"id": 1,
"name": "John Doe",
"email": "john@mail.com",
"active": true,
"roles": ["USER", "ADMIN"],
"address": {
"city": "Montreal",
"postalCode": "H2X 1Y4"
}
}

In Spring Boot, Jackson automatically converts Java objects to JSON and vice versa:

// Java → JSON (serialization)
@GetMapping("/users/1")
public UserDTO getUser() {
return new UserDTO(1L, "John", "john@mail.com");
// Jackson automatically transforms to JSON
}

// JSON → Java (deserialization)
@PostMapping("/users")
public void create(@RequestBody UserDTO dto) {
// Jackson transforms the JSON body into a UserDTO object
}

12. What is Postman and Swagger?​

ToolRole
PostmanHTTP client to manually test REST APIs (send GET, POST, etc.)
Swagger / OpenAPIAutomatically generates an interactive documentation of the API

Swagger in Spring Boot:

<!-- Add to pom.xml -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>

Then, access http://localhost:8080/swagger-ui.html to test your endpoints directly from the browser.


13. What is Docker?​

Docker creates containers: isolated environments that contain your application + all its dependencies.

Without Docker:                With Docker:
"It works on my machine" "It works EVERYWHERE"

My PC: Container:
├── Java 17 ├── Java 17
├── Maven 3.9 ├── Maven 3.9
├── PostgreSQL 15 ├── App.jar
└── My App └── (everything included)
↕ Possible conflicts ↕ Isolated and portable
# Dockerfile for Spring Boot
FROM eclipse-temurin:17-jre
COPY target/app.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

14. What is CI/CD?​

TermMeaningWhen
CI — Continuous IntegrationAutomatically compile + test on each git pushOn each commit
CD — Continuous DeliveryAutomatically deploy to productionAfter tests

Tools: GitHub Actions, Jenkins, GitLab CI, CircleCI.


15. What is Git and GitHub?​

TermDefinition
GitVersion control tool — tracks code change history
GitHubWeb platform that hosts Git repositories + collaboration
git add .              # Stage changes
git commit -m "fix" # Record in local history
git push origin main # Push to GitHub
git pull # Fetch changes from others
git branch feature-x # Create a branch
git merge feature-x # Merge a branch

16. What is Layered Architecture?​

Golden Rule​

Each layer only communicates with the layer directly below it.

✅ Controller → Service → Repository → Database
❌ Controller → Repository (never directly!)
❌ Controller → Database (never directly!)
Interview phrase

"I follow a layered architecture: Controller handles HTTP, Service contains business logic, Repository handles data access. Each layer only talks to the layer directly below it. This separation makes the code testable and maintainable."


17. What is the Spring IoC Container (ApplicationContext)?​

The container that creates, configures, and assembles all Spring beans at startup:

Application startup:

1. @SpringBootApplication → starts the scan
2. Finds @Component, @Service, @Repository, @Controller
3. Creates instances (beans)
4. Resolves dependencies (@Autowired)
5. Injects dependencies
6. Calls @PostConstruct
7. ══════ Application ready ══════

18. What is @Autowired? What is dependency injection?​

3 ways to inject in Spring:

// ✅ 1. CONSTRUCTOR Injection (recommended)
@Service
public class OrderService {
private final UserRepository userRepo;
private final EmailService emailService;

public OrderService(UserRepository userRepo, EmailService emailService) {
this.userRepo = userRepo;
this.emailService = emailService;
}
}

// ⚠️ 2. SETTER Injection
@Service
public class OrderService {
private UserRepository userRepo;

@Autowired
public void setUserRepo(UserRepository userRepo) {
this.userRepo = userRepo;
}
}

// ❌ 3. FIELD Injection (discouraged)
@Service
public class OrderService {
@Autowired
private UserRepository userRepo;
}

Why is the constructor the best?​

CriterionConstructorSetterField
Immutability (final)✅❌❌
Testable without Spring✅⚠️❌
Mandatory dependencies✅❌❌
Detects circular dependencies✅❌❌
Interview phrase

"I prefer constructor injection because it allows final fields (immutability), makes dependencies explicit, and works without Spring for testing. Since Spring 4.3, @Autowired is optional on a single constructor."


19. What is a Java Record?​

A Record (Java 16+) is a special type for immutable objects that only contain data:

// Before (classic POJO — 30 lines)
public class UserDTO {
private final Long id;
private final String name;
private final String email;

public UserDTO(Long id, String name, String email) {
this.id = id; this.name = name; this.email = email;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
// + equals(), hashCode(), toString()...
}

// After (Record — 1 line!)
public record UserDTO(Long id, String name, String email) {}
// Automatically generates: constructor, getters, equals, hashCode, toString

Ideal for: DTOs, requests, responses, events.


20. What is Lombok?​

A library that automatically generates repetitive code (boilerplate) at compile time:

// Without Lombok — 50+ lines
public class User {
private Long id;
private String name;
private String email;
// constructor, getters, setters, equals, hashCode, toString...
}

// With Lombok — 5 lines
@Data // getters, setters, equals, hashCode, toString
@NoArgsConstructor // no-argument constructor
@AllArgsConstructor // all-arguments constructor
@Builder // Builder pattern
public class User {
private Long id;
private String name;
private String email;
}
Lombok AnnotationGenerates
@Getter / @SetterGetters and/or setters
@ToStringtoString()
@EqualsAndHashCodeequals() and hashCode()
@DataEverything above
@BuilderBuilder pattern
@NoArgsConstructorNo-argument constructor
@AllArgsConstructorAll-arguments constructor
@Slf4jLogger log

21. What is ResponseEntity?​

A Spring object that represents the complete HTTP response (status + headers + body):

// Without ResponseEntity — no control over status
@GetMapping("/{id}")
public UserDTO getUser(@PathVariable Long id) {
return userService.findById(id); // always 200 OK
}

// With ResponseEntity — full control
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok) // 200 OK
.orElse(ResponseEntity.notFound().build()); // 404 Not Found
}

@PostMapping
public ResponseEntity<UserDTO> create(@Valid @RequestBody CreateUserRequest req) {
UserDTO created = userService.create(req);
return ResponseEntity
.status(HttpStatus.CREATED) // 201 Created
.header("Location", "/api/users/" + created.id())
.body(created);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build(); // 204 No Content
}

22. What is @Valid and Bean Validation?​

// DTO with validation constraints
public record CreateUserRequest(
@NotBlank(message = "Name is required")
String name,

@Email(message = "Invalid email")
@NotBlank
String email,

@Size(min = 8, message = "Minimum 8 characters")
String password,

@Min(value = 18, message = "Minimum 18 years")
int age
) {}

// Controller — @Valid triggers validation
@PostMapping
public ResponseEntity<UserDTO> create(@Valid @RequestBody CreateUserRequest req) {
// If validation fails → 400 Bad Request automatically
return ResponseEntity.status(HttpStatus.CREATED)
.body(userService.create(req));
}
AnnotationChecks
@NotNullNot null
@NotBlankNot null, not empty, not just spaces
@NotEmptyNot null, not empty
@EmailValid email format
@Size(min, max)Size between min and max
@Min / @MaxNumeric min/max value
@Pattern(regexp)Matches a regular expression
@Past / @FutureDate in the past/future

23. What is application.properties / application.yml?​

The configuration file for the Spring Boot application:

# application.yml
server:
port: 8080

spring:
datasource:
url: jdbc:postgresql://localhost:5432/mydb
username: admin
password: secret
jpa:
hibernate:
ddl-auto: update
show-sql: true

app:
jwt:
secret: mySecretKey
expiration: 86400000

Access values with @Value:

@Value("${app.jwt.secret}")
private String jwtSecret;

@Value("${server.port}")
private int port;

24. What is Spring Security?​

The Spring security framework for authentication and authorization:

ConceptQuestionExample
Authentication"Who are you?"Login + password, JWT
Authorization"Do you have permission?"USER, ADMIN role

25. What is JWT (JSON Web Token)?​

A token sent in each request to prove the user's identity:

JWT = HEADER.PAYLOAD.SIGNATURE

eyJhbGciOiJIUzI1NiJ9. ← Header (algorithm)
eyJzdWIiOiJhbGljZSJ9. ← Payload (data: user, role, expiration)
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ← Signature (verification)

The flow​

1. POST /api/auth/login  { "email": "alice@mail.com", "password": "123" }
2. Server verifies → Generates a JWT → Returns it to the client
3. Client stores the JWT
4. GET /api/users Header: Authorization: Bearer eyJhbG...
5. Server validates the JWT → Authorizes the request

26. What is CORS?​

CORS = Cross-Origin Resource Sharing

When your frontend (localhost:3000) calls your backend (localhost:8080), the browser blocks the request for security. CORS allows these cross-origin requests.

@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}

27. What is Singleton in Spring?​

By default, each Spring bean is a Singleton — a single instance shared throughout the application:

@Service
public class UserService { ... } // ONE single instance, shared everywhere

// Everywhere in the app, it's the SAME UserService object
@RestController
class UserController {
private final UserService userService; // same instance
}

@RestController
class AdminController {
private final UserService userService; // same instance!
}

28. What is the difference between PUT and PATCH?​

MethodActionExample
PUTReplaces all of the objectSend all fields
PATCHModifies partiallySend only fields to modify
// PUT — replaces everything
@PutMapping("/{id}")
public UserDTO update(@PathVariable Long id, @RequestBody UserDTO dto) {
// All fields are overwritten
}

// PATCH — modifies partially
@PatchMapping("/{id}")
public UserDTO patch(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
// Only sent fields are modified
}

29. What is a Custom Exception?​

// Custom exception
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}

// Usage
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found: " + id));
}

// Global handling
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(404)
.body(new ErrorResponse(404, ex.getMessage()));
}
}

public record ErrorResponse(int status, String message) {}

30. What is Spring Actuator?​

Ready-to-use monitoring endpoints:

# application.yml
management:
endpoints:
web:
exposure:
include: health, info, metrics
EndpointWhat it shows
/actuator/healthApp is UP or DOWN
/actuator/infoApp information
/actuator/metricsMetrics (memory, CPU, requests)
/actuator/envEnvironment variables

Summary — The 30 concepts in 1 sentence​

ConceptIn 1 sentence
DTOObject to transport data without exposing the entity
MVCModel (data), View (display), Controller (requests)
REST APIWeb interface using GET/POST/PUT/DELETE on URLs
CRUDCreate, Read, Update, Delete
POJOSimple Java object without framework dependency
BeanObject created and managed by Spring
IoCSpring creates dependencies instead of the code
ORM/JPAMap Java objects to SQL tables
MavenDependency and build management
TomcatWeb server embedded in Spring Boot
JSONLightweight data format (key-value)
PostmanClient to test APIs
SwaggerAutomatic API documentation
DockerIsolated container for the application
CI/CDAutomatic build + test + deployment
GitSource code versioning
LayersController → Service → Repository → DB
@AutowiredAutomatic dependency injection
RecordAuto-generated immutable class (Java 16+)
LombokAutomatically generates getters/setters/equals
ResponseEntityComplete HTTP response (status + body)
@ValidTriggers input validation
application.ymlSpring Boot configuration file
Spring SecurityAuthentication + authorization
JWTToken to identify the user
CORSAllow cross-origin requests
SingletonOne instance of the bean in the entire app
PUT vs PATCHPUT replaces everything, PATCH modifies partially
Custom ExceptionCustom exception with HTTP code
ActuatorApplication monitoring and metrics

⬅️ Chapter 7: Java Collections | ⬅️ Back to Module 18