0% found this document useful (0 votes)
3 views33 pages

Java Backend Interview Questions

The document provides a comprehensive list of Java backend interview questions covering core concepts such as encapsulation, inheritance, polymorphism, abstraction, and access modifiers. It also includes advanced topics like Java 8 Stream API, multithreading, and Spring Boot, along with explanations and examples for each concept. The content is structured to aid candidates in preparing for Java-related interviews by highlighting key principles and practices.

Uploaded by

sourabhchhanchar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views33 pages

Java Backend Interview Questions

The document provides a comprehensive list of Java backend interview questions covering core concepts such as encapsulation, inheritance, polymorphism, abstraction, and access modifiers. It also includes advanced topics like Java 8 Stream API, multithreading, and Spring Boot, along with explanations and examples for each concept. The content is structured to aid candidates in preparing for Java-related interviews by highlighting key principles and practices.

Uploaded by

sourabhchhanchar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🔹

👉
Java backend interview Questions

Core java Questions

Encapsulation

Q1: What is Encapsulation in Java? Why is it important?


Answer:
Encapsulation is the process of binding data (fields) and methods (behaviors) that operate on
that data into a single unit (class), while restricting direct access to the data. In Java, this is
achieved by:
• Declaring fields as private.
• Providing public getters and setters with validation.

It ensures:
• Data security: prevents unauthorized access/modification.
• Flexibility: internal implementation can change without breaking external
code.
• Maintainability: enforces rules like “marks ≤ 100” or “balance ≥ 0”.

Example: In a BankAccount class, balance is private and updated only via deposit()/withdraw().

Inheritance

Q2: Explain Inheritance in Java with a real-life example.


Answer:
Inheritance is an OOP mechanism where a class (child) derives properties and behavior from
another class (parent).
• Declared using extends.
• Enables code reusability and method overriding.

Example:
• Vehicle class → methods like start(), stop().
• Car and Bike extend Vehicle → reuse behavior, override if needed.

This makes code modular and reduces duplication.

Q3: Why does Java not support multiple inheritance with classes?
Answer:
Java avoids multiple class inheritance to prevent the diamond problem, where ambiguity arises
if two parent classes have the same method.
Instead, Java allows multiple inheritance through interfaces, which don’t hold state and avoid
such ambiguity.

Polymorphism

Q4: What is Polymorphism? Difference between compile-time and runtime polymorphism?


Answer:
Polymorphism means “many forms” → the same method name behaves differently depending on
context.
• Compile-time polymorphism (overloading):
Method signature differs (parameters). Example: add(int,int), add(double,double).
Decided at compile time.
• Runtime polymorphism (overriding):
Subclass provides new implementation of parent’s method. Example: Dog overrides
sound() from Animal.
Decided at runtime based on object type.

Q5: Where do you use polymorphism in real projects?


Answer:
• Collections API: A List reference can point to ArrayList or LinkedList.
• Spring Framework: Service interfaces injected with different
implementations (PaymentService → UPI, Card, etc.).
• Strategy Pattern: Applying different tax or discount rules at runtime.

Abstraction

Q6: What is Abstraction? How is it different from Encapsulation?


Answer:
• Abstraction: Hides implementation details and exposes only essential
behavior. Achieved via abstract classes and interfaces.
• Encapsulation: Hides data and provides controlled access via methods.

So, abstraction = what to do, encapsulation = how data is protected.

Example:
• Abstract Shape class with method area().
• Subclasses (Circle, Rectangle) implement their own formulas.
• Caller only cares about area(), not formula details.

Q7: Abstract class vs Interface — when do you use which?


Answer:
• Use interface when you need a contract for unrelated classes (e.g.,
Comparable, Runnable).
• Use abstract class when classes share some common behavior + state (e.g.,
AbstractList in Java).

In modern Java (8+), interfaces can have default and static methods, but they still
can’t hold state like abstract classes.

Access Modifiers
Q8: Explain all access modifiers in Java with visibility scope.
Answer:
• private → within the same class only.
• default (no keyword) → package level.
• protected → package + subclasses (even in other packages).
• public → accessible everywhere.

Example:
• A helperMethod() could be private.
• A service exposed to other packages is public.

Q9: Why is it recommended to keep fields private and not public?


Answer:
• Prevents direct modification of internal state (e.g., setting balance to
negative).
• Allows validation and business rules in setters.
• Supports encapsulation principle.

Combined

Q10: How do all OOP principles work together in real backend development?
Answer:
• Encapsulation: User entity keeps fields private; only validated setters update
data.
• Inheritance: Common base exception class (AppException) extended by
specific exceptions (UserNotFoundException).
• Polymorphism: Payment service interface injected with multiple
implementations (UPI, Card, Wallet).
• Abstraction: Repository interfaces in Spring (UserRepository) hide
persistence logic; developers just call save() or findById().
• Access Modifiers: Core domain classes and helpers kept package-private;
only service APIs are public.
This combination makes the system secure, reusable, testable, and maintainable.

Java 8 Stream API – Interview Q&A

1. What is Stream API in Java?

Answer:
• Introduced in Java 8.
• A stream is a sequence of data that supports functional-style operations
(map, filter, reduce).
• Allows processing collections (like List, Set) efficiently using parallelism
and lazy evaluation.

2. Difference between Streams and Collections?


• Collections → store data (like List, Set, Map).
• Streams → process data (do not store, only provide operations).
• Collections are eagerly constructed, Streams are lazily evaluated.

3. Common Stream Operations?


• Intermediate (return Stream): map, filter, sorted, distinct, limit.
• Terminal (return result): forEach, collect, reduce, count.

Example: Get names of employees with salary > 50,000

List<String> names = [Link]()


.filter(e -> [Link]() > 50000)
.map(Employee::getName)
.collect([Link]());

4. Difference between map() and flatMap()?


• map() → transforms each element into another form.
• flatMap() → flattens nested structures (like List of Lists).

Example:

List<List<Integer>> numbers = [Link]([Link](1,2), [Link](3,4));


[Link]().flatMap(list -> [Link]()).forEach([Link]::println);

5. What is Optional in Java 8?

Answer:
• Optional is a container object to avoid NullPointerException.
• Provides methods like isPresent(), orElse(), ifPresent().

Example:

Optional<String> name = [Link](null);


[Link]([Link]("Default"));

More Core Java Q&A

6. Difference between HashMap and ConcurrentHashMap?


• HashMap → not thread-safe.
• ConcurrentHashMap → thread-safe, uses segment locking.


7. Difference between volatile and synchronized?
• volatile: ensures visibility of variable across threads.
• synchronized: ensures mutual exclusion + visibility.

8. What is the difference between wait(), sleep(), and join()?


• wait() → releases lock, waits until notified.
• sleep() → pauses thread but doesn’t release lock.
• join() → makes one thread wait until another finishes.

Java Interview Q&A

1. What is Multithreading in Java?

Answer:
• Multithreading is the ability of a CPU to execute multiple threads
concurrently.
• In Java, each thread is a lightweight subprocess managed by the JVM.
• Improves performance, especially for CPU-bound and I/O-bound tasks.
• Achieved using Thread class or Runnable interface.

Example:

class MyThread extends Thread {


public void run() {
[Link]("Thread running: " + [Link]().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();
}
}

2. What is Synchronization?

Answer:
• Synchronization is the process of controlling multiple threads’ access to
shared resources.
• Prevents race conditions.
• Achieved using synchronized keyword, locks, or [Link] package.

Example:

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}
}

3. Difference between static and final in Java?

Answer:
• static: Belongs to class, not object. Used for memory management.
• Example: static variables, static methods, static blocks.
• final: Used for restriction.
• final variable → constant.
• final method → cannot be overridden.
• final class → cannot be inherited.

4. What is Polymorphism in Java?

Answer:
• Polymorphism = “one name, many forms”.
• Compile-time polymorphism (method overloading).
• Runtime polymorphism (method overriding).
• Achieved using inheritance and interfaces.

Example (runtime):

class Animal {
void sound() { [Link]("Animal sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Bark"); }
}

String, StringBuilder, and StringBuffer in Java

1. What is the difference between String, StringBuilder, and StringBuffer?

Feature String StringBuilder StringBuffer


Mutability Immutable Mutable Mutable
(once created,
cannot be
changed)
Thread Safety Thread-safe Not thread-safe Thread-safe
(because
immutable)
Not thread-safe Thread-safe
(because (methods are
immutable) synchronized)
Performance Slower for Faster (no Slower than
modifications synchronization StringBuilder
(creates new overhead) (because of
object every synchronization
time) )
Use case When string When frequent When frequent
won’t change modifications in modifications in
much single-threaded multi-threaded
(constants, app app
keys)

2. Why is String immutable in Java?

Answer:
• Security: Strings are used in class loading, network connections →
immutability prevents tampering.
• Caching: JVM caches string literals in the String pool.
• Thread-safety: Multiple threads can share same String without
synchronization.
• Hashing: Immutable makes String safe for use as keys in HashMap.

3. Example of String immutability:

public class Test {


public static void main(String[] args) {
String s1 = "Hello";
String s2 = s1;
s1 = s1 + " World";
[Link](s1); // Hello World
[Link](s2); // Hello (not changed)
}
}

Shows that modification creates a new object.

4. When to use StringBuilder vs StringBuffer?


• Use StringBuilder → in single-threaded environment (better performance).
• Use StringBuffer → in multi-threaded environment where thread-safety is
needed.

5. Code Example (StringBuilder vs StringBuffer):

public class Demo {


public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link]("StringBuilder: " + sb);

StringBuffer sbf = new StringBuffer("Java");


[Link](" Rocks");
[Link]("StringBuffer: " + sbf);
}
}


6. Which is faster: StringBuilder or StringBuffer? Why?
• StringBuilder is faster because its methods are not synchronized.
• StringBuffer is slower because it ensures thread safety using
synchronization.

7. Can StringBuilder/StringBuffer be stored in String pool?


• No. Only String objects are stored in the String pool.
• StringBuilder and StringBuffer are mutable, so not eligible.

8. Can we make String mutable?


• Not directly. But you can simulate mutability using StringBuilder or
StringBuffer.

interview-ready answer sheet.

JAVA – Interview Q&A

Strings

Q: Why use StringBuilder/StringBuffer instead of String?


A: Because String is immutable, frequent modifications create new objects (costly). StringBuilder
and StringBuffer are mutable, so better for performance.

Q: How is == different from .equals() for Strings?


A: == compares reference (memory address), .equals() compares content.
Q: What is the String pool?
A: Special memory inside JVM heap where string literals are stored to save memory.

Q: Example of reversing a string?

String s = "Sourabh";
[Link](new StringBuilder(s).reverse());

OOPs

Q: Abstract class vs Interface?


A: Abstract class can have both abstract and concrete methods, can maintain state. Interface is
100% contract (before Java 8, now allows default/static methods). A class can extend one
abstract class but implement multiple interfaces.

Q: Can a class be abstract and final?


A: No, abstract means it must be extended, final means it cannot be extended.

Q: Real-world example of polymorphism?


A: Payment system – same method pay(), but works differently for UPI, Card, Wallet.

Multithreading

Q: What is a deadlock?
A: Situation where two or more threads are waiting on each other’s lock, causing infinite waiting.

Q: Process vs Thread?
A: Process is independent execution unit with its own memory, thread is lightweight sub-process
sharing process memory.
Q: ExecutorService vs Thread class?
A: Thread → manual thread creation. ExecutorService → manages thread pool, reusable,
scalable.

Collections

Q: HashMap vs LinkedHashMap vs TreeMap?


• HashMap: Unordered, O(1) lookup.
• LinkedHashMap: Maintains insertion order.
• TreeMap: Sorted order (based on keys).

Q: Why HashMap is not thread-safe?


A: Because multiple threads can modify it concurrently. Use ConcurrentHashMap for thread-safe
operations.

Q: Coding – Frequency of characters in string?

Map<Character,Integer> map = new HashMap<>();


for(char c : [Link]())
[Link](c, [Link](c,0)+1);

Java 8 Features

Q: What are functional interfaces?


A: Interfaces with a single abstract method, used in lambda expressions. Example: Runnable,
Predicate.

Q: Predicate vs Function vs Consumer?


• Predicate → returns boolean.
• Function<T,R> → takes input T, returns R.
• Consumer → takes input T, returns nothing.
Q: Streams – max salary?

Optional<Employee> max = [Link]()


.max([Link](Employee::getSalary));

Spring Boot Q&A

12. What is Dependency Injection (DI)?

Answer:
• Technique where object dependencies are injected by the Spring container,
not created manually.
• Improves testability and loose coupling.

13. What is Spring Data JPA?

Answer:
• Abstraction over Hibernate.
• Provides JpaRepository and CrudRepository for easy database access.
• Eliminates boilerplate DAO code.

Example:

public interface EmployeeRepository extends JpaRepository<Employee, Integer> { }

14. What is Spring Boot Actuator?


Answer:
• Provides production-ready features like health checks, metrics, and
monitoring endpoints.
• Example: /actuator/health, /actuator/metrics.

15. Difference between @Component, @Service, and @Repository?


• @Component → generic bean.
• @Service → service/business logic layer.
• @Repository → persistence/DAO layer (adds exception translation).

16. What is the difference between Monolithic and Microservices architecture?


• Monolithic → single, large application, tightly coupled.
• Microservices → small, independent services communicating via REST/
Message queues.
• Spring Boot + Spring Cloud are often used for microservices.

8. What is Spring Boot?

Answer:
• Spring Boot is a framework for building Java-based applications quickly.
• It simplifies Spring framework setup with auto-configuration, starter
dependencies, and embedded servers (Tomcat, Jetty).

9. Why do we use Spring Boot?

Answer:
• Reduces boilerplate code.
• No need for complex XML configuration.
• Production-ready features (Actuator, Metrics, Health checks).
• REST API support out-of-the-box.

10. Explain Layers in Spring Boot Architecture.

Answer:
• Controller Layer → handles HTTP requests (API layer).
• Service Layer → business logic.
• Repository/DAO Layer → database operations (JPA/Hibernate).
• Entity Layer → maps to DB tables.

11. Difference between Spring and Spring Boot?

Answer:
• Spring: Requires lots of XML/manual config.
• Spring Boot: Provides auto-config, embedded server, starter dependencies.

12. How do you create a REST API in Spring Boot?

Answer:

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

@GetMapping("/{id}")
public String getEmployee(@PathVariable int id) {
return "Employee ID: " + id;
}
}
______

Spring Boot – Advanced Interview Q&A

1. What is the difference between @RestController and @Controller?


• @Controller → returns views (HTML, JSP).
• @RestController → returns data (@ResponseBody by default, JSON/XML).

2. Explain Spring Boot Starter dependencies.


• Pre-configured dependencies to simplify setup.
• Example: spring-boot-starter-web, spring-boot-starter-data-jpa.

3. What is Autowiring in Spring?


• Automatic injection of bean dependencies.
• Modes: @Autowired (by type), @Qualifier (by name), @Primary.

4. How do you handle exceptions in Spring Boot?


• Using @ControllerAdvice + @ExceptionHandler.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler([Link])
public ResponseEntity<String> handleException(Exception e) {
return [Link](HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error: " + [Link]());
}
}

5. How does Spring Boot connect to a database?


• Uses Spring Data JPA + Hibernate ORM.
• Configured in [Link]:

[Link]=jdbc:mysql://localhost:3306/test
[Link]=root
[Link]=root
[Link]-auto=update

6. What is the difference between @Entity, @Table, and @Id?


• @Entity → marks a class as JPA entity.
• @Table → maps entity to specific table.
• @Id → marks primary key.

7. What is the difference between CrudRepository, JpaRepository, and


PagingAndSortingRepository?
• CrudRepository: basic CRUD methods.
• JpaRepository: adds JPA-specific features (pagination, flush).
• PagingAndSortingRepository: supports pagination + sorting.

8. How do you secure a REST API in Spring Boot?


• Using Spring Security (authentication + authorization).
• Can use JWT tokens for stateless authentication.


9. What is the difference between [Link] and [Link]?
• Both store config.
• properties: key=value format.
• yml: hierarchical format, more readable.

10. Explain Spring Boot Profiles.


• Profiles = different configurations for different environments.
• Example: [Link], [Link].
• Activated via:

[Link]=dev

11. How do you test in Spring Boot?


• Unit Testing → JUnit, Mockito.
• Integration Testing → @SpringBootTest.

Example:

@SpringBootTest
class EmployeeServiceTest {
@Autowired
EmployeeService service;

@Test
void testGetEmployee() {
assertEquals("John", [Link](1).getName());
}
}

12. How does Spring Boot manage transactions?


• Using @Transactional.
• Ensures rollback on failure.

Spring Boot – Advanced Interview Q&A

1. What is the difference between @RestController and @Controller?


• @Controller → returns views (HTML, JSP).
• @RestController → returns data (@ResponseBody by default, JSON/XML).

2. Explain Spring Boot Starter dependencies.


• Pre-configured dependencies to simplify setup.
• Example: spring-boot-starter-web, spring-boot-starter-data-jpa.

3. What is Autowiring in Spring?


• Automatic injection of bean dependencies.
• Modes: @Autowired (by type), @Qualifier (by name), @Primary.

4. How do you handle exceptions in Spring Boot?


• Using @ControllerAdvice + @ExceptionHandler.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler([Link])
public ResponseEntity<String> handleException(Exception e) {
return [Link](HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error: " + [Link]());
}
}

5. How does Spring Boot connect to a database?


• Uses Spring Data JPA + Hibernate ORM.
• Configured in [Link]:

[Link]=jdbc:mysql://localhost:3306/test
[Link]=root
[Link]=root
[Link]-auto=update

6. What is the difference between @Entity, @Table, and @Id?


• @Entity → marks a class as JPA entity.
• @Table → maps entity to specific table.
• @Id → marks primary key.

7. What is the difference between CrudRepository, JpaRepository, and


PagingAndSortingRepository?
• CrudRepository: basic CRUD methods.
• JpaRepository: adds JPA-specific features (pagination, flush).
• PagingAndSortingRepository: supports pagination + sorting.


8. How do you secure a REST API in Spring Boot?
• Using Spring Security (authentication + authorization).
• Can use JWT tokens for stateless authentication.

9. What is the difference between [Link] and [Link]?


• Both store config.
• properties: key=value format.
• yml: hierarchical format, more readable.

10. Explain Spring Boot Profiles.


• Profiles = different configurations for different environments.
• Example: [Link], [Link].
• Activated via:

[Link]=dev

11. How do you test in Spring Boot?


• Unit Testing → JUnit, Mockito.
• Integration Testing → @SpringBootTest.

Example:

@SpringBootTest
class EmployeeServiceTest {
@Autowired
EmployeeService service;

@Test
void testGetEmployee() {
assertEquals("John", [Link](1).getName());
}
}

12. How does Spring Boot manage transactions?


• Using @Transactional.
• Ensures rollback on failure
__________

SQL Interview Q&A

5. Difference between UNION and JOIN?

Answer:
• UNION: Combines results of two queries (row-wise). Removes duplicates by
default.
• JOIN: Combines columns from multiple tables based on related keys.

Example:

-- UNION
SELECT name FROM employees
UNION
SELECT name FROM managers;

-- JOIN
SELECT [Link], d.dept_name
FROM employees e
JOIN department d ON e.dept_id = d.dept_id;


6. Types of Joins in SQL?

Answer:
• INNER JOIN → common records.
• LEFT JOIN → all from left + matching from right.
• RIGHT JOIN → all from right + matching from left.
• FULL JOIN → all records, matching and non-matching.
• SELF JOIN → table joins with itself.

7. Write a basic SQL query:

Get all employees with department name.

SELECT e.emp_id, [Link], d.dept_name


FROM employees e
INNER JOIN departments d ON e.dept_id = d.dept_id;

9. What is the difference between WHERE and HAVING?


• WHERE → used before grouping (filters rows).
• HAVING → used after GROUP BY (filters groups).

Example:

SELECT dept_id, COUNT(*)


FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;


10. What is a Primary Key and Foreign Key?
• Primary Key: Uniquely identifies each row. Cannot be null.
• Foreign Key: Refers to primary key in another table, maintains relationship.

11. Write query: Find 2nd highest salary.

Solution 1 (Subquery):

SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

Solution 2 (LIMIT - MySQL/Postgres):

SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

1. Difference between DELETE, TRUNCATE, and DROP?


• DELETE: Removes rows, can use WHERE, rollback possible.
• TRUNCATE: Removes all rows, faster, can’t use WHERE, rollback depends on
DB.
• DROP: Removes table structure and data permanently.

2. What are indexes in SQL? Why are they used?


• Index = special data structure that speeds up query retrieval.
• Like a book index (helps jump to data quickly).
• Types:
• Clustered index (reorders table rows, 1 per table).
• Non-clustered index (stores pointer to data).

Example:

CREATE INDEX idx_name ON employees(name);

3. Difference between INNER JOIN, LEFT JOIN, and CROSS JOIN?


• INNER JOIN: common records in both tables.
• LEFT JOIN: all from left table + matching from right.
• CROSS JOIN: Cartesian product (all combinations).

4. How do you find duplicate records in SQL?

SELECT name, COUNT(*)


FROM employees
GROUP BY name
HAVING COUNT(*) > 1;

5. What are aggregate and window functions?


• Aggregate functions: SUM, AVG, COUNT, MAX, MIN (group level).
• Window functions: operate over partitions without collapsing rows.

Example (2nd highest salary with ROW_NUMBER):

SELECT emp_id, name, salary


FROM (
SELECT emp_id, name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) as row_num
FROM employees
)t
WHERE row_num = 2;

6. Explain EXISTS vs IN.


• IN: checks if value exists in a list (faster for small subqueries).
• EXISTS: checks if subquery returns rows (better for large datasets).

Example:

SELECT * FROM employees e


WHERE EXISTS (SELECT 1 FROM department d WHERE e.dept_id = d.dept_id);

7. What is normalization and denormalization?


• Normalization: breaking tables into smaller ones to reduce redundancy (1NF,
2NF, 3NF, BCNF).
• Denormalization: combining tables for performance (common in reporting).

SQL – Interview Q&A

Joins & Queries

Q: Inner vs Self Join?


A: Inner Join matches between 2 tables. Self Join joins a table with itself.
Q: Employees without department?

SELECT [Link]
FROM employees e
LEFT JOIN department d ON e.dept_id = d.dept_id
WHERE d.dept_id IS NULL;

Q: Nth highest salary?

SELECT salary FROM (


SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) as rn
FROM employees
)t
WHERE rn = 2;

Performance

Q: What is an index?
A: Data structure that speeds up search. Clustered index = data sorted physically. Non-clustered
= separate structure.

Q: Primary key vs Unique key?


A: Both enforce uniqueness. PK = only one per table, not null. Unique = multiple allowed, can
have null.

Q: Foreign key?
A: Enforces relationship between tables. Child table column refers parent table’s PK.

Transactions

Q: ACID properties?
• Atomicity: all or nothing.
• Consistency: DB must remain valid.
• Isolation: transactions don’t affect each other.
• Durability: once committed, data is permanent.

Q: Commit vs Rollback?
• Commit → permanently saves.
• Rollback → undo changes.

Q: Isolation levels?
• Read Uncommitted, Read Committed, Repeatable Read, Serializable.

SPRING BOOT – Interview Q&A

Basics

Q: How does auto-configuration work?


A: Uses @EnableAutoConfiguration, classpath scanning + conditionals to auto-configure beans.

Q: @Component vs @Service vs @Repository?


• @Component: generic bean.
• @Service: business logic bean.
• @Repository: DAO bean with exception translation.

REST APIs

Q: How to validate requests?


A: Use annotations like @Valid, @NotNull, @Size with DTOs.

Q: Difference between @GetMapping and @PostMapping?


A: GET → fetch data, POST → create resource.

Data & Persistence

Q: How Spring Boot connects to DB?


A: Uses Spring Data JPA and Hibernate. Config in [Link].

Q: save() vs saveAll()?
• save() → persists single entity.
• saveAll() → persists collection of entities.

Configurations

Q: Spring Boot profiles?


A: Different env configs (dev/test/prod). Activate with [Link]=dev.

Q: [Link] vs [Link]?
• properties = key=value.
• yml = hierarchical, more readable.

Advanced

Q: What is Actuator?
A: Provides endpoints for monitoring: /actuator/health, /actuator/metrics.

Q: How to secure Spring Boot app?


A: With Spring Security. JWT tokens for stateless auth.

Q: Monolithic vs Microservices?
• Monolithic = one large app.
• Microservices = independent services, communicate via REST/queues.

Quick Coding Practice

SQL

Q: Employees with salary > avg salary?

SELECT * FROM employees


WHERE salary > (SELECT AVG(salary) FROM employees);

Q: Delete duplicate rows but keep one?

DELETE FROM employees


WHERE id NOT IN (
SELECT MIN(id)
FROM employees
GROUP BY name, dept_id
);

Java

Q: Palindrome check?

String s = "madam";
[Link]([Link](new StringBuilder(s).reverse().toString()));

Q: Find duplicate characters?

for(char c : [Link]()){
if([Link](c, [Link](c,0)+1) > 1)
[Link]("Duplicate: " + c);
}
Q: Odd/Even printing with threads?
→ Classic wait/notify example. (Mention in interview, don’t need full code unless asked).

You might also like