Fresher Java + Spring Boot: Common Interview
Questions
Below is a concise, topic-wise checklist of questions commonly asked for entry-level (fresher)
roles focusing on Java and Spring Boot. Use it as a prep roadmap.
Core Java (must-know)
OOP basics: class vs object, inheritance, polymorphism (overloading vs overriding),
encapsulation, abstraction.
Access modifiers: public, private, protected, default; packages.
String vs StringBuilder vs StringBuffer; immutability; string pool.
Collections Framework: List vs Set vs Map; ArrayList vs LinkedList; HashSet vs TreeSet;
HashMap vs LinkedHashMap vs TreeMap; equals() and hashCode().
Generics basics and wildcards (? extends / ? super).
Exceptions: checked vs unchecked; try-catch-finally; try-with-resources; custom
exceptions.
Java 8+ features: functional interfaces, lambda expressions, method references, streams
(map/filter/reduce), Optional.
Multithreading: Thread vs Runnable; synchronized, volatile; deadlock, race condition; basics
of ExecutorService and futures.
JVM basics: JDK vs JRE vs JVM; heap vs stack; garbage collection basics.
I/O and NIO basics; serialization.
Immutability and builder pattern; common design patterns (Singleton, Factory, Strategy).
Spring Core/Foundation
What is Spring Framework? Advantages of DI/IoC.
Bean lifecycle; bean scopes (singleton, prototype).
Dependency Injection: constructor vs setter injection; @Autowired best practices.
@Component, @Service, @Repository, @Controller – purpose and differences.
@Configuration, @Bean; component scanning and base packages.
@Value and externalized configuration.
Spring Boot Basics
What is Spring Boot? Why Spring Boot over traditional Spring?
Auto-configuration: how it works conceptually; how to customize/disable.
Starters (spring-boot-starter-web, data-jpa, security, test, validation, thymeleaf, actuator).
@SpringBootApplication (combines @Configuration, @EnableAutoConfiguration,
@ComponentScan).
Project setup methods: Spring Initializr; Maven vs Gradle basics.
[Link] vs [Link]; profiles ([Link]).
Embedded servers (Tomcat/Jetty/Undertow); changing [Link].
Running and packaging apps: executable JAR, basic build/run commands.
REST APIs with Spring Boot
@RestController vs @Controller; @RequestMapping,
@GetMapping/@PostMapping/@PutMapping/@DeleteMapping.
@PathVariable vs @RequestParam vs @RequestBody vs @RequestHeader.
HTTP status codes; returning ResponseEntity; content negotiation basics (JSON/XML).
Validation: Bean Validation (JSR-380), @Valid/@Validated, constraint annotations, handling
validation errors.
Exception handling: @ControllerAdvice/@RestControllerAdvice, @ExceptionHandler; custom
error responses.
Logging basics (SLF4J/Logback) and log levels.
Data Access: Spring Data JPA
JPA/Hibernate basics: Entity, @Id, @GeneratedValue, @Column, relationships
(@OneToMany, @ManyToOne, fetch types), cascades.
Repositories: CrudRepository, JpaRepository, derived query methods, @Query.
Persistence context, lazy vs eager loading; N+1 basics.
Transactions: @Transactional – readOnly, propagation basics.
Datasource configuration; H2 for dev/testing; schema/data SQL; DDL auto.
Pagination and sorting (Pageable, Page, Sort).
Testing
Spring Boot Test basics: @SpringBootTest; slicing tests (@WebMvcTest, @DataJpaTest).
Mocking with Mockito; @MockBean vs @Mock; unit vs integration tests.
Testing controllers with MockMvc; testing repositories with H2.
Actuator, Monitoring, and Configuration
Actuator endpoints (health, info, metrics); enabling/exposing endpoints.
Health checks and info contributors; readiness/liveness basics.
Externalized config order of precedence; environment-specific configs;
@ConfigurationProperties.
Security (intro level)
Basics of Spring Security: authentication vs authorization concepts.
Securing endpoints; in-memory users; password encoders.
Simple stateless auth idea (JWT high-level understanding is a plus for freshers).
Build/Dev Tools and Productivity
DevTools: auto-restart/live reload.
Lombok annotations (@Getter/@Setter/@Builder/@Data) and pitfalls.
Maven basics: dependency management, BOM, parent POM; typical lifecycle phases.
Microservices (high-level awareness)
What is a microservice; why/when to use.
API gateway, service discovery (conceptual); configuration server basics; resilience patterns
(circuit breaker concept).
Inter-service communication (REST; basic idea of Feign/OpenFeign).
Message brokers overview (Kafka/RabbitMQ) – only conceptual for freshers.
Practical/Scenario Questions
Design a simple CRUD REST API (entities, controller endpoints, service, repository).
How to handle validation and return meaningful error messages.
How to configure a different database per environment (dev/test/prod) with profiles.
How to avoid N+1 issue; when to use DTOs vs exposing entities.
How to log request/response; create a simple filter or interceptor.
How to paginate and sort a list endpoint.
Steps to change server port, context path, and enable CORS.
Typical 404/400/500 troubleshooting approach in Spring Boot.
SQL and Database Fundamentals (often included)
Basic SQL: SELECT/INSERT/UPDATE/DELETE; JOINS; indexes; primary vs foreign keys;
normalization basics.
Transactions and isolation levels (conceptual).
Version Control and Deployment Basics
Git fundamentals: branching, pull/merge, resolving conflicts.
Running Spring Boot JAR on a server; basic environment variables; reading secrets safely.
Container basics: Dockerfile for Spring Boot (awareness).
Quick 50-question checklist (grab-and-go)
What is Spring Boot and its key benefits?
How does auto-configuration work?
What do starters do? Name common starters.
What does @SpringBootApplication include?
Difference between @RestController and @Controller?
Purpose of [Link]/yml; switch profiles.
How to change [Link]?
How to set up a simple REST endpoint?
@PathVariable vs @RequestParam vs @RequestBody.
What is ResponseEntity and when to use it?
Validation with @Valid and common constraints.
Global exception handling with @ControllerAdvice.
What is Spring Data JPA? Benefits.
JpaRepository vs CrudRepository.
Derived query methods; @Query usage.
Entity mapping annotations and relationships.
Lazy vs eager fetch; N+1 problem.
Purpose of @Transactional.
What is the persistence context?
How to use H2 in-memory DB for tests.
@SpringBootTest vs @WebMvcTest vs @DataJpaTest.
MockMvc basics for controller tests.
Mockito: @Mock vs @MockBean.
Actuator: enabling health and metrics endpoints.
What is a health check endpoint used for?
Externalized configuration precedence.
@ConfigurationProperties vs @Value.
What is Spring Security at a high level?
How to create in-memory users for testing.
Why prefer constructor injection?
Bean scopes and lifecycle basics.
@Component vs @Service vs @Repository differences.
What problem does DI/IoC solve?
Maven: what is a parent POM/BOM?
Lombok: benefits and caveats.
DevTools: what does it provide?
Logging levels and configuration basics.
How to handle CORS in Spring Boot?
Pagination and sorting with Pageable.
DTO vs Entity in controller responses.
How to return proper error codes.
Common HTTP status codes for REST.
Steps to package and run a Spring Boot JAR.
Basic Dockerfile for Spring Boot (conceptual).
Core Java: equals/hashCode and why they matter in collections.
String vs StringBuilder; immutability.
Checked vs unchecked exceptions.
Java 8 streams and Optionals basics.
Thread basics and common concurrency pitfalls.
If a tailored set is needed for a specific job description, share the JD or the tech stack focus
(e.g., JPA-heavy, REST-only, security, or microservices exposure), and a role-specific question
bank can be curated accordingly.
⁂
Interview Answers: Core Java, Spring, and Spring
Boot
Below are concise, interview-ready answers to the topics requested. Each point gives a crisp
definition and the practical nuance expected in fresher interviews.
Core Java (must‑know)
OOP basics
Class vs Object: A class is a blueprint; an object is an instance with state and behavior. [1] [2]
[3]
Inheritance: Mechanism to acquire fields/methods of a parent using extends; models “is‑a”
and promotes reusability. [4] [1]
Polymorphism:
Overloading: Same method name, different parameter lists (compile‑time). [4] [1]
Overriding: Subclass changes behavior of a superclass method (runtime). [1] [4]
Encapsulation: Bundle data and methods; hide state via private fields and expose via
getters/setters for safety and clarity. [2] [4] [1]
Abstraction: Expose essential behavior, hide details using abstract classes/interfaces to
reduce complexity. [5] [2] [4]
Access modifiers and packages
public: Visible everywhere; protected: package+subclasses; default: package‑private;
private: within class only; packages group related classes and control visibility. [3] [1]
String vs StringBuilder vs StringBuffer
String is immutable; operations create new objects; benefits: thread‑safety, interning in
string pool. [3] [1]
StringBuilder is mutable, not thread‑safe, fastest for single‑threaded concatenation. [3]
StringBuffer is mutable, synchronized, thread‑safe, slower than StringBuilder. [3]
Collections Framework essentials
List keeps order and duplicates; Set unique elements; Map key‑value pairs. [3]
ArrayList vs LinkedList: ArrayList random access O(1), shifts on insert/delete; LinkedList O(1)
insert/delete with O(n) access. [3]
HashSet vs TreeSet: HashSet unordered O(1) average ops; TreeSet sorted O(log n). [3]
HashMap vs LinkedHashMap vs TreeMap: HashMap unordered, LinkedHashMap insertion
order, TreeMap sorted by key. [3]
equals() and hashCode(): Must be consistent; equal objects must have equal hash codes to
work correctly in hash‑based collections. [1] [3]
Generics and wildcards
Generics add type safety at compile time. [3]
? extends T: Producer (read) upper‑bounded; ? super T: Consumer (write) lower‑bounded;
PECS guideline. [3]
Exceptions
Checked vs Unchecked: Checked must be declared/handled; unchecked
(RuntimeException) typically programming errors. [3]
try‑catch‑finally: finally runs regardless; try‑with‑resources auto‑closes AutoCloseable
resources. [3]
Custom exceptions: Extend Exception/RuntimeException with meaningful names and
context. [3]
Java 8+ features
Functional interfaces: Single abstract method (e.g., Runnable, Comparator). [3]
Lambdas/method references: Concise behavior passing; streams enable map/filter/reduce
pipelines. [3]
Optional: Avoids null checks with expressive APIs. [3]
Multithreading basics
Thread vs Runnable: Runnable decouples task from thread; prefer executors. [3]
synchronized, volatile: synchronized ensures mutual exclusion and happens‑before; volatile
ensures visibility, not atomicity. [3]
Deadlock/race condition: Deadlock is circular wait; race is unsynchronized shared state
hazard; avoid with ordering and synchronization. [3]
ExecutorService/futures: Thread pools manage tasks; Future/CompletableFuture handle
async results. [3]
JVM basics
JDK vs JRE vs JVM: JDK=tools+JRE; JRE=JVM+libs; JVM runs bytecode. [3]
Heap vs stack: Heap for objects/GC; stack for frames/locals. [3]
GC basics: Automatically reclaims unreachable objects; different collectors exist; tuning as
needed. [3]
I/O, NIO, serialization
I/O streams for byte/char operations; NIO offers channels, buffers, selectors for scalable I/O.
[3]
Serialization: Converts objects to byte stream; implement Serializable; manage
serialVersionUID and transient fields. [3]
Immutability, builder, patterns
Immutability: Final fields, no setters, defensive copies; thread‑safe and simple reasoning. [3]
Builder pattern: Stepwise construction, avoids telescoping constructors. [3]
Common patterns: Singleton, Factory, Strategy widely used for creation and behavior
encapsulation. [4] [3]
Spring Core/Foundation
What is Spring? Why DI/IoC?
Spring is a framework providing IoC/DI, AOP, MVC, data access; IoC container creates and
wires beans, promoting loose coupling and testability. [6] [7] [8]
DI injects dependencies via constructor/setter/field; prefer constructor injection for
immutability and testing. [7] [8]
Bean lifecycle and scopes
Lifecycle: Instantiation → dependency injection → initialization → ready → destruction;
hooks via @PostConstruct/@PreDestroy or InitializingBean/DisposableBean. [8] [7]
Scopes: singleton (default), prototype; web scopes like request, session when applicable. [7]
[8]
DI styles and @Autowired
Constructor injection preferred; setter for optional dependencies; avoid field injection for
testability; @Autowired on single constructor is implicit. [8] [7]
Stereotypes
@Component generic; @Service business logic; @Repository data access (exception
translation); @Controller MVC handler. [7] [8]
Configuration and scanning
@Configuration marks config classes; @Bean defines factory methods; @ComponentScan
controls package scanning roots. [9] [8] [7]
@Value and externalized config
Inject primitives/strings from properties; externalized configuration supports different
environments via files, env vars, etc.. [9] [7]
Spring Boot Basics
What is Spring Boot? Why over classic Spring?
Spring Boot simplifies Spring with auto‑configuration, starter dependencies, embedded
server, opinionated defaults, and production‑ready features. [9] [8] [7]
Benefits: Minimal configuration, faster development, reduced boilerplate, easy testing and
deployment. [9] [7]
Auto‑configuration
Conditionally configures beans based on classpath and properties; customizable via
properties or excluding specific auto‑configs. [6] [7] [9]
Starters
spring‑boot‑starter‑web, data‑jpa, security, test, validation, thymeleaf, actuator, etc., bundle
dependencies with compatible versions. [6] [7] [9]
@SpringBootApplication
Combines @Configuration, @EnableAutoConfiguration, @ComponentScan; main entry point
calling [Link](). [6] [7] [9]
Project setup
Spring Initializr to generate projects; Maven vs Gradle are common build tools; Boot
manages versions via parent/BOM. [7] [9]
Properties/yaml and profiles
[Link] or [Link]; activate profiles via [Link] for
env‑specific config. [9] [7]
Embedded servers and ports
Default Tomcat; can switch to Jetty/Undertow via starters; change [Link] property to
alter port. [7] [9]
Running and packaging
Build executable JAR and run with java -jar; mvn spring-boot:run or gradle bootRun in dev.
[9] [7]
REST APIs with Spring Boot
Controllers and mappings
@RestController returns JSON/XML directly; @Controller returns views/templates; map
endpoints via @RequestMapping and composed annotations. [6] [7] [9]
Parameters and bodies
@PathVariable for URI segments, @RequestParam for query params, @RequestBody for
request payloads, @RequestHeader for headers. [7] [9]
HTTP status and ResponseEntity
Use ResponseEntity to set status/headers/body explicitly; support content negotiation via
message converters. [9] [7]
Validation
Bean Validation (JSR‑380) with @Valid/@Validated and constraints like @NotNull, @Size;
handle binding errors via BindingResult or exception advice. [7] [9]
Exception handling
Global handling using @ControllerAdvice/@RestControllerAdvice with @ExceptionHandler to
return consistent error responses. [6] [9] [7]
Logging
SLF4J with Logback by default; control levels via [Link]; use parameterized logs to
avoid string building. [9] [7]
Data Access: Spring Data JPA
JPA/Hibernate basics
@Entity maps classes; @Id/@GeneratedValue for identifiers; @Column for fields;
relationships via @OneToMany/@ManyToOne with fetch types and cascades. [7] [9]
Default fetch: ManyToOne/OneToOne EAGER by spec; OneToMany/ManyToMany LAZY;
prefer marking associations LAZY and fetch selectively to avoid performance issues. [10] [11]
Repositories
CrudRepository/JpaRepository provide CRUD, pagination, sorting; derived query methods
and @Query for custom queries. [6] [9] [7]
Persistence context and fetching
Persistence context tracks entities; lazy vs eager impacts when associations load;
LazyInitializationException occurs if accessing lazy association outside open context. [12] [13]
[10]
Solutions: fetch joins, entity graphs, transactional scope, or targeted config; avoid globally
disabling lazy checks. [14] [12] [10]
Transactions
@Transactional defines boundaries; readOnly hints optimizations; propagation controls how
transactions join or create new ones. [12] [7]
Datasource and dev DBs
Configure datasource via properties; H2 commonly used for dev/test; [Link]/[Link]
auto‑run; [Link]-auto for DDL strategy. [6] [9] [7]
Pagination and sorting
Pageable, Page, and Sort provided by Spring Data; repository methods accept Pageable to
return Page<T>. [9] [7]
Testing
@SpringBootTest loads full context for integration testing; slice tests: @WebMvcTest for
MVC, @DataJpaTest for JPA only. [6] [7] [9]
Mockito for mocking; @MockBean to replace beans in context; MockMvc to test controllers
without starting server; H2 for repository tests. [7] [9]
Actuator, Monitoring, Config
Actuator exposes endpoints like /actuator/health, /info, /metrics; enable/expose as needed
via properties; supports health/info contributors. [6] [9] [7]
Externalized config order of precedence allows overriding via env vars, command line, etc.;
@ConfigurationProperties binds structured config. [9] [7]
Security (intro)
Spring Security covers authentication/authorization; define in‑memory users for demos; use
password encoders; JWT is a common stateless approach conceptually. [7] [9]
Build/Dev Tools
DevTools provides auto‑restart and live reload to speed development. [9] [7]
Maven parent/BOM manage dependency versions; typical lifecycle phases clean, compile,
test, package. [7] [9]
Microservices (awareness)
Microservices are small, independently deployable services; concepts: API gateway, service
discovery, config server, circuit breakers, inter‑service communication (e.g., REST/Feign). [8]
[9] [7]
A few nuanced JPA points interviewers like
Lazy vs eager defaults: OneToMany/ManyToMany default LAZY; ManyToOne/OneToOne
default EAGER per spec, but many teams override to LAZY and use fetch strategies on
demand for performance. [11] [10]
Handling LazyInitializationException: Access within transaction, use fetch joins or
EntityGraph, or repository projections; avoid globally disabling lazy checks which can mask
design issues. [13] [14] [12]
If sample answers with code snippets are needed for any specific bullet (e.g., global exception
handler, pagination endpoint, or @ConfigurationProperties), specify which ones to expand and
they can be provided in ready‑to‑use form.
⁂
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. [Link]
pa-and-hibernate
14. [Link]