🔤 Arc A — Java Fundamentals
int and Integer?int is a primitive type that holds a 32-bit signed integer value directly on the stack — it cannot be null and has no methods. Integer is its wrapper class in java.lang that boxes the primitive into an object on the heap, can be null, and provides utility methods like Integer.parseInt(), Integer.MAX_VALUE, and compareTo(). Java automatically converts between the two via autoboxing and unboxing, but watch out — unboxing a null Integer throws a NullPointerException.
StringBuilder over String concatenation?Use StringBuilder when building a string in a loop or appending many pieces together. Each + on a String creates a new immutable String object in memory, because String is immutable — in a loop of n iterations this allocates O(n²) bytes of garbage. StringBuilder maintains a mutable char buffer and resizes it as needed, keeping allocation O(n). The Java compiler automatically optimises a single-line "a" + "b" + "c" to a StringBuilder, but it cannot do this across loop iterations.
final mean on a variable, method, and class?On a variable, final means it can only be assigned once — it is a constant reference (note: the object it points to can still be mutated unless it is itself immutable). On a method, final prevents subclasses from overriding it, useful for security-critical or template-method implementations. On a class, final prevents the class from being subclassed at all — String, Integer, and all primitive wrapper classes are final for immutability and security reasons.
Java is strictly pass-by-value — always. For primitives, the actual value is copied. For objects, the reference (memory address) is copied, not the object itself. This means a method can mutate the state of the object the caller passed (because both caller and method hold a reference to the same heap object), but reassigning the parameter inside the method to a new object does not affect the caller's variable. The confusion arises because "passing a reference by value" looks similar to pass-by-reference in other languages, but they are different concepts.
== and .equals() for Strings?== compares object identity — it checks whether two references point to the exact same object in memory. .equals() compares content — for String it checks character-by-character equality. String literals are interned by the JVM into a string pool, so "hello" == "hello" is often true, but new String("hello") == new String("hello") is false because each new creates a distinct heap object. Always use .equals() (or Objects.equals() for null-safety) to compare string values.
NullPointerException?Autoboxing is the automatic conversion the compiler inserts between a primitive (int, double, etc.) and its wrapper object (Integer, Double, etc.) and vice versa. It causes a NullPointerException during unboxing: if you have an Integer variable that is null and then assign it to an int (or use it in an arithmetic expression), Java tries to call .intValue() on null and throws. Classic traps: a Map<String, Integer> returning null for a missing key then unboxed into an int, or a ternary condition ? nullInteger : primitiveInt.
Each thread has its own stack — a LIFO structure that stores stack frames containing local variables, method parameters, and return addresses. Stack memory is automatically reclaimed when a method returns. The heap is a shared area where all objects live; it is divided into Young Generation (Eden + Survivor spaces), Old Generation (Tenured), and (in Java 8+) Metaspace for class metadata. The Garbage Collector periodically traces live objects from GC roots (stack references, static fields, JNI) and reclaims unreachable objects. Minor GCs collect the Young Gen (fast, frequent); Major/Full GCs collect the Old Gen (slower, less frequent). OutOfMemoryError occurs when the heap is exhausted; StackOverflowError when the stack is exhausted (typically from infinite recursion).
Checked exceptions extend Exception (but not RuntimeException) and must be declared in the method signature with throws or handled with try-catch — the compiler enforces this. They represent recoverable conditions the caller should plan for (IOException, SQLException). Unchecked exceptions extend RuntimeException (or Error) and are not enforced by the compiler — they represent programming bugs (NullPointerException, IllegalArgumentException) or unrecoverable JVM errors (OutOfMemoryError). Modern Java (and Spring) prefers unchecked exceptions to avoid checked exception boilerplate, wrapping infrastructure checked exceptions in runtime ones (DataAccessException).
🧩 Arc B — OOP
An interface defines a contract — methods a class must implement — with no instance state. Since Java 8, interfaces can have default and static methods, and since Java 9, private helper methods. A class can implement multiple interfaces. An abstract class can have instance fields, constructors, and concrete methods alongside abstract ones; it is used when you want to share implementation across related classes. A class can only extend one abstract class. Prefer interfaces when you want to define a contract that unrelated classes can implement; prefer abstract classes when you want to provide a common base implementation.
@Override do and why is it important?@Override is a compiler annotation that instructs the compiler to verify the annotated method actually overrides a method in a superclass or implements a method from an interface. If the signature does not match (e.g., a typo in the method name or wrong parameter type), the compiler emits an error rather than silently creating a new overloaded method that never gets called. It documents intent, prevents subtle bugs from signature mismatches, and makes the code easier to understand during code reviews.
record and when should you use one instead of a class?Introduced in Java 16, a record is a concise way to declare an immutable data carrier. The compiler automatically generates a canonical constructor, private final fields, public accessor methods, and correct equals(), hashCode(), and toString() implementations. Use a record instead of a class when the type's sole purpose is to hold data (DTOs, value objects, response payloads, test fixtures) and immutability is desired. Avoid records when you need inheritance (records are implicitly final), mutable fields, or custom JPA-managed entities.
Polymorphism means "many forms" — the same method call behaves differently depending on the actual runtime type of the object. In Java this is achieved via method overriding (runtime polymorphism). For example, a PaymentGateway interface has a processPayment(double amount) method. Both RazorpayGateway and StripeGateway implement it differently. Code that holds a PaymentGateway reference can call gateway.processPayment(1000) without knowing the concrete type — at runtime the JVM dispatches to the correct implementation via the virtual method table. This enables the Open/Closed Principle: add a new gateway without touching existing code.
The Liskov Substitution Principle (LSP) — the "L" in SOLID — states that objects of a subclass must be substitutable for objects of their superclass without breaking the program's correctness. In practice: a subclass should not strengthen preconditions (accept less), weaken postconditions (guarantee less), or throw exceptions that the superclass does not. The classic violation is a Square subclass of Rectangle that overrides setWidth and setHeight to always keep them equal — code that expects a Rectangle and changes width and height independently will get surprising behaviour from a Square. When LSP is violated, prefer composition over inheritance.
Java allows a class to implement multiple interfaces, but restricts class-level inheritance to a single parent to avoid the diamond problem (ambiguity about which parent's implementation to inherit). With Java 8 default methods, two interfaces can both provide an implementation for the same method signature — if a class implements both, the compiler forces the class to explicitly override the method and choose (or combine) the implementations using InterfaceA.super.method() syntax. This makes the resolution explicit and unambiguous. If one interface extends the other, the more specific one wins. This approach lets Java gain most benefits of multiple inheritance without the brittleness of full multiple class inheritance.
Inheritance ("is-a") means a subclass extends a parent, reusing and potentially overriding its behaviour — it creates tight coupling because the subclass depends on the parent's internals and any change to the parent can break the subclass. Composition ("has-a") means a class holds references to collaborators and delegates behaviour to them — it is more flexible, easier to test (inject mocks), and avoids fragile base class problems. Prefer inheritance when there is a genuine is-a relationship and you need polymorphic substitution (e.g., AdminUser extends User). Prefer composition for code reuse without a strong is-a relationship (e.g., a NotificationService that has an EmailSender and an SmsSender). GoF's rule of thumb: "favour composition over inheritance."
🌊 Arc C — Functional & Modern Java
Intermediate operations (filter, map, flatMap, sorted, distinct) are lazy — they return a new Stream and do not execute until a terminal operation is called. They simply build up a pipeline of transformations. Terminal operations (collect, count, forEach, reduce, findFirst, anyMatch) are eager — they trigger the entire pipeline to execute and produce a result or side effect. A stream is consumed after a terminal operation and cannot be reused. This laziness enables short-circuit optimisations: findFirst() stops processing as soon as one element passes all intermediate filters.
Optional.orElse() do vs Optional.orElseGet()?Both return the wrapped value if present, or a default if empty — but they differ in when the default is evaluated. orElse(default) evaluates the default expression eagerly, even if the Optional is not empty. orElseGet(supplier) takes a Supplier and evaluates it lazily, only when the Optional is empty. This matters for performance when the default involves an expensive computation (a DB query, object construction): always use orElseGet(() -> expensiveCall()) in those cases. For simple constant defaults (orElse("")) the difference is negligible.
A functional interface has exactly one abstract method (it may have multiple default or static methods). The @FunctionalInterface annotation enforces this at compile time. They are the target types for lambda expressions and method references. Three important built-in ones from java.util.function: Predicate<T> — takes a T, returns boolean (used in filter); Function<T,R> — takes a T, returns R (used in map); Consumer<T> — takes a T, returns void (used in forEach). Others worth knowing: Supplier<T>, BiFunction<T,U,R>, UnaryOperator<T>.
groupingBy work under the hood?Collectors.groupingBy(classifier) is a mutable reduction that partitions stream elements into a Map<K, List<V>>. Internally it works like iterating the stream and calling map.computeIfAbsent(classifier.apply(element), k -> new ArrayList<>()).add(element) for each element. When you supply a downstream collector (e.g., Collectors.summingDouble(Invoice::amount)), the default toList() accumulator is replaced by that collector for each group. The result map is a HashMap by default; use groupingBy(classifier, TreeMap::new, downstream) if you need a sorted map. The operation is O(n) in time.
Streams are lazy so the JVM can optimise the pipeline — specifically, it can short-circuit and avoid processing elements that are not needed. Consider: employees.stream().filter(e -> e.dept().equals("Engineering")).map(Employee::name).findFirst(). Without laziness the filter would process all employees, then map all matching ones, then return the first. With laziness, as soon as the first match passes the filter and the map, findFirst() returns immediately — no remaining elements are ever touched. For a list of 10,000 employees where the first Engineering employee is at index 3, laziness avoids processing 9,997 elements.
Try-with-resources (Java 7+) is a try statement that automatically closes one or more resources when the block exits — whether normally or via an exception. The resource must implement java.lang.AutoCloseable (or its subinterface Closeable), which requires a close() method. The JVM calls close() in reverse order of declaration at the end of the block, before any catch or finally. It eliminates the error-prone boilerplate of finally { if (resource != null) resource.close(); }. If both the body and close() throw, the close exception is suppressed (accessible via Throwable.getSuppressed()) and the original exception propagates.
reduce and collectreduce is a functional fold — it combines stream elements immutably using an associative binary operator: (accumulator, element) -> newAccumulator. Each step produces a new value; there is no shared mutable container. It is ideal for computing a single scalar (sum, product, min). collect is a mutable reduction — it accumulates elements into a mutable container (List, Map, StringBuilder) using a Collector that provides a supplier, accumulator, and combiner. collect is more efficient when building collections because it reuses the same container object rather than creating a new one on every combination step. Use reduce for scalar results; use collect for building data structures.
parallelStream() and when should you avoid it?Use parallelStream() when: the data set is large (tens of thousands of elements or more), each element's processing is CPU-bound, stateless, and independent of others, and the source supports efficient splitting (ArrayList and arrays split O(1); LinkedList splits poorly). Avoid it when: elements must be processed in encounter order (use forEachOrdered() only as a last resort — it defeats parallelism); lambdas have shared mutable state (race conditions); the per-element work is tiny or I/O-bound (thread overhead dominates); or you are in a container like Spring Boot where the common ForkJoinPool is shared across many requests. Always benchmark; the overhead of splitting and merging often exceeds the benefit for typical in-memory lists under ~10,000 elements.
🌱 Arc D — Spring Boot
@SpringBootApplication do?@SpringBootApplication is a convenience meta-annotation that combines three annotations: @Configuration (marks the class as a source of bean definitions), @EnableAutoConfiguration (tells Spring Boot to automatically configure beans based on jars on the classpath — for example, configuring a DataSource if H2 is present), and @ComponentScan (scans the current package and sub-packages for Spring components). Placing it on your main class bootstraps the entire application context and enables Spring Boot's opinionated auto-configuration.
@RestController and @Controller?@Controller is a stereotype annotation that marks a class as a Spring MVC controller; by default its methods return view names resolved by a ViewResolver (for server-side HTML rendering with Thymeleaf, Freemarker, etc.). @RestController is a meta-annotation combining @Controller and @ResponseBody, which tells Spring to serialise the return value directly to the HTTP response body (as JSON or XML) rather than resolving a view. For REST APIs always use @RestController; use @Controller only when rendering server-side templates.
Spring Boot's @EnableAutoConfiguration reads entries from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (Spring Boot 3.x; previously spring.factories). Each listed class is a @Configuration class annotated with conditions (@ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, etc.) that check whether certain classes are on the classpath, beans are absent, or properties are set. Only the conditions that match result in beans being registered. For example, DataSourceAutoConfiguration creates a DataSource bean only if a JDBC driver class is on the classpath and no DataSource bean is already defined by the user. You can exclude specific auto-configurations with @SpringBootApplication(exclude = ...).
Constructor injection means dependencies are provided via the class constructor rather than via @Autowired on a field. It is preferred because: (1) dependencies are explicit and mandatory — the object cannot be created in an invalid state; (2) the class is easily unit-testable without a Spring context — just call new MyService(mockRepo); (3) the field can be final, enforcing immutability; (4) circular dependencies are detected at startup rather than at runtime. Field injection (@Autowired private Repo repo;) hides dependencies, requires reflection to inject (breaking encapsulation), and makes the class hard to test outside Spring. Spring Team recommends constructor injection, and Spring will auto-wire a single-constructor class without an explicit @Autowired.
@Valid work with @ExceptionHandler?When a controller method parameter is annotated with @Valid (or @Validated), Spring triggers Bean Validation (Hibernate Validator) on the incoming request body before the method body executes. If any constraint (@NotBlank, @Size, @Email, etc.) is violated, Spring throws a MethodArgumentNotValidException and the controller method is never called. You handle this centrally in a @RestControllerAdvice class with an @ExceptionHandler(MethodArgumentNotValidException.class) method that extracts the field errors from the exception's BindingResult and returns a structured 400 Bad Request response. This keeps validation logic out of service code and provides consistent error responses across the API.
application.properties and application-dev.properties?application.properties contains the base configuration loaded for every environment. application-dev.properties is a profile-specific file that is loaded additionally when the dev Spring profile is active (set via SPRING_PROFILES_ACTIVE=dev or --spring.profiles.active=dev). Profile-specific values override base values for the same key. This lets you share common config (app name, logging format, pagination defaults) in the base file while keeping environment-specific settings (database URL, Ollama host, debug flags) in profile files. Best practice: commit application.properties and application-dev.properties with safe defaults; put secrets in environment variables or a secrets manager, never in committed files.
SecurityFilterChain work?Spring Security intercepts HTTP requests through a chain of servlet filters registered in the FilterChainProxy. The SecurityFilterChain bean — defined in your @Configuration using the HttpSecurity DSL — configures which filters are active and in what order. Key filters include: UsernamePasswordAuthenticationFilter (handles login form), BearerTokenAuthenticationFilter (validates JWT), ExceptionTranslationFilter (converts auth exceptions into 401/403 responses), and FilterSecurityInterceptor (enforces access rules on URLs). When a request arrives, it passes sequentially through each filter; any filter can reject the request or store authentication in the SecurityContextHolder. You can define multiple SecurityFilterChain beans with different securityMatcher patterns (e.g., one for /api/**, another for the admin console).
Spring bean lifecycle: (1) Instantiation — Spring calls the constructor (or factory method). (2) Property population — dependencies are injected. (3) BeanNameAware / BeanFactoryAware callbacks — if the bean implements these interfaces, Spring calls the corresponding setters. (4) BeanPostProcessor.postProcessBeforeInitialization — e.g., @Autowired and AOP proxying infrastructure runs here. (5) Init callbacks — @PostConstruct method, then InitializingBean.afterPropertiesSet(), then initMethod from @Bean. (6) BeanPostProcessor.postProcessAfterInitialization — AOP proxies are typically created here. (7) Bean is ready for use. (8) On context shutdown: Destroy callbacks — @PreDestroy, then DisposableBean.destroy(), then destroyMethod. Singleton beans go through the full lifecycle once; prototype beans are not tracked after creation so destroy callbacks are not called.
@Component, @Service, @Repository, and @Controller?All four are specialisations of @Component — they all register a Spring-managed bean and are detected by component scanning. The differences are semantic and infrastructural: @Component is the generic stereotype. @Controller marks web layer beans; Spring MVC dispatch infrastructure recognises it. @Service marks business logic layer beans; it currently adds no extra behaviour but signals intent and allows future AOP advice targeting services. @Repository marks persistence layer beans and, crucially, enables Spring's PersistenceExceptionTranslationPostProcessor, which automatically translates JDBC/JPA exceptions into Spring's DataAccessException hierarchy — providing a consistent, unchecked exception abstraction across different ORM frameworks. Use each annotation at the appropriate layer to communicate architecture intent clearly.
🗄️ Arc E — Databases & JPA
JPA (Jakarta Persistence API) is a specification — a set of interfaces and annotations defined by the Jakarta EE standard that describes how Java objects should be mapped to relational database tables (ORM). It defines concepts like @Entity, @Id, EntityManager, JPQL, and transaction semantics, but contains no actual implementation code. Hibernate is the most popular JPA implementation — it provides the actual SQL generation, connection pooling integration, caching, and query execution. Spring Boot auto-configures Hibernate as the default JPA provider when spring-boot-starter-data-jpa is on the classpath. Spring Data JPA adds another layer on top, generating repository implementations from interface method names.
@Transactional do?@Transactional tells Spring to wrap the annotated method (or all methods of the annotated class) in a database transaction. Spring uses AOP to create a proxy: before the method executes, it opens (or joins) a transaction; after the method returns normally, it commits; if a runtime exception is thrown, it rolls back. The annotation also controls propagation (REQUIRED by default — join existing or create new), isolation level, timeout, and read-only hints. Placing it on the service layer keeps transaction boundaries in business logic rather than in controllers or repositories.
The N+1 problem occurs when fetching a list of N entities triggers N additional queries to load a related association. For example, loading 100 Order entities each with a Customer lazily: one query fetches orders, then 100 separate queries each fetch one customer — 101 queries total. Fixes: (1) @EntityGraph or JOIN FETCH in JPQL to eagerly load the association in a single query; (2) use a Spring Data JPA @Query with JOIN FETCH; (3) switch to FetchType.EAGER (use carefully — it always loads the association); (4) use Hibernate's batch fetching (@BatchSize) to load associations in batches. The N+1 problem is one of the most common JPA performance issues in production.
EAGER and LAZY fetching?FetchType.EAGER instructs JPA to load the related entity or collection immediately as part of the owning entity's query — always, regardless of whether you actually need it. This can lead to loading large graphs of data unnecessarily and triggering many joins. FetchType.LAZY tells JPA to load the association only when it is first accessed; a proxy is returned initially. JPA defaults: @ManyToOne and @OneToOne default to EAGER; @OneToMany and @ManyToMany default to LAZY. Best practice: override @ManyToOne to LAZY and use JOIN FETCH or @EntityGraph in the specific queries that need the association — this gives you explicit, predictable control over SQL generation.
Spring Data JPA parses repository method names and generates the corresponding JPQL query at startup. The method name follows the convention findBy<Property><Operator><Conjunction>. For example, findByEmailAndActiveTrue(String email) generates SELECT e FROM User e WHERE e.email = ?1 AND e.active = true. Supported keywords include And, Or, Is, Not, Like, Between, LessThan, GreaterThan, OrderBy, Distinct, Top/First. For complex queries that cannot be expressed this way, use @Query with JPQL or native SQL. Derived queries are convenient for simple lookups but can become unreadable for more than 2-3 conditions.
@Transactional rollback work? What exceptions trigger rollback by default?By default, Spring rolls back the transaction on any unchecked exception (RuntimeException and its subclasses) and on Error. Checked exceptions do not trigger rollback by default — this mirrors EJB behaviour and the assumption that checked exceptions represent expected, recoverable conditions. You can override this with @Transactional(rollbackFor = IOException.class) to rollback on a checked exception, or noRollbackFor = SpecificRuntimeException.class to suppress rollback for a specific unchecked one. When an exception propagates out of the proxied method, the AOP advice catches it, calls connection.rollback(), and re-throws the exception. Note: if the exception is caught and swallowed inside the @Transactional method, Spring never sees it and will commit.
Optimistic locking is a concurrency strategy that assumes conflicts are rare — it does not acquire a database lock when reading, but checks at write time whether anyone else modified the same row since it was read. In JPA, add a @Version field (typically int or Long) to the entity. JPA automatically includes the version in UPDATE statements: UPDATE product SET stock=?, version=version+1 WHERE id=? AND version=?. If another transaction already incremented the version, the WHERE clause matches zero rows and JPA throws OptimisticLockException (Spring wraps it in ObjectOptimisticLockingFailureException). The caller can retry or inform the user of the conflict. This avoids the overhead of SELECT FOR UPDATE (pessimistic locking) and scales well for read-heavy workloads.
🧪 Arc F — Testing
A unit test tests a single class or method in complete isolation — all dependencies are replaced with mocks or stubs, no Spring context is loaded, and no database or network is involved. Unit tests are fast (milliseconds) and pinpoint failures to one component. An integration test tests the collaboration between multiple components — it typically loads a (possibly partial) Spring context, uses a real or in-memory database, and verifies that components wire together correctly. Integration tests are slower but give higher confidence that the system works end-to-end. A good test suite has many more unit tests than integration tests (the "testing pyramid").
@Mock vs @Spy do in Mockito?@Mock creates a complete mock — every method returns a default value (null, 0, empty list) and does nothing unless you stub it with when(...).thenReturn(...). None of the real class's code executes. @Spy wraps a real instance — by default every method calls the real implementation, but you can selectively stub individual methods with doReturn(...).when(spy).method(). Use @Mock when you want full control and don't need real behaviour (most unit tests). Use @Spy when you want to test a real object but stub one or two expensive or external methods within it. Both require @ExtendWith(MockitoExtension.class) or MockitoAnnotations.openMocks(this).
verify(mock, never())?verify(mock, never()).method() asserts that the given method was never called on the mock during the test — it fails if the method was invoked even once. Use it to verify negative side effects: for example, if a service validates input and rejects an invalid request, you want to confirm the repository's save() method was never called. This is valuable for testing conditional paths where the absence of an interaction is the important behaviour. Other useful invocation modes: times(n), atLeast(n), atMost(n). Combine with verifyNoMoreInteractions(mock) to assert no unexpected calls happened at all.
@DataJpaTest do? How is it different from @SpringBootTest?@DataJpaTest is a slice test annotation that loads only the JPA-related parts of the Spring context — entities, repositories, JPA auto-configuration — and by default replaces the configured datasource with an embedded in-memory database (H2). It also wraps each test method in a transaction that rolls back after the test, keeping tests isolated. @SpringBootTest loads the full application context (all beans, all auto-configuration, all layers), which makes tests slower and requires more setup. Use @DataJpaTest for fast, focused repository tests; use @SpringBootTest for full end-to-end integration tests or when you need beans from multiple layers to collaborate. Pair @DataJpaTest with Testcontainers if you need a real database engine instead of H2.
@ParameterizedTest with @CsvSource work?@ParameterizedTest (JUnit 5) runs the same test method multiple times with different arguments, turning one test into N test cases without code duplication. @CsvSource provides the arguments as comma-separated strings inline: @CsvSource({"'hello', 5", "'world', 5", "'', 0"}). JUnit parses each string into the method's parameter types using implicit type conversion. Each row becomes a separate test run with its own result in the report. Other argument sources: @ValueSource (single argument), @MethodSource (static factory method returning a Stream), @CsvFileSource (CSV from resources), @EnumSource (enum values). Use parameterized tests for boundary conditions, valid/invalid input pairs, and any logic that should behave consistently across many input combinations.
Testcontainers is a Java library that starts real Docker containers (PostgreSQL, MySQL, Redis, Kafka, etc.) programmatically during tests and tears them down after. It is preferred over H2 for integration tests because: (1) Dialect fidelity — H2 has its own SQL dialect and does not support all features of PostgreSQL/MySQL (specific functions, JSON operators, CTEs, generated columns). Bugs caused by dialect differences surface in production, not in tests. (2) Behaviour accuracy — transactional isolation, index behaviour, and constraint handling differ. (3) Migration testing — Flyway/Liquibase scripts run against the real engine. The trade-off is that Testcontainers tests are slower and require Docker. Spring Boot 3.1+ provides first-class Testcontainers support via @ServiceConnection, eliminating manual URL configuration.
🤖 Arc G+H — Java + AI
/api/generate endpoint do?Ollama is an open-source tool that lets you download and run large language models (Llama 3, Mistral, Phi-3, Gemma, etc.) locally on your machine — no internet connection or API key required after the initial model download. It exposes a REST API on http://localhost:11434. The POST /api/generate endpoint accepts a JSON body with model (e.g., "llama3"), prompt (the text to send), and optional parameters like temperature and stream. When stream is false, it returns a single JSON response containing the generated text in the response field. From Java you can call it with RestTemplate, WebClient, or Spring AI's OllamaClient.
RAG (Retrieval-Augmented Generation) solves the problem that LLMs have a fixed training cutoff and no knowledge of your private documents. The three steps: (1) Indexing — your documents are split into chunks, each chunk is converted to a vector embedding (a numeric representation of semantic meaning) using an embedding model, and stored in a vector database (pgvector, Qdrant, Chroma). This happens offline. (2) Retrieval — at query time, the user's question is also embedded and the vector database returns the K most semantically similar document chunks using cosine similarity. This solves relevance. (3) Generation — the retrieved chunks are injected into the LLM's prompt as context alongside the question, and the LLM generates a grounded, factual answer. This solves hallucination by giving the model the facts it needs.
A PromptTemplate is a parameterised string with named placeholders ({topic}, {language}) that are filled at runtime with actual values before being sent to the LLM. In Spring AI, PromptTemplate takes a template string and a Map of variables and produces a fully rendered Prompt. Versioning prompts matters because even small wording changes in a prompt can dramatically change model output — this is the "prompt brittleness" problem. Treating prompts like code (storing in version control, writing eval tests, reviewing changes in PRs) enables rollback when a prompt regression is discovered, A/B testing between versions, and audit trails for regulated industries. A prompt change without a version bump can silently break production quality.
LLM output evaluation requires multiple strategies because there is no single "correct" answer. (1) Exact match / contains — for structured outputs (JSON, code, entity extraction), assert the response contains expected fields or values. (2) LLM-as-judge — send the original question, the expected answer, and the model's response to a second LLM call and ask it to score relevance, faithfulness, and completeness on a 1-5 scale; this scales to open-ended responses. (3) Embedding similarity — embed the expected and actual answers and compute cosine similarity; high similarity (>0.9) suggests semantic equivalence. (4) RAG-specific metrics — context precision (are retrieved chunks relevant?), context recall (are all needed facts retrieved?), answer faithfulness (does the answer contradict the context?). Frameworks like RAGAS and DeepEval automate these. Run evaluations in CI on a golden question set after every prompt or model change.
A text-generation model (decoder-only transformer, e.g., Llama 3, Mistral, GPT-4) takes a prompt and auto-regressively generates the next token, then the next, producing free-form text. It is optimised for language generation tasks — answering questions, summarising, writing code. An embedding model (encoder, e.g., nomic-embed-text, text-embedding-ada-002) takes a text input and produces a fixed-length dense vector (e.g., 768 or 1536 floats) that encodes the semantic meaning of the text. It does not generate text — its output is a number array used for similarity search, clustering, or classification. In a RAG pipeline you use an embedding model to index documents and encode queries, and a generation model to produce the final answer. They are not interchangeable; using a generation model for embeddings produces poor-quality vectors.
⚡ Quick-fire answers
| Question | One-line Answer |
|---|---|
| What HTTP status means 'resource created'? | 201 Created |
| Which annotation makes a field non-null in JPA? | @Column(nullable = false) |
| How do you inject config values in Spring? | @Value("${property.name}") |
| Which assertion checks an exception is thrown? | assertThrows(ExceptionClass.class, () -> ...) |
What does stream.toList() return (Java 16+)? | An unmodifiable List |
| What port does Ollama listen on? | 11434 |
| What is the default Spring Boot port? | 8080 |
What does @PrePersist do? | Runs a method before JPA saves an entity |
| How do you mark a Spring test with a real DB? | @SpringBootTest + Testcontainers |
| What is the JPA annotation for auto-incremented IDs? | @GeneratedValue(strategy = GenerationType.IDENTITY) |
✅ Key takeaways
- Know the why, not just the what — interviewers probe reasoning. Explain trade-offs (e.g., eager vs lazy fetching, composition vs inheritance) with concrete examples from past projects.
- Prepare one real story for each arc: a bug you fixed, a design decision you made, or a performance optimisation you applied. Concrete anecdotes beat textbook answers every time.
- Practice writing code on a whiteboard or plain editor — no IDE autocomplete. Be comfortable writing a JPA entity, a Spring service, and a Mockito unit test from scratch in 5 minutes.
- For "hard" topics (Bean lifecycle, JVM memory, transactional rollback), draw a diagram as you explain. Diagrams signal deep understanding and help the interviewer follow your reasoning.
- Always ask a clarifying question before answering ambiguous prompts — "Are you asking about JPA or JDBC?" shows maturity and saves you from answering the wrong question with confidence.
From interview prep to offer letter
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →