[Go to site: main page, start]

0% found this document useful (0 votes)
12 views27 pages

Java Interview Questions

Naresh Reddy has nearly 5 years of experience in Java backend development, focusing on Java, Spring Boot, and Microservices at T-Mobile. The document covers core Java concepts, including OOP principles, exception handling, threading, and Java 8 features, along with practical examples. It also highlights Naresh's involvement in Agile methodologies and production issue resolution using tools like Splunk.

Uploaded by

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

Java Interview Questions

Naresh Reddy has nearly 5 years of experience in Java backend development, focusing on Java, Spring Boot, and Microservices at T-Mobile. The document covers core Java concepts, including OOP principles, exception handling, threading, and Java 8 features, along with practical examples. It also highlights Naresh's involvement in Agile methodologies and production issue resolution using tools like Splunk.

Uploaded by

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

1|Page

Hi, my name is Naresh Reddy. I have around 4 years and 10 months of


experience in Java backend development, mainly using Java, Spring
Boot, and Microservices.
Currently, I’m part of the T-Mobile Payments domain, where I’ve worked
on migration stories and production issue resolutions.
I use Splunk for analyzing logs and identifying the root cause of
production issues.
Our application has around 60 microservices, and each service handles
a specific functionality — for example, transaction processing, card type
validation, cardless, and retail transactions, as well as report
generation and feed submissions to external systems.
For testing, I write JUnit test cases, and we follow Agile methodology,
where I’m actively involved in daily scrums, sprint planning, and code
reviews.

🧠 Core Java (Spoken Version)

1. What is Java?
Java is a high-level, object-oriented programming language.
It’s platform-independent — which means we can write the code once and run it anywhere, thanks
to the JVM (Java Virtual Machine).
It’s mainly used for building web, mobile, and enterprise applications.

2. What are the main OOP concepts?


There are four main OOP concepts — Encapsulation, Inheritance, Polymorphism, and Abstraction.

 Encapsulation means wrapping data and methods together, like keeping your variables
private and using getters and setters.

 Inheritance means reusing code — one class can use the properties and methods of another
using the extends keyword.

 Polymorphism means “many forms” — the same method behaves differently depending on
the input.

 Abstraction means hiding the internal details and showing only the important part — like
using a car’s start button without worrying how the engine works.

3. What is a Class and Object?


A class is a blueprint or template that defines variables and methods.
An object is an actual instance of that class, created in memory.

Example:

class Car { void run() {} }


2|Page

Car myCar = new Car();

Here, Car is the class, and myCar is the object.

4. What is Inheritance?
Inheritance means one class can use the properties and methods of another class.
We achieve it using the extends keyword.

Example:

class Child extends Parent { }

This helps in code reusability and builds relationships between classes.

5. What is Polymorphism?
Polymorphism means the same action behaves differently depending on the situation.
There are two types:

 Compile-time Polymorphism (Overloading): Same method name but different parameters.

 Runtime Polymorphism (Overriding): A child class changes or overrides a parent class


method.

Example:

class A { void show() { } }

class B extends A { void show() { } } // overriding

6. What is Encapsulation?
Encapsulation means data hiding.
We keep class variables private and use getters and setters to access them.
This protects data from being modified directly from outside the class.

Example:

private String name;

public void setName(String name) { [Link] = name; }

7. What is Abstraction?
Abstraction hides the internal logic and shows only what’s necessary.
We achieve abstraction using abstract classes or interfaces.

Example:
When we call start() on a car, we don’t know how the engine starts — that’s abstraction.
3|Page

8. What is a Constructor?
A constructor is a special method that runs automatically when an object is created.
It has the same name as the class and no return type.
We use it to initialize object variables.

Example:

public Car() {

[Link]("Car is created");

9. Difference between == and equals()?


== compares memory locations (it checks if both references point to the same object).
equals() compares actual content or value.

Example:

String s1 = new String("Hi");

String s2 = new String("Hi");

s1 == s2 → false

[Link](s2) → true

10. Difference between final, finally, and finalize()

 final → used for constants, methods, or classes you don’t want to modify or extend.

 finally → a block that always executes after try-catch, usually for cleanup work.

 finalize() → a method called by Garbage Collector before destroying an object (not


commonly used now).

11. What is String in Java?


String is a class in Java used to store text.
It’s immutable, meaning once created, it can’t be changed.
If we modify it, a new String object is created in memory.

12. How to make a class immutable?


To make a class immutable:

 Make the class final (can’t be extended)

 Make all fields private and final

 Don’t provide setters


4|Page

 Initialize fields only in the constructor

 Return copies of mutable fields instead of direct references

Example: The String class in Java is immutable.

13. What is HashMap?


HashMap stores data in key-value pairs.
Each key is unique, and it uses hashing for faster data access.
It allows one null key and multiple null values.
It’s not thread-safe and doesn’t maintain order.

14. What is ConcurrentHashMap?


ConcurrentHashMap is a thread-safe version of HashMap.
It allows multiple threads to read and write safely at the same time.
It doesn’t allow null keys or values and performs faster because it locks only small parts of the map
(segments).

15. What is the volatile keyword?


volatile ensures that the latest value of a variable is always read from the main memory, not from a
thread’s local cache.
It’s mainly used in multi-threading for visibility between threads.

16. Difference between synchronized and Lock?

 synchronized → simpler, automatically handles locking and unlocking of code blocks.

 Lock (from [Link]) → gives more control, you can use features like tryLock() or
lockInterruptibly().
Locks are better for complex concurrency cases.

17. What are Wrapper Classes?

Wrapper classes convert primitive data types into objects (e.g., int → Integer, double → Double).
They’re used in collections or generics where objects are required.
Example:

int num = 10;

Integer obj = [Link](num);

18. What is Autoboxing and Unboxing?

 Autoboxing → automatically converts primitive to wrapper.

 Unboxing → converts wrapper back to primitive.


Example:
5|Page

Integer i = 5; // autoboxing

int x = i;

19. What is method overloading and overriding?

 Overloading → same method name, different parameters (compile-time polymorphism).

 Overriding → same method signature in subclass (runtime polymorphism)

20. What is the difference between an abstract class and an interface?

 Abstract class → can have abstract and normal methods; supports inheritance.

 Interface → all methods are abstract (till Java 7), used for full abstraction and multiple
inheritance.
From Java 8, interfaces can also have default and static methods.

21. What is Garbage Collection?

Garbage Collection automatically removes unused objects from memory.


You don’t have to delete them manually — JVM does it.
It helps prevent memory leaks.

22. Difference between String, StringBuilder, and StringBuffer?

 String → immutable (once created, can’t change).

 StringBuilder → mutable, not thread-safe, faster.

 StringBuffer → mutable, thread-safe, slightly slower.

Example:

StringBuilder sb = new StringBuilder("Hello");

[Link](" World"); // modifies same object

23. What is the difference between shallow copy and deep copy?

 Shallow copy → copies references, not actual objects.

 Deep copy → creates a full new copy of the object and its contents.

24. What is Serialization and Deserialization?

 Serialization → converting an object into a byte stream (to save to file or send over
network).

 Deserialization → converting the byte stream back into an object.


Used for persistence or communication between systems.

 Example:
6|Page

 ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("[Link]"));
 [Link](obj);

25. What are access modifiers in Java?

There are four:

 public → accessible everywhere

 protected → accessible in same package or subclass

 default → accessible only within package

 private → accessible only inside the same class

26. What is the difference between an Interface and Abstract class in Java 8+?

From Java 8 onwards:

 Interfaces can now have default and static methods.

 Abstract classes can still have constructors and instance variables — interfaces can’t.

27. What is a Package in Java?


A package is basically a folder structure that helps group related classes together.
It helps avoid class name conflicts and makes code organized.
For example,

package [Link];

It means this class belongs to that specific package.

28. What is the use of import keyword?


The import keyword is used to bring other classes or packages into the current file so we can use
them directly.
Example:

import [Link];

Without it, we’d have to use full names like [Link] everywhere.

28. What is this keyword?


this refers to the current object of the class.
We use it when variable names conflict or when we want to call another constructor in the same
class.

Example:

[Link] = name;

Here, [Link] means the class variable, not the local one.
7|Page

29. What is super keyword?


super refers to the parent class.
We use it to access parent methods, variables, or constructors from the child class.
Example:

[Link]();

It helps when we override methods but still want to call parent behavior.

30. What is Exception Handling in Java?


Exception Handling is a way to deal with runtime errors so that the program doesn’t crash.
We handle exceptions using keywords like try, catch, finally, throw, and throws.
This helps in writing reliable and stable applications.

31. What is the difference between Checked and Unchecked Exceptions?

 Checked exceptions are checked at compile time — for example IOException, SQLException.

 Unchecked exceptions happen at runtime — for example NullPointerException,


ArithmeticException.

So basically, checked ones must be either handled using try-catch or declared using throws.

32. How does try and catch work?


We put the risky code inside the try block and handle the error in the catch block.
Example:

try {

int a = 5 / 0;

} catch (ArithmeticException e) {

[Link]("Cannot divide by zero");

This prevents the program from crashing.

33. What is finally block used for?


The finally block always executes — whether an exception occurs or not.
It’s mostly used to close database connections, files, or release resources.

Example:

finally {

[Link]("Cleanup done");
8|Page

34. Difference between throw and throws?

 throw is used to manually throw an exception inside a method.

 throws is used in the method declaration to tell the caller that this method might throw an
exception.

Example:

void readFile() throws IOException { }

35. Can we have multiple catch blocks?


Yes, you can have multiple catch blocks for different types of exceptions.
Always catch more specific exceptions first, and then general ones later.

Example:

try {

// risky code

} catch (IOException e) {

// handle IO issue

} catch (Exception e) {

// handle anything else

36. What is try-with-resources?


It’s a feature from Java 7 onwards that automatically closes resources (like files or DB
connections).
You don’t need a finally block for cleanup.

Example:

try (FileReader fr = new FileReader("[Link]")) {

// use file

37. Can we catch multiple exceptions in one block?


Yes, you can combine multiple exceptions using a pipe (|).
Example:

catch (IOException | SQLException e) {


9|Page

[Link]();

38. What is a Thread?


A thread is the smallest unit of execution in a program.
It allows multiple tasks to run at the same time, like downloading a file while showing progress
on screen.
Multithreading helps improve performance and responsiveness.

39. How do you create a Thread in Java?


There are two main ways:
1️⃣ By extending the Thread class
2️⃣ By implementing the Runnable interface

Example:

class MyThread extends Thread {

public void run() {

[Link]("Running...");

new MyThread().start();

or

new Thread(() -> [Link]("Running...")).start();

40. Difference between start() and run()?

 start() creates a new thread and then calls run() inside it (runs in parallel).

 run() just executes in the current thread (no multithreading).

41. What is synchronization in threads?


Synchronization means allowing only one thread at a time to access shared resources.
It prevents data inconsistency when multiple threads are updating the same variable.

Example:

synchronized void withdraw() { ... }

42. What is a Deadlock?


Deadlock happens when two threads are waiting for each other’s lock and both are stuck forever.
To avoid it, always acquire locks in the same order and release them properly.
10 | P a g e

43. What is Inter-thread Communication?


It’s when threads communicate with each other using methods like wait(), notify(), and
notifyAll().
These are used to coordinate actions between threads.

44. What is Thread Lifecycle?


A thread goes through these states:

 New

 Runnable

 Running

 Blocked/Waiting

 Terminated

You can say:

“Basically, it starts as new, then runnable, then running, and finally terminates after completing
its work.”

45. What is ExecutorService?


ExecutorService is part of Java’s concurrency framework — it manages a pool of threads.
Instead of creating threads manually, you submit tasks to it.

Example:

ExecutorService executor = [Link](3);

[Link](() -> [Link]("Task running"));

[Link]();

It makes thread management cleaner and more efficient.

46. What is Callable and Future?


Callable is like Runnable, but it returns a result and can throw exceptions.
When you submit a Callable to ExecutorService, it returns a Future object, which holds the
result.

Example:

Future<Integer> result = [Link](() -> 5 + 10);

[Link]([Link]());
11 | P a g e

47. What is the difference between wait() and sleep()?

 wait() → releases the lock and waits until notify() is called.

 sleep() → just pauses the thread for some time but keeps the lock.

48. What is the difference between synchronized block and synchronized method?

 Synchronized method locks the whole method.

 Synchronized block locks only a portion of code.


Using a block gives more control and better performance.

49. What is ThreadLocal in Java?


ThreadLocal provides each thread its own copy of a variable.
Useful when you want to avoid shared-state issues in multithreading.

Example:

ThreadLocal<Integer> counter = [Link](() -> 0);

50. What is volatile variable in threads?


volatile ensures the variable’s value is always read from main memory, not from a thread’s cache.
It helps in visibility — one thread’s update is visible to others immediately.

51. What is a Singleton Class?


A Singleton class is a design pattern where only one object of that class can exist in the entire
JVM.
Even if you try to create multiple objects, it always returns the same instance.
We usually use it for things like logging, configuration, or database connections.

52. How to Create a Singleton Class?


It must satisfy three conditions:

1. Private constructor — to stop others from creating objects directly.

2. A static instance variable — to hold the single object.

3. A public static method — to provide that instance.

Example:

public class Singleton {

private static Singleton instance = new Singleton();

private Singleton() { }

public static Singleton getInstance() {


12 | P a g e

return instance;

So if we call [Link]() multiple times, it always returns the same object.

🚀 Java 8+ Features (Spoken Version)

1. What are Lambda Expressions?


Lambda expressions are used to write short and clean code for functional interfaces.
They let you pass code as data — just like passing a method as an argument.

Instead of writing a whole anonymous class, we can use a lambda.

Example:

Runnable r = () -> [Link]("Running thread...");

They make code concise and easy to read.

2. What are Functional Interfaces?


A functional interface has only one abstract method.
They’re used with lambda expressions.
Examples: Runnable, Comparator, Predicate, Consumer.

We can mark them using @FunctionalInterface.

3. What is Optional?
Optional helps avoid NullPointerException.
It represents a value that might be present or not.

Example:

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

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

This prints “Default Name” if the value is null.

4. What are Method References?


Method references are a shorthand for lambda expressions when you already have an existing
method.

Example:
13 | P a g e

[Link]([Link]::println);

It’s just a cleaner way to call methods.

5. What are Stream APIs?


Streams help process collections in a functional way — like filtering, mapping, or reducing.
You can perform bulk operations easily and write less code.

Example:

[Link]()

.filter(n -> n % 2 == 0)

.forEach([Link]::println);

6. What are Default and Static methods in Interfaces?


Before Java 8, interfaces could only have abstract methods.
Now, they can have default and static methods.

 Default methods provide common behavior to all implementing classes.

 Static methods belong to the interface itself.

Example:

interface Vehicle {

default void start() { [Link]("Starting..."); }

static void service() { [Link]("Servicing..."); }

7. What is the Date and Time API in Java 8?


Java 8 introduced a new date/time package — [Link].
It’s much better than the old Date class.
Examples:
LocalDate, LocalTime, LocalDateTime, and ZonedDateTime.

Example:

LocalDate today = [Link]();

[Link](today);

8. What is Stream map() vs filter() vs reduce()?

 map() → transforms each element.

 filter() → filters elements based on condition.


14 | P a g e

 reduce() → combines all elements to produce a single result.

Example:

int sum = [Link]().reduce(0, (a, b) -> a + b);

9. What is CompletableFuture?
It’s part of Java 8’s concurrency API — used for asynchronous programming.
You can run tasks in the background and combine multiple async calls easily.

Example:

[Link](() -> [Link]("Running async task"));

🧺 Collections Framework (Spoken Version)

1. What is the Java Collections Framework?


The Java Collections Framework is a set of classes and interfaces that help us store and manage
groups of objects easily.
It provides data structures like List, Set, Map, and Queue, and utility classes to perform
operations like sorting or searching.
Basically, instead of writing your own data structure logic, Java gives it ready-made.

2. What’s the difference between Collection and Collections?

 Collection is an interface — it’s the parent for List, Set, and Queue.

 Collections is a utility class with static helper methods like sort(), reverse(), and shuffle().

So remember: Collection is an interface; Collections is a helper class.

3. What are the main interfaces in Collections?


There are four main ones:

 List is ordered, allows duplicates (e.g., ArrayList, LinkedList)

 Set is no duplicates (e.g., HashSet, TreeSet)

 Queue is follows FIFO order (e.g., PriorityQueue)

 Map is stores key–value pairs (e.g., HashMap, TreeMap)

4. Difference between ArrayList and LinkedList


15 | P a g e

 ArrayList uses a dynamic array internally — it’s faster for reading, but slower for
insert/delete.

 LinkedList uses nodes — it’s faster for insert/delete, but slower for reading.

So, if you mostly read data → use ArrayList.


If you add/remove often → use LinkedList.

5. Difference between ArrayList and Vector

 Vector is synchronized, so it’s thread-safe but slower.

 ArrayList is not synchronized, so it’s faster but not thread-safe.


In modern Java, we usually use ArrayList.

6. Can ArrayList store duplicate and null values?


Yes, absolutely.
ArrayList allows duplicate elements and also allows multiple null values.

7. How to sort a List in Java?


We can use:

[Link](list);

Or with lambdas:

[Link]((a, b) -> [Link](b));

8. Difference between HashSet, LinkedHashSet, and TreeSet

 HashSet → no order, no duplicates.

 LinkedHashSet → maintains insertion order, no duplicates.

 TreeSet → sorts elements automatically in natural order, no duplicates.

Use TreeSet when you need sorting, HashSet when order doesn’t matter.

9. How does HashSet work internally?


Internally, HashSet uses a HashMap.
Each element of the set is stored as a key in that HashMap with a dummy value.
That’s why keys (or elements) must be unique.

14. How does HashMap work internally?


HashMap stores data in buckets based on the hash code of keys.
When two keys have the same hash (collision), it uses a linked list or a balanced tree (from Java 8
onwards) to store them.
This gives fast lookups — usually O(1) time.
16 | P a g e

10. Difference between HashMap and Hashtable

 HashMap → not synchronized, faster, allows one null key and many null values.

 Hashtable → synchronized, slower, doesn’t allow null keys or values.

We usually prefer HashMap in modern Java applications.

11. Difference between HashMap and LinkedHashMap

 HashMap → unordered.

 LinkedHashMap → maintains insertion order.

So if order matters, go for LinkedHashMap.

12. Difference between HashMap and TreeMap

 HashMap → no ordering.

 TreeMap → sorts keys in natural order (alphabetical or numeric).

13. Can we have null keys in Map?

 HashMap allows one null key.

 Hashtable and TreeMap do not allow null keys.

15. What happens if hashCode() and equals() are not implemented properly?
Then HashMap and HashSet won’t behave correctly — duplicates may appear or some elements
may not be found.
These methods are used to compare keys and detect duplicates.

16. What is a Queue in Java?


A Queue follows the FIFO order — First In, First Out.
Example implementations: LinkedList, PriorityQueue.
We use it for scheduling or processing tasks in order.

17. What is PriorityQueue?


PriorityQueue is a special queue where elements are ordered based on priority, not insertion
order.
For example, smallest or highest value comes out first depending on the comparator.
17 | P a g e

18. What is ConcurrentHashMap?


ConcurrentHashMap is a thread-safe version of HashMap.
Multiple threads can read/write without locking the entire map.
Internally, it divides the map into smaller segments, so performance is better under concurrency.

19. Difference between synchronizedMap and ConcurrentHashMap

 synchronizedMap → locks the whole map for every operation (slow).

 ConcurrentHashMap → locks only small parts (fast).

That’s why we usually prefer ConcurrentHashMap in multi-threaded applications.

20. What is CopyOnWriteArrayList?


It’s a thread-safe version of ArrayList.
When modified, it creates a copy of the list, so reads are never blocked.
Best for scenarios with many reads and few writes.

21. How to make a collection thread-safe?


You can use:

List<String> safeList = [Link](list);

But for better performance, use concurrent collections like ConcurrentHashMap or


CopyOnWriteArrayList.

22. How to remove duplicates from a List?


Easiest way:

List<String> unique = new ArrayList<>(new HashSet<>(list));

It converts the list to a set (removing duplicates) and back to a list.

23. Comparator vs Comparable

 Comparable → defines natural ordering (inside the class itself).

 Comparator → defines custom sorting (outside the class).

Example:

[Link](list, (a, b) -> [Link]() - [Link]());

24. Difference between Fail-fast and Fail-safe iterators


18 | P a g e

 Fail-fast → throws ConcurrentModificationException if you modify the collection while


iterating (like in ArrayList, HashMap).

 Fail-safe → works on a copy, so safe to modify (like in ConcurrentHashMap,


CopyOnWriteArrayList).

🌱 Spring Boot — Spoken Version

1. What is Spring Boot?


Spring Boot is a framework that makes it easy to build and run Spring-based applications.
It removes a lot of manual configuration by providing auto-configuration, starter dependencies,
and an embedded server like Tomcat or Jetty.

In simple words:

“Spring Boot helps you create production-ready Spring applications quickly — you just write the
business logic, and Boot handles setup.”

2. What is Dependency Injection (DI)?


Dependency Injection means Spring automatically provides the required object instead of us
creating it manually using new.
This helps in writing loosely coupled and testable code.

Example:

@Autowired

private PaymentService service;

Here, Spring injects the PaymentService object automatically.

You can say:

“In DI, Spring manages the object creation — I just declare what I need, and it gives me that
dependency.”

3. Commonly used Spring Boot Annotations

Let’s go over the important ones in simple words 👇

🔹 @SpringBootApplication

It’s the main entry point of a Spring Boot app.


It combines three annotations — @Configuration, @EnableAutoConfiguration, and
@ComponentScan.

In simple words:

“This tells Spring Boot to start your app, auto-configure it, and scan for beans.”

Example:
19 | P a g e

@SpringBootApplication

public class PaymentApp {

public static void main(String[] args) {

[Link]([Link], args);

🔹 @RestController

Used to create REST APIs.


It combines @Controller and @ResponseBody, so whatever method returns, Spring
automatically converts it into JSON.

Example:

@RestController

@RequestMapping("/api/payments")

public class PaymentController {

@GetMapping("/{id}")

public Payment getPayment(@PathVariable int id) {

return new Payment(id, "SUCCESS");

In short:

“@RestController makes a class behave like an API endpoint that returns JSON.”

🔹 @Service

Used at the service layer where we write our main business logic.
Example:

@Service

public class PaymentService {

public String processPayment() {

return "Payment processed successfully!";

}
20 | P a g e

“@Service tells Spring — this is where the main logic lives.”

🔹 @Repository

Used at the data access layer — for database operations.


It also converts database exceptions into Spring’s DataAccessException.

Example:

@Repository

public class PaymentRepository {

public void save(Payment payment) { }

🔹 @Autowired

Used to inject dependencies automatically.


You don’t create objects manually — Spring provides them.

“Basically, I just declare what I need, and Spring gives it.”

🔹 @RequestMapping, @GetMapping, @PostMapping

These annotations are used to map URLs (API endpoints) to specific controller methods.
They tell Spring which method should handle which HTTP request.

Example:

@GetMapping("/users")

public List<User> getUsers() {

return [Link]();

 @GetMapping → handles HTTP GET requests (used for fetching data)

 @PostMapping → handles HTTP POST requests (used for saving or creating data)

 @RequestMapping → can be used at both class and method level to define base paths or
general mappings

4. Difference between @Component, @Service, and @Repository

All three are Spring-managed beans, but used at different layers:

 @Component → general-purpose bean (like utility classes)


21 | P a g e

 @Service → used in business logic layer

 @Repository → used in DAO layer (handles DB operations and converts SQL exceptions)

In short:

“All are beans, but their names help other developers understand the layer they belong to.”

5. What is [Link] or [Link] used for?


They are used to store configuration values — like server port, database credentials, or custom
properties.
It helps you change behavior without touching code.

Example:

[Link]=8081

[Link]=jdbc:mysql://localhost:3306/db

“Basically, all my app settings live here — easy to modify for different environments.”

6. What is Auto-Configuration in Spring Boot?


Auto-Configuration means Spring Boot automatically configures beans based on dependencies
you add.
For example, if you add spring-boot-starter-web, it automatically sets up Tomcat,
DispatcherServlet, etc.

“In simple terms, Boot configures things for me automatically — I don’t have to write extra XML
or Java config.”

7. What is the Bean Lifecycle in Spring?


The lifecycle includes:

1. Bean creation

2. Dependency injection

3. Initialization (@PostConstruct)

4. Ready to use

5. Destruction (@PreDestroy)

“Spring creates and manages my beans from start to end — I just define what they do.”

8. What is @Transactional?
@Transactional manages database transactions automatically.
If something fails midway, it rolls back all changes — ensuring data consistency.

“It saves me from partial updates — either everything succeeds or everything rolls back.”
22 | P a g e

9. What is AOP (Aspect-Oriented Programming)?


AOP helps separate cross-cutting concerns like logging, security, or transaction management.
Instead of writing the same code in multiple places, you write it once in an Aspect, and it applies
everywhere.

Example: logging before every service method runs.

“AOP basically helps me write cleaner code by moving common logic out of business methods.”

10. Difference between @Controller and @RestController

 @Controller → used for web pages (returns HTML, JSP).

 @RestController → used for REST APIs (returns JSON or XML).

“If I’m building APIs, I’ll always use @RestController.”

11. What are Spring Boot Starters?


Starters are pre-defined dependency bundles for common use cases.
For example:

 spring-boot-starter-web → for REST APIs

 spring-boot-starter-data-jpa → for JPA and Hibernate

“Starters save time — instead of adding 10 libraries manually, I just add one starter.”

12. What is Spring Boot Actuator?


Actuator gives production-ready monitoring endpoints — like checking app health, metrics, or
info.
Example: /actuator/health, /actuator/info

“It’s very helpful in real-time apps to monitor system status.”

13. How do you handle exceptions globally in Spring Boot?


We use @ControllerAdvice with @ExceptionHandler to handle exceptions in one centralized
place.

Example:

@ControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler([Link])

public ResponseEntity<String> handleAll(Exception ex) {


23 | P a g e

return [Link](500).body("Something went wrong!");

“It keeps my code clean — no need to write try-catch everywhere.”

14. What is CommandLineRunner in Spring Boot?


It’s an interface used to run code automatically when the application starts — for example,
initializing data or calling setup methods.

Example:

@Component

public class DataSetup implements CommandLineRunner {

public void run(String... args) {

[Link]("App started!");

“Basically, any startup logic goes inside CommandLineRunner.”

15. What is the use of @Value annotation?


@Value is used to inject values from properties files into variables.
Example:

@Value("${[Link]}")

private int port;

“It’s a shortcut to read config values directly in Java code.”

16. What is Spring Boot DevTools?


It’s a developer tool that automatically restarts the app when you change the code — helps
during development.

“Saves me time — no need to restart manually every time.”

17. What is Spring Boot Starter Parent?


It’s a parent project that provides default configurations for plugins, versions, and dependencies.
It helps maintain consistent builds across the project.

18. What is the difference between @ComponentScan and @EnableAutoConfiguration?


24 | P a g e

 @ComponentScan → tells Spring where to look for beans (scans your packages).

 @EnableAutoConfiguration → lets Spring Boot auto-configure beans based on


dependencies.

“One scans for my code, the other sets up required beans automatically.”

🌐 Microservices — Spoken Version

1. What are Microservices?


Microservices are small, independent services that work together to form a large application.
Each service focuses on a single business function — for example, payment, order, or user
management — and communicates with others through REST APIs or messaging systems.

You can say:

“In my project, we have around 60 microservices — each one handles a specific functionality like
transaction processing, card validation, or reporting.”

2. What are the advantages of Microservices?

 Independent deployment — we can deploy one service without affecting others.

 Scalability — we can scale only the service that needs more load.

 Fault isolation — if one service fails, others still keep running.

 Easier development — different teams can work on different services.

“Basically, microservices make applications more flexible, reliable, and easier to maintain.”

3. What is a REST API?


REST stands for Representational State Transfer — it’s a way for services to communicate over
HTTP.
We use HTTP methods like GET, POST, PUT, and DELETE to perform operations.
Data is usually shared in JSON format.

Example:

@GetMapping("/orders/{id}")

public Order getOrder(@PathVariable int id) { ... }

“In microservices, most services talk to each other using REST APIs.”

4. What is Feign Client?


Feign Client is used for service-to-service communication in microservices.
25 | P a g e

Instead of writing complex RestTemplate code, we just define an interface and Feign handles the
rest.

Example:

@FeignClient(name = "payment-service")

public interface PaymentClient {

@GetMapping("/payments/{id}")

Payment getPayment(@PathVariable Long id);

“Feign makes it super simple — I just call a method, and it internally makes a REST call to another
microservice.”

5. What is Eureka Server?


Eureka is a Service Registry.
All microservices register themselves with Eureka, and other services discover them using the
service name — not hardcoded URLs.

“In short, Eureka helps with service discovery — who’s running and where.”

Example:

 A Payment service registers as payment-service

 The Order service calls it using Feign: @FeignClient(name="payment-service")


No need to use actual host and port.

6. What is an API Gateway?


An API Gateway acts as a single entry point for all microservices.
It routes requests to the right service and can handle things like authentication, logging, load
balancing, and rate limiting.

Example:
We can use Spring Cloud Gateway or Netflix Zuul.

“In simple words, instead of calling 10 different services directly, the client just talks to one
gateway — it handles routing internally.”

7. What is the Circuit Breaker Pattern?


Circuit Breaker prevents a failure in one microservice from crashing others.
If a service is down, the circuit opens and returns a fallback response instead of repeatedly trying
the failed call.

Libraries like Resilience4j or Hystrix are used for this.

Example:
26 | P a g e

@CircuitBreaker(name = "paymentService", fallbackMethod = "fallbackPayment")

“It’s like an electric circuit — when a call fails too many times, the breaker trips and stops further
calls temporarily.”

8. What is Config Server?


Spring Cloud Config Server is used for centralized configuration management.
All microservices can read their configurations from one central place — usually a Git repository.

“It’s very useful — if I change a value in Git, all services automatically pick it up, no redeploy
needed.”

9. What is Distributed Tracing?


In a microservices system, a single request may pass through multiple services.
Distributed tracing helps track that request end-to-end.
We use tools like Zipkin or Sleuth to trace requests using unique trace IDs.

“It helps in debugging — we can see which service took how long and where failure occurred.”

10. What’s the difference between Monolithic and Microservices Architecture?

 Monolithic → one big application; tightly coupled; harder to scale.

 Microservices → multiple smaller apps; loosely coupled; easier to deploy and scale
independently.

“In monolithic, one bug can crash the whole app — in microservices, only one part fails.”

11. What is Idempotency in APIs?


Idempotency means calling the same API multiple times gives the same result.
Example: deleting the same record twice should not throw an error — it should just say, “Already
deleted.”

“It ensures APIs behave predictably, even with retries or failures.”

12. What is Synchronous vs Asynchronous Communication?

 Synchronous → one service waits for another’s response (like REST calls).

 Asynchronous → services don’t wait; they use message brokers like Kafka, RabbitMQ, or
AWS SQS.

“We use synchronous for real-time APIs, asynchronous for background processing or events.”

13. What is API Versioning?


API versioning helps us maintain backward compatibility when we change our API.
27 | P a g e

Example:
/api/v1/orders and /api/v2/orders

“It allows old clients to keep working even when new changes are rolled out.”

14. How do Microservices communicate with each other?


They can communicate using:

 REST APIs (synchronous)

 Message Queues like Kafka or RabbitMQ (asynchronous)

“In my project, we mostly use REST for real-time and Kafka for background jobs.”

15. How do you secure Microservices?


We use:

 OAuth2 / JWT tokens for authentication and authorization

 Spring Security for access control

 Sometimes, API Gateway handles authentication centrally.

“Basically, each request must have a valid token — no service trusts another blindly.”

16. How do you handle communication failures between services?


We use Retry mechanisms, Circuit Breaker, and Fallback responses using tools like Resilience4j.
This keeps the system stable even if one service is temporarily down.

17. What are common challenges in Microservices?

 Managing configurations

 Distributed logging and tracing

 Handling failures between services

 Database per service

 Versioning and backward compatibility

“The key is to design them loosely coupled and observable.”

You might also like