Mastering Core Java and Spring Framework Fundamentals
System DesignModel answerLast updated
A comprehensive technical overview of essential Java language mechanics, concurrency models, SOLID architecture, and Spring Framework core concepts for backend engineers.
During a technical screen for a modern Java and Spring backend development position, you are asked to demonstrate deep foundational knowledge across core Java features, concurrency primitives, design practices, and framework architecture.
Provide clear, technically precise answers to the following 8 core topics:
-
Sequential Data Structures
- Compare
ArrayListvsLinkedListregarding underlying implementations, complexity for operations (indexing, insertion, deletion), and hardware efficiency considerations.
- Compare
-
Object-Oriented Design (SOLID)
- Detail each letter of the SOLID acronym and provide a concrete practical scenario illustrating each principle in application design.
-
Key-Value Collections and Concurrent Maps
- Contrast
HashtableandHashSetregarding key/value semantics, inner mechanisms, and thread safety. - Explain how
ConcurrentHashMapoperates internally under Java 8+, how it differs fromHashMapandHashtable, and when to apply it.
- Contrast
-
Immutability and Character Sequences
- Compare
String,StringBuilder, andStringBuffer(mutability, synchronization, typical use cases). - Define object immutability, detail its key advantages, and provide a code implementation demonstrating how to build an immutable class safely in Java.
- Compare
-
Java Concurrency Primitives
- Describe the memory model semantics of the
volatilemodifier, including its guarantees and limits. - Explain intrinsic locking via
synchronized, its execution guarantees, overhead, and alternatives. - Describe the
java.util.concurrent.atomicpackage, detailing how lock-free algorithms work using CAS mechanism.
- Describe the memory model semantics of the
-
Robust Exception Handling
- Differentiate checked vs. unchecked exceptions, detailing when each category is appropriate.
- Outline enterprise best practices for handling exceptions across application boundaries.
-
Spring Architecture & Dependency Management
- Explain Inversion of Control (IoC) and Dependency Injection (DI) with code/conceptual examples.
- Describe Aspect-Oriented Programming (AOP) in Spring and common cross-cutting concerns handled by it.
- Explain Spring bean definition, life cycle, and component stereotypes (
@Component,@Service,@Repository). - Define core annotations such as
@Autowired,@Qualifier,@Configuration,@Bean, and@Transactional.
-
Functional Collection Processing (Stream API)
- Explain the execution model of Java Streams (lazy evaluation, pipelines) and demonstrate key operations (
filter,map,collect,groupingBy).
- Explain the execution model of Java Streams (lazy evaluation, pipelines) and demonstrate key operations (
Hints
Hint 1
Focus on memory access patterns (like CPU cache lines) when comparing data structures.
Hint 2
When explaining ConcurrentHashMap, mention the lock-free read path vs fine-grained node locks for writes.
Hint 3
Make sure your custom immutable class performs defensive copying for non-primitive, mutable field inputs.
Hint 4
For Spring dependency injection, prefer constructor injection over field injection and explain why.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. ArrayList vs. LinkedList
| Attribute | ArrayList | LinkedList |
|---|---|---|
| Underlying Data Structure | Dynamic array (grows by ~50% when full). | Doubly linked list (nodes pointing to next/prev). |
Random Access (get(i)) | $O(1)$ continuous memory access. | $O(n)$ must traverse nodes from head/tail. |
Append (add) | Amortized $O(1)$; occasional $O(n)$ re-allocation cost. | $O(1)$ update of tail pointer. |
| Middle Insert/Delete | $O(n)$ due to array element memory shifting. | $O(1)$ node pointer update once position is reached (reaching position is $O(n)$). |
| Memory Locality & Overhead | Low memory overhead; sequential storage maximizes CPU L1/L2 cache hits. | Node wrapper overhead (24 bytes per node in 64-bit JVM); random memory allocation hurts CPU cache locality. |
Practical Choice: ArrayList is almost always preferred due to CPU cache efficiency. For FIFO/LIFO queues, ArrayDeque is preferred over LinkedList.
2. SOLID Design Principles
- Single Responsibility Principle (SRP): A class should have only one reason to change.
- Example: Decouple an
OrderProcessor(business calculation logic) from anInvoicePdfGenerator(formatting and rendering).
- Example: Decouple an
- Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
- Example: Use a
PaymentProcessorinterface with implementations likeCreditCardProcessorandPayPalProcessorinstead of using complexswitch-casestatements in a single class.
- Example: Use a
- Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types without altering program correctness.
- Example: Avoid creating a
Squaresubclass extending aRectangleif modifyingSquare.setWidth()unexpectedly changes the height, breaking invariant expectations.
- Example: Avoid creating a
- Interface Segregation Principle (ISP): Prefer small, specific interfaces over monolithic ones.
- Example: Split a generic
DocumentManagerinterface into fine-grainedReadable,Writable, andPrintableinterfaces so consumers only implement methods they consume.
- Example: Split a generic
- Dependency Inversion Principle (DIP): High-level modules should depend on abstractions, not concrete implementations.
- Example:
UserServicedepends on aNotificationSenderinterface, not a concreteSendGridEmailClient.
- Example:
3. Hash Collections & Concurrency
Hashtable vs. HashSet
Hashtable: A legacy, thread-safe key-value implementation. Every method usessynchronizedon the entire object instance. Null keys and values are strictly prohibited.HashSet: A collection storing distinct elements. It is internally backed by aHashMap(where elements act as map keys, mapped to a static dummy object value). It allows a singlenullelement, is non-thread-safe, and relies on correct implementation ofequals()andhashCode().
ConcurrentHashMap Mechanics
- Design & Lock Strategy: Under Java 8+, read operations are completely lock-free using
volatilereads. Writes acquire fine-grained locks only on the bucket head node (synchronizedon the specific bucket node) or use atomic Compare-And-Swap (CAS) operations if the bucket is empty. (Java 7 used Segment-level locking). - Null Values: Disallows
nullkeys or values to eliminate ambiguity between a key mapping tonullversus a missing key during concurrent reads. - Iterators: Offers weakly consistent iterators that reflect states at point of creation without throwing
ConcurrentModificationException. - When to use: Multi-threaded caching, high-concurrency counters, and global lookup registries.
4. Strings & Immutability
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread Safety | Thread-safe by design | Not thread-safe | Thread-safe (synchronized methods) |
| Primary Use | General identifiers, constants | Local string construction/loops | Legacy shared buffer modification |
Designing an Immutable Class
Immutable objects guarantee safety across threads, safe usage as HashMap keys, and predictable behaviour.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// 1. Declare class final to prevent subclass overriding
public final class UserProfile {
// 2. Make fields private and final
private final String username;
private final List<String> permissions;
public UserProfile(String username, List<String> permissions) {
this.username = username;
// 3. Perform defensive copy on mutable input references
if (permissions == null) {
this.permissions = Collections.emptyList();
} else {
this.permissions = List.copyOf(permissions); // Unmodifiable defensive copy
}
}
public String getUsername() {
return username; // Strings are immutable, safe to expose
}
public List<String> getPermissions() {
// 4. Return unmodifiable view or defensive copy
return permissions;
}
}
Note: Java 16+ record constructs implicitly handle shallow immutability, though mutable reference fields still require manual defensive copies in constructor bodies.
5. Concurrency Primitives
volatile Modifier
- Guarantees: Direct reading and writing to main memory (bypassing CPU registers and L1-L3 caches) ensuring visibility across threads. Establishes a happens-before ordering boundary prohibiting instruction reordering across the write boundary.
- Limitations: Does not offer atomicity. Multi-step operations like
count++(read-modify-write) are prone to race conditions. - Common Applications: Flag variables (e.g., volatile
boolean shutdownRequested) or lock-free state publishing.
Intrinsic Locking (synchronized)
- Behavior: Obtains the intrinsic monitor of an object instance or class object, enforcing mutual exclusion (only one thread executes the block at a time) while flushing updates to main memory on release.
- Trade-offs: Simple to write, but blocked threads enter context switching states (heavyweight kernel transitions). Risk of deadlocks if locking order across resources is inconsistent.
- Alternatives:
ReentrantLockprovides non-blocking acquisition attempts (tryLock), timed lock attempts, and multi-condition variables.
Atomics (java.util.concurrent.atomic)
- Implements lock-free concurrent updates relying on CPU-level atomic instructions such as Compare-And-Swap (CAS).
- Operation (e.g.,
AtomicInteger): A thread reads value $V$, calculates target value $V + 1$, and invokes hardware instructionCAS(expectedValue=V, updateValue=V+1). If another thread altered $V$ in the interim, the operation fails, and the loop retries until success. - Trade-offs: Excellent throughput under low-to-moderate contention. High thread contention leads to excessive CAS CPU spinning (in such cases
LongAdderis preferable).
6. Exception Handling Best Practices
Checked vs. Unchecked Exceptions
- Checked Exceptions: Subclasses of
Exception(excludingRuntimeException). The compiler enforces explicit handling viatry-catchor declaration viathrows. Intended for recoverable operational issues outside direct application control (e.g.,FileNotFoundException). - Unchecked Exceptions: Subclasses of
RuntimeException. Unenforced by the compiler. Represent unexpected programming bugs, invalid arguments, or non-recoverable system states (e.g.,NullPointerException,IllegalArgumentException).
Application Design Guidelines
- Avoid empty
catchblocks or swallowing exceptions silently. - Preserve original causal stack traces when wrapping domain exceptions:
throw new OrderProcessingException("Payment gateway failure", causeException); - Utilize modern
try-with-resourcesstatements forAutoCloseablesystem resources (file streams, database connections). - Centralize domain-level REST exception translation in Spring controllers using
@RestControllerAdviceand@ExceptionHandlermethods instead of fragmented catches.
7. Spring Core Framework & Dependency Injection
Inversion of Control (IoC) & Dependency Injection (DI)
- IoC: Architectural pattern where object creation, configuration, and execution lifecycles are inverted from explicit application logic to a central framework container (
ApplicationContext). - DI: Concrete mechanism of IoC where dependency instances are passed into a dependent component (preferably via constructor injection):
@Service
public class OrderService {
private final PaymentGateway paymentGateway;
// Constructor Injection (Recommended: enables immutability & simplified unit testing)
public void OrderService(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}
Aspect-Oriented Programming (AOP)
Enables modularization of cross-cutting concerns separate from core business code.
- Uses Aspects containing Advice (actions run
@Before,@After, or@Around) attached to specified execution Join Points matched by Pointcuts. - Common use cases: Declarative transaction management (
@Transactional), security authorization checks, audit logging, and performance metric tracking.
Component Stereotypes & Core Annotations
@Component: Generic root annotation designating a Spring-managed bean.@Service: Specialist stereotype marking business logic layers.@Repository: Stereotype for persistence components; automatically translates DB vendor exceptions into Spring's unifiedDataAccessExceptionhierarchy.@Controller/@RestController: Defines HTTP request handler components (the latter implicitly appends@ResponseBodyreturn mapping).@Autowired/@Qualifier: Directs automatic dependency injection.@Qualifierresolves ambiguities when multiple beans implement the target type.@Configuration&@Bean: Java-based configuration defining explicit bean creation methods inside a factory configuration class.@Transactional: Wraps method execution inside database transaction boundaries utilizing Spring AOP proxies.
8. Java Stream API
Streams process data collections functionally using lazy evaluation. A pipeline consists of a data source, zero or more intermediate operations (returning transformed streams lazily), and one terminal operation (triggering pipeline evaluation).
import java.util.*;
import java.util.stream.Collectors;
record Employee(String department, String name, double salary) {}
public class StreamExamples {
public static void main(List<Employee> employees) {
// 1. Filter, Map, and Collect to List
List<String> highEarners = employees.stream()
.filter(e -> e.salary() > 100_000)
.map(Employee::name)
.collect(Collectors.toList());
// 2. Grouping and Aggregation (Average salary per department)
Map<String, Double> avgSalaryByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
Collectors.averagingDouble(Employee::salary)
));
}
}