Top interview questions

 

1. Design Patterns Used in Spring Framework

Spring extensively uses various design patterns. Key ones:

PatternWhere Used in SpringExplanation
Dependency Injection (DI)Spring IoC ContainerInjects dependencies instead of creating them internally.
Singleton PatternSpring Bean default scopeSpring beans are singleton by default.
Factory Method PatternBeanFactory, ApplicationContextCreates bean instances.
Prototype PatternPrototype-scoped beansReturns new bean instance every time.
Proxy PatternAOP, Transaction ManagementCreates proxy objects for cross-cutting concerns.
Template Method PatternJdbcTemplate, RestTemplateDefines skeleton of process and allows custom logic.
Observer PatternSpring Events (ApplicationEventPublisher)Event listeners for communication.
Front Controller PatternDispatcherServlet in Spring MVCSingle entry point for HTTP requests.
Builder PatternBean definition & configurationsCreating complex bean definitions.

2. Spring Bean Lifecycle

Spring bean lifecycle steps:

  1. Instantiate — Object creation

  2. Populate Properties — Dependency Injection

  3. BeanNameAware / BeanFactoryAware / ApplicationContextAware (if implemented)

  4. BeanPostProcessor — postProcessBeforeInitialization()

  5. InitializingBean — afterPropertiesSet() OR custom init method

  6. BeanPostProcessor — postProcessAfterInitialization()

  7. Bean is Ready to Use

  8. Destroy Phase

    • DisposableBean.destroy() OR custom destroy method

3. Difference Between Singleton and Static Class

FeatureSingletonStatic Class
InstanceSingle object instanceNo object, directly accessed
Memory useCreated once lazily or eagerlyLoaded once in memory at JVM start
ImplementationDesign patternLanguage feature
InheritanceCan implement interfaces, inheritCannot extend classes or implement interfaces
Use caseShared state, resourcesUtility or helper methods

4. Multiple Inheritance in Java

  • Java does not support multiple inheritance with classes

    • To avoid diamond problem

  • Java supports multiple inheritance through interfaces

Example:

interface A { void show(); } interface B { void display(); } class C implements A, B { public void show() {} public void display() {} }



5. OOP Concepts in Java

ConceptExplanation
EncapsulationBinding data and methods (private variables + public getters/setters)
InheritanceAcquiring properties of parent class
PolymorphismSame interface, different behavior (method overloading & overriding)
AbstractionShowing essential details only (abstract classes & interfaces)

Short Interview-Friendly Summary Spring uses DI, Singleton, Factory, Proxy, Template, Observer patterns. Bean lifecycle: Instantiate → Set Properties → Init → Ready → Destroy Singleton vs Static: Singleton = object; static = no object Java supports multiple inheritance only via interfaces OOP pillars: Encapsulation, Inheritance, Polymorphism, Abstraction

1. What version of Java do you know?

I work with Java 8+, including features like Streams, Lambdas, Optional, CompletableFuture, and Functional interfaces.
Also familiar with Java 11/21 enhancements like var keyword, records, switch expressions, text blocks, and module system.

2. Java - What is Interface and Abstract? When do you use one over the other?

FeatureInterfaceAbstract Class
MethodsAbstract methods + default + staticAbstract + concrete methods
Variablespublic static finalInstance variables allowed
InheritanceMultiple inheritanceSingle inheritance
Use caseCapabilities/contractShared base behavior + state

3. Difference between StringBuilder and StringBuffer

StringBuilderStringBuffer
Not thread-safeThread-safe (synchronized)
FasterSlightly slower
Use in single-threaded context



4. Java - What is Message Digest?

Message digest = fixed-length hash value created from input data, used for integrity.

Example algorithms: SHA-256, SHA-512, MD5 (not secure)

Used in:

  • Password hashing

  • Digital signatures

  • Data integrity checks

Use in multi-threaded context





7. Spring - How would you create an API? What layers would you use?

Layers in Spring Boot API:

LayerPurpose
ControllerHandles HTTP requests
ServiceBusiness logic
Repository/DAODB access (JPA/Hibernate)
Model/EntityDefines data structures

8. SQL - HAVING keyword

  • Used with GROUP BY

  • Filters aggregated results (after grouping)

SELECT dept, COUNT(*) FROM employees GROUP BY dept HAVING COUNT(*) > 5;
14. Docker - what can you tell me about Docker?

Docker = containerization platform

It packages app + dependencies into lightweight containers. Benefits: Consistency across environments Fast deployment Isolation Works great with microservices

36. Describe the differences between HashMap, LinkedHashMap, and TreeMap.

Here's a summary of the terms:

  • HashMap: Unordered, allows null keys and values, O(1) average time complexity for basic operations.
  • LinkedHashMap: Maintains insertion order (or access order), allows null keys and values, slightly slower than HashMap.
  • TreeMap: Sorted by keys, doesn't allow null keys, O(log n) time complexity for basic operations

37. What is the purpose of the transient keyword in Java?

I’d like to answer this question with an example. Consider this class:

public class User implements Serializable { private String username; private transient String password; }

In this case, when you serialize a User object, the password won’t be included in the serialized data because it is transient. So, this keyword is used to indicate fields that shouldn't be serialized when the object is converted to a byte stream. 56 Java Interview Questions And Answers For All Levels | DataCamp


43. Explain the difference between synchronized collections and concurrent collections in Java.

  • Synchronized collections: Found in java.util.Collections (e.g., Collections.synchronizedList). They are thread-safe but achieve this by synchronizing all methods, which can cause contention in multi-threaded environments.
  • Concurrent collections: Found in java.util.concurrent (e.g., ConcurrentHashMap). They allow concurrent access by multiple threads using more fine-grained locks or lock-free algorithms, improving performance in concurrent environments.

55. How does the CompletableFuture class improve asynchronous programming in Java?

CompletableFuture provides a more flexible and functional approach to asynchronous programming compared to Future. It allows chaining tasks with methods like .thenApply(), .thenAccept(), and .thenCompose().

CompletableFuture.supplyAsync(() -> fetchData()) .thenApply(data -> processData(data)) .thenAccept(result -> System.out.println("Result: " + result));


Comments

Popular posts from this blog

Archunit test

Hexagonal Architecture

visitor design pattern