Skip to main content

First One

Mock Java + Spring Boot Backend Interview (2 Years Experience)

Candidate Profile

  • Experience: ~2 years as a Java Developer (plus a few months in PHP)
  • Tech Stack: Java 8, Spring Boot, Spring MVC, REST APIs, banking domain (Kisan Credit Card, Internet Banking, ATM console), JMS, JWT-based auth, MySQL/SQL, Git (GitLab/GitHub), IntelliJ

Topic: Background & Projects

1. Self Introduction / Recent Project

The Question: “Could you introduce yourself?” “Can you tell me about your recent project?”

Candidate’s Approach:

  • Introduced himself as a Java developer at a consultancy company.
  • Mentioned working on multiple banking projects: Kisan Credit Card (KCC), internet banking, inventory projects, REST APIs.
  • Described KCC project: connecting core banking to a government website, creating JSON loan data in Spring Boot backend and sending it to government systems.

Evaluation: ✅ Correct (good real-world context, but could be more structured and impact-focused)

The Ideal Answer: A clean, structured version:

“I’m a Java backend developer with ~2 years of experience. I currently work at <Company>, mainly in the banking domain.

My recent project is Kisan Credit Card (KCC) integration:

  • Stack: Java 8, Spring Boot, REST, JPA/Hibernate, MySQL, Git, IntelliJ.

  • Problem: Core banking system needed to periodically submit loan data to a government portal in a specific JSON format over secure APIs.

  • My Role:

    • Designed REST endpoints to fetch loan & customer data from core banking DB.
    • Transformed and validated data into required JSON schema.
    • Implemented error handling, logging, and retry mechanisms for failed submissions.
    • Optimized queries and batch jobs for large datasets.
  • Impact: Improved reliability of government reporting, reduced manual file uploads, and ensured compliance with regulatory timelines.”

The 'Senior' Concept: A senior engineer uses project descriptions to highlight responsibility, complexity, and impact:

  • Distinguish what you owned vs what the team did.
  • Mention non-functional requirements: performance, security, reliability, observability.
  • For regulated domains (banking/government), explicitly mention audits, compliance, and data integrity – those are big signals for senior interviewers.

Topic: Java 8 & Core Java

2. Java Version & Java 8 Features

The Question: “What Java version are you using?” “Can you tell me some new features that were introduced in Java 1.8 / Java 8?”

Candidate’s Approach:

  • Said they use Java 1.8.
  • Mentioned lambda expressions, then got stuck.
  • Interviewer prompted about Stream API, Optional, and methods like isBlank (which is actually Java 11, not 8).

Evaluation: ⚠️ Partial (knew lambda expressions but missed several core Java 8 features; some confusion around APIs & versions)

The Ideal Answer: Key Java 8 features:

  • Lambda Expressions:

    list.forEach(s -> System.out.println(s));
    

    Anonymous functions enabling functional programming style.

  • Functional Interfaces (java.util.function package): Interfaces with a single abstract method – e.g., Predicate<T>, Function<T, R>, Consumer<T>, Supplier<T>.

  • Stream API: Processing collections with declarative pipelines.

    List<String> result = names.stream()
        .filter(n -> n.startsWith("A"))
        .map(String::toUpperCase)
        .collect(Collectors.toList());
    
  • Default & Static Methods in Interfaces: Allow adding behavior to interfaces without breaking existing implementations.

  • Optional<T> Class: A container object to represent presence/absence of a value and avoid many null checks.

  • New Date/Time API (java.time): LocalDate, LocalDateTime, ZonedDateTime, Duration, etc., immutable and much better than Date/Calendar.

The 'Senior' Concept: Seniors not only list features but know why they matter:

  • Streams + lambdas → less boilerplate, more expressive, but need to watch for performance and readability.
  • Optional → better semantics than null, but overusing it in fields/collections can hurt performance.
  • java.time → timezone correctness & immutability, crucial in distributed systems. Also, seniors must be version-accurate (String.isBlank() is from Java 11, not 8).

Topic: Collections

3. Use of HashMap

The Question: “You said you are using HashMap in your project, so can you tell me what’s the use of HashMap?”

Candidate’s Approach:

  • Said HashMap stores data in key–value pairs.
  • Keys cannot be duplicate; inserting a duplicate key updates the value.
  • Mentioned hashing technique to store data.

Evaluation: ✅ Mostly Correct (good basics; missing load factor, capacity, null handling, concurrent behavior)

The Ideal Answer:

  • HashMap<K, V> stores key–value pairs.

  • Key properties:

    • No duplicate keys; new value overwrites existing for the same key (based on equals() & hashCode()).
    • Allows one null key and multiple null values.
  • Complexity: Average O(1) for get, put, remove due to hashing; worst case O(n) if many collisions (Java 8 uses tree bins for heavy collisions which improves to O(log n)).

  • Internals (high level):

    • Uses array of buckets; index determined by hash(key) & (n-1).
    • Each bucket is a linked list or a tree (for high collision scenarios).

The 'Senior' Concept: A senior connects this to design & performance:

  • HashMap is not thread-safe; use ConcurrentHashMap in concurrent scenarios.
  • Always override equals() and hashCode() correctly for custom key classes.
  • Consider iteration order; if you must maintain insertion order, use LinkedHashMap.
  • Be aware of resize operations and their cost in hot paths.

4. Difference Between HashSet and TreeSet

The Question: “What’s the difference between TreeSet and HashSet?”

Candidate’s Approach:

  • Struggled; interviewer guided: TreeSet maintains order while HashSet doesn’t; time complexity differs.
  • Candidate seemed to agree but didn’t articulate details.

Evaluation: ⚠️ Partial (relied on interviewer, didn’t clearly state complexities or ordering semantics)

The Ideal Answer:

  • HashSet:

    • Backed by HashMap.
    • No guaranteed iteration order.
    • Average O(1) add/remove/contains.
  • TreeSet:

    • Backed by a TreeMap (Red-Black tree).
    • Maintains sorted order according to natural ordering or a Comparator.
    • Operations add/remove/contains are O(log n).

The 'Senior' Concept: Choosing between them is a design decision:

  • Use HashSet when you only care about membership and performance.
  • Use TreeSet when you need sorted data, range queries (headSet, tailSet, subSet) or need NavigableSet behavior.
  • In performance-critical code, using TreeSet accidentally can be a big regression versus HashSet.

Topic: OOP & Core Concepts

5. Is Java 100% Object-Oriented?

The Question: “Is Java a 100% object-oriented programming language?”

Candidate’s Approach:

  • Initially said “No” but justified it incorrectly by talking about multiple inheritance.
  • Interviewer corrected: Java isn’t 100% OO because of primitive types (int, char, etc.).

Evaluation: ❌ Wrong reasoning (correct conclusion, wrong explanation)

The Ideal Answer:

  • Answer: No, Java is not 100% object-oriented.
  • Reason: Java has primitive types (int, boolean, char, double, etc.) which are not objects.
  • Some operations (like arithmetic on primitives, for loops, etc.) are not purely object-based.

The 'Senior' Concept: Seniors understand:

  • Why primitives exist → performance (less overhead than objects).
  • The role of wrapper classes (Integer, Boolean, etc.) and autoboxing, and the pitfalls (extra allocations, Integer caching).
  • In high-performance code, avoid unnecessary boxing/unboxing and be careful with collections of wrapper types.

6. Polymorphism in Java

The Question: “Do you know how Java implements polymorphism? Have you implemented polymorphism before?”

Candidate’s Approach:

  • Explained method overloading: same method name with different parameters.
  • Gave example of fetching farmer data using overloaded methods (one by account number, another by account + state code).

Evaluation: ⚠️ Partial (covered compile-time polymorphism only, missed runtime polymorphism/overriding)

The Ideal Answer: Polymorphism in Java:

  1. Compile-time Polymorphism (Method Overloading): Same method name, different parameter list (type/number/order).

    void find(String account);
    void find(String account, String stateCode);
    
  2. Runtime Polymorphism (Method Overriding & Dynamic Dispatch): Subclass provides its own implementation of a superclass method.

    class Payment {
        void pay() { ... }
    }
    class CardPayment extends Payment {
        @Override void pay() { ... }
    }
    Payment p = new CardPayment();
    p.pay(); // calls CardPayment.pay() at runtime
    

The 'Senior' Concept: Seniors think about polymorphism and design:

  • Use polymorphism to avoid giant if-else / switch blocks → apply Strategy, Template Method, etc.
  • Understand costs: virtual calls, potential inlining/JIT optimizations.
  • Avoid abusing overloading where signatures become ambiguous or confusing.

7. Singleton Pattern

The Question: “Have you created a Singleton class in your project? Do you know about Singleton classes?”

Candidate’s Approach:

  • Referred to Spring Boot: when app starts, it creates single instances (beans) used for database queries instead of creating objects repeatedly.
  • Roughly equated Spring beans with singletons.

Evaluation: ⚠️ Partial (intuition is okay, but no explicit definition or standard implementation details)

The Ideal Answer:

  • Singleton: A class that allows only one instance globally and provides a global access point.

  • Classic implementation (eager):

    public class MySingleton {
        private static final MySingleton INSTANCE = new MySingleton();
        private MySingleton() {}
        public static MySingleton getInstance() {
            return INSTANCE;
        }
    }
    
  • In Spring:

    • The default bean scope is singleton, meaning one bean instance per Spring container, which is similar but not identical to the GoF Singleton pattern.

The 'Senior' Concept: Seniors are wary of singletons:

  • Singletons can become global state, hurting testability and introducing hidden coupling.
  • Prefer dependency injection (like Spring) to manage “one instance” semantics cleanly.
  • Consider thread safety (synchronized, double-checked locking, enum singleton).

8. Immutability & String

The Question: “What does immutability mean in Java?” “String is immutable – can you explain?” “If I ask you to create an immutable class, how would you do it?”

Candidate’s Approach:

  • Confused at first between String, StringBuffer, string pool.
  • Eventually agreed that String is immutable and mentioned string pool.
  • For immutable class: said to use final (class and members), private fields, and avoid setters; plus constructor-based initialization.

Evaluation: ⚠️ Partial (correct final picture but explanation was messy and technically imprecise)

The Ideal Answer:

Immutability:

  • An object is immutable if its state cannot change after construction.

  • String is immutable:

    • Once created, its char[] (in older versions) or value cannot be modified.
    • Operations like concat or substring create new String objects.

Creating an Immutable Class:

  1. Declare the class final to prevent subclassing.
  2. Make all fields private and final.
  3. Initialize all fields in constructor only.
  4. Do not provide setters.
  5. For mutable fields, make defensive copies in constructor and getters.
public final class ImmutableUser {
    private final String name;
    private final LocalDate dob;
    private final List<String> roles;

    public ImmutableUser(String name, LocalDate dob, List<String> roles) {
        this.name = name;
        this.dob = dob;
        this.roles = List.copyOf(roles); // defensive copy
    }

    public String getName()  { return name; }
    public LocalDate getDob() { return dob; }
    public List<String> getRoles() { return roles; } // unmodifiable list
}

The 'Senior' Concept: Immutability is a power tool:

  • Great for concurrency (no locks needed, inherently thread-safe).
  • Used everywhere in modern frameworks: DTOs, configuration, event objects.
  • Tradeoff: more object creation (GC pressure), so be careful on high-throughput paths.

9. public static void main(String[] args)

The Question: “Can you explain public static void main(String[] args) in Java? Why is static used? What happens if main is not static?”

Candidate’s Approach:

  • Said public means anyone can access, static means can be changed (incorrect), void means no return.
  • Partially reasoned that static is needed so JVM can call it without creating an object.
  • Incorrectly claimed it would still run if main were not static.

Evaluation: ❌ Mostly Wrong (partial idea about JVM calling main without an object, but lots of incorrect details)

The Ideal Answer:

  • public – JVM (from outside the class) must be able to access main, so it must be public.
  • static – JVM needs to call main without instantiating the class. Static methods belong to the class, not an object.
  • voidmain doesn’t return any value to JVM (process exit code is handled differently).
  • String[] args – command line arguments passed to the program.

If main is not static:

  • The JVM will not recognize it as a valid entry point and will throw a NoSuchMethodError: main at runtime.

The 'Senior' Concept: Seniors know:

  • Entry-point signatures are conventions required by the runtime.
  • In modern apps (Spring Boot, containers), main usually just bootstraps the framework. Real logic should be elsewhere.
  • Static is often overused; DI frameworks are preferred to manage lifecycle and dependencies.

10. Abstract Class vs Interface

The Question: “Can you tell me the difference between abstract classes and interfaces?”

Candidate’s Approach:

  • Gave a vague explanation about defining methods in one class and implementing in another.
  • Talked about using them in a project (beans and remotes) but not in general terms.
  • Interviewer had to provide the general differences.

Evaluation: ⚠️ Partial/Wrong (didn’t clearly articulate core differences)

The Ideal Answer: Key differences (especially pre-Java 8):

  • Abstract Class:

    • Can have both abstract and concrete methods.
    • Can have state (instance variables).
    • A class can extend only one abstract class (single inheritance).
    • Constructors are allowed.
  • Interface:

    • Originally only abstract methods; since Java 8, can have default and static methods; since Java 9, private methods.
    • Cannot have instance state (only public static final constants).
    • A class can implement multiple interfaces.

Use guidelines:

  • Use abstract class when you need a base class with shared state or behavior.
  • Use interfaces for defining capabilities/contracts that multiple unrelated classes can implement.

The 'Senior' Concept: Seniors reason about evolution and design:

  • Interfaces are better for API contracts because existing implementations won’t break when you add default methods thoughtfully.
  • Abstract classes are more about code reuse and enforcing partial implementations.
  • Prefer composition over inheritance; don’t overuse abstract base classes in deep hierarchies.

11. Java Memory Model & Garbage Collection

The Question: “Have you heard about Java memory model and garbage collection? Can you explain both? What does garbage collection do? How does it affect system performance?”

Candidate’s Approach:

  • Only spoke about garbage collection in vague terms: unused variables become garbage and are cleaned automatically.
  • Couldn’t address the Java Memory Model.
  • Didn’t explain GC’s impact on performance beyond generic statements.

Evaluation: ⚠️ Partial (basic intuition for GC, no understanding of JMM or GC-performance relationship)

The Ideal Answer:

Java Memory Model (JMM):

  • Defines how variables are read/written across threads: visibility, ordering, and happens-before rules.

  • Concepts:

    • Main memory vs CPU caches.
    • volatile → guarantees visibility & ordering for reads/writes.
    • synchronized → mutual exclusion + happens-before edges.
    • Reordering rules that compilers/CPUs must obey.

Garbage Collection (GC):

  • Automatically finds unreachable objects and reclaims their memory.

  • Modern collectors: generational, with young/old generations; minor and major GCs.

  • Performance impact:

    • Reduces memory leaks by reclaiming unused objects.
    • But introduces GC pauses (stop-the-world events).
    • Requires tuning heap size, generations, and GC algorithm (G1, ZGC, etc.) for latency vs throughput.

The 'Senior' Concept: Seniors:

  • Think about allocation patterns (many short-lived objects → young gen; long-lived → old gen).
  • Design APIs to avoid excessive object creation in hot paths.
  • Understand that concurrency correctness depends on JMM, especially when using volatile, Atomic* classes, and lock-free algorithms.
  • Know how to read GC logs, tune GC, and reason about pause times for latency-sensitive systems.

12. Handling IOException and Exceptions

The Question: “If a method throws an IOException, how would you handle it?”

Candidate’s Approach:

  • Mentioned using try-catch-finally.
  • Said he would catch the exception, print stack trace (e.printStackTrace()), maybe log it.

Evaluation: ⚠️ Partial (knows syntax but no discussion of proper error handling)

The Ideal Answer: Use try-catch when you can recover or need to log:

try {
    Files.readAllLines(path);
} catch (IOException e) {
    log.error("Failed to read file: {}", path, e);
    throw new CustomAppException("File read error", e); // or handle gracefully
}

or declare it and let the caller handle:

public void processFile(Path path) throws IOException {
    Files.readAllLines(path);
}

The 'Senior' Concept: Seniors:

  • Avoid swallowing exceptions or relying on printStackTrace().
  • Use structured logging, meaningful error messages, and custom exceptions where appropriate.
  • Think about API contracts: does this method guarantee handling IO issues, or does it propagate them?

13. Optional Class

The Question: “Do you know about the Optional class in Java? Have you used it?”

Candidate’s Approach:

  • Said “no” / unsure.
  • Confused Optional with IoC (Inversion of Control).

Evaluation: ❌ Wrong / No knowledge

The Ideal Answer:

  • Optional<T> is a container to represent a value that may or may not be present.
  • It helps avoid null and NullPointerException.

Example:

Optional<User> userOpt = userRepository.findById(id);

userOpt.ifPresent(user -> log.info(user.getName()));

User user = userOpt.orElseThrow(() -> new NotFoundException("User not found"));

The 'Senior' Concept:

  • Use Optional primarily as method return type, not for fields or parameters.
  • Avoid Optional.get() without checking – defeats the purpose.
  • Don’t wrap everything in Optional; it can add overhead and complexity – use judiciously.

14. SOLID Principles

The Question: “Have you heard about SOLID principles?”

Candidate’s Approach:

  • Said no, hadn’t studied them.

Evaluation: ❌ No knowledge

The Ideal Answer: S – Single Responsibility Principle O – Open/Closed Principle L – Liskov Substitution Principle I – Interface Segregation Principle D – Dependency Inversion Principle

Briefly:

  • SRP: A class should have one reason to change.
  • OCP: Open for extension, closed for modification.
  • LSP: Subtypes must be substitutable for their base types.
  • ISP: Many small, specific interfaces are better than one big “fat” interface.
  • DIP: Depend on abstractions, not concretions.

The 'Senior' Concept: SOLID is a mental checklist for design:

  • Are my classes doing too much?
  • Am I breaking clients when adding new behavior?
  • Is the inheritance hierarchy valid, or am I violating LSP?
  • Are my modules loosely coupled through interfaces?

Topic: Spring & Spring Boot

15. Advantages of Spring Boot Over Traditional Spring

The Question: “Can you tell me the advantages of using Spring Boot over traditional Spring applications?”

Candidate’s Approach:

  • Focused on configuration: said Spring Boot reduces XML config.
  • Mentioned that in older Spring apps he had to configure many files for JMS and other features; in Spring Boot it’s simpler.
  • Mentioned that embedded Tomcat is provided so no need to configure server manually.

Evaluation: ✅ Mostly Correct (got key points, could be more structured)

The Ideal Answer: Advantages of Spring Boot:

  • Auto-Configuration: Sensible defaults for many common use cases (web, data, security).
  • Starter Dependencies: spring-boot-starter-web, spring-boot-starter-data-jpa, etc., reduce dependency management.
  • Embedded Servers: Tomcat/Jetty/Undertow embedded – easier local dev & deployment (java -jar).
  • Actuator: Production-ready endpoints (health, metrics, env, etc.).
  • Reduced Boilerplate: No XML configuration by default; mostly Java config and properties/yaml.
  • Opinionated but configurable: Good conventions with flexibility.

The 'Senior' Concept: Seniors:

  • Know how auto-config works and when to override it (e.g., custom DataSource, security config).
  • Understand profile-based configuration (dev, test, prod).
  • Think about deployment patterns: fat JAR vs WAR, containerization, health checks via Actuator.

16. Replacing Embedded Tomcat With Another Server

The Question: “Tomcat is the inbuilt server in Spring Boot, right? If we want to use another server, how can we replace it?”

Candidate’s Approach:

  • Said we can configure in pom.xml, and also mentioned DB connection in application.properties.
  • Did not clearly describe how to exclude Tomcat and bring another container.

Evaluation: ⚠️ Partial (idea of using Maven is correct, but missing concrete steps)

The Ideal Answer: Example: Replace Tomcat with Jetty:

  • In pom.xml, exclude Tomcat from spring-boot-starter-web and add Jetty:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
    

The 'Senior' Concept:

  • Container choice affects performance characteristics and sometimes supported features.
  • In the cloud, often containerized apps run as standalone processes; embedded server choice is a deployment decision.
  • For WAR deployment to external app servers, Spring Boot can be configured accordingly.

17. How Spring Resolves Dependencies at Runtime

The Question: “How does Spring resolve dependencies at runtime?”

Candidate’s Approach:

  • Talked about controllers including other classes and Spring injecting them.
  • Mentioned that unused objects might be garbage collected (mixing two concepts).
  • Didn’t clearly describe IoC container / bean lifecycle.

Evaluation: ⚠️ Partial (intuition about injection, but explanation is unclear and mixes GC with DI)

The Ideal Answer:

  • Spring uses an IoC (Inversion of Control) container.

  • At startup, it:

    • Scans classes annotated with @Component, @Service, @Repository, @Controller, etc.
    • Instantiates them as beans.
    • Resolves dependencies by looking at constructor parameters or fields annotated with @Autowired / constructor injection.
  • At runtime, when someone needs a dependency, Spring either:

    • Injects the proper bean into the consumer.
    • Or provides it via ApplicationContext.getBean(...).

The 'Senior' Concept: Seniors:

  • Prefer constructor injection for immutability and testability.
  • Understand scopes (singleton, prototype, request, session).
  • Know that Spring often uses proxies (AOP, @Transactional, etc.), which affects equality, serialization, and lazy loading.

Topic: Spring MVC & Error Handling

18. Request Mapping in Spring MVC

The Question: “You have used Spring MVC – how is request mapping handled in Spring MVC?”

Candidate’s Approach:

  • Mentioned @RestController and returning JSON/XML.
  • Did not clearly describe @RequestMapping, @GetMapping, etc., and how URI paths map to controller methods.

Evaluation: ⚠️ Partial

The Ideal Answer:

  • Use controller annotations:

    @RestController
    @RequestMapping("/api/users")
    public class UserController {
    
        @GetMapping("/{id}")
        public UserDto getUser(@PathVariable Long id) { ... }
    
        @PostMapping
        public UserDto createUser(@RequestBody UserDto dto) { ... }
    }
    
  • Request mapping is defined by:

    • HTTP method (GET, POST, PUT, DELETE, etc.)
    • Path (/api/users/{id})
    • Params / headers / consumes / produces if specified
  • Spring’s DispatcherServlet routes incoming HTTP requests to the appropriate handler method.

The 'Senior' Concept: Seniors:

  • Think about API versioning, error payload consistency, and proper HTTP status codes.
  • Use validation (@Valid, @NotNull, etc.) and ensure consistent response models.
  • Handle cross-cutting concerns (logging, tracing, security) without cluttering controllers.

19. @ControllerAdvice and Global Exception Handling

The Question: “Can you tell me what’s the use of @ControllerAdvice annotation? Have you used global exception handler before?”

Candidate’s Approach:

  • Said he hasn’t used @ControllerAdvice or global exception handling.

Evaluation: ❌ No knowledge

The Ideal Answer:

  • @ControllerAdvice allows global handling of exceptions and cross-cutting concerns for controllers.

  • Example:

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(NotFoundException.class)
        public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException ex) {
            ErrorResponse err = new ErrorResponse("NOT_FOUND", ex.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
        }
    
        @ExceptionHandler(Exception.class)
        public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) {
            ErrorResponse err = new ErrorResponse("INTERNAL_ERROR", "Something went wrong");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(err);
        }
    }
    

The 'Senior' Concept:

  • Seniors design consistent error contracts (error codes, messages, trace IDs).
  • They centralize exception handling for observability and easier client integration.
  • They avoid leaking internal details or stack traces to clients in production.

Topic: JDBC & Transactions

20. JDBC and Transaction Management in Spring

The Question: “Do you know about JDBC? How does Spring manage transactions in JDBC?”

Candidate’s Approach:

  • Said JDBC is for connecting SQL DB and project.
  • Mentioned using entity classes and queries.
  • Referred to using @Transactional for update/delete operations but without much detail.

Evaluation: ⚠️ Partial

The Ideal Answer:

  • JDBC: Low-level API to connect to relational databases (Connection, PreparedStatement, ResultSet).

  • In Spring:

    • You can use JdbcTemplate or JPA (EntityManager/Spring Data JPA).
    • Transaction boundaries are typically managed using @Transactional.
@Service
public class TransferService {

    @Transactional
    public void transferMoney(Long fromId, Long toId, BigDecimal amount) {
        accountRepository.debit(fromId, amount);
        accountRepository.credit(toId, amount);
        // if any exception is thrown, whole transaction rolls back
    }
}
  • Spring uses AOP proxies:

    • Starts transaction before method.
    • Commits if method finishes successfully.
    • Rolls back on runtime exceptions (configurable).

The 'Senior' Concept: Seniors:

  • Understand isolation levels, propagation behavior, and rollback rules.
  • Avoid mixing multiple transaction managers unintentionally.
  • Are careful with lazy loading and @Transactional boundaries to prevent LazyInitializationException.

Topic: Security & JWT

21. Securing APIs With JWT

The Question: “How will you secure REST endpoints / APIs?”

Candidate’s Approach:

  • Mentioned JWT (JSON Web Token) authentication.
  • Said they use an access token so only authenticated users can call APIs.

Evaluation: ⚠️ Partial (correct direction but not detailed)

The Ideal Answer:

  • Use Spring Security + JWT:

    • User logs in with credentials → server authenticates and issues a signed JWT (with expiry, user ID, roles).
    • Client sends JWT in Authorization: Bearer <token> header with each request.
    • A filter/interceptor validates token signature, expiry, and extracts claims to create Authentication.
    • Use @PreAuthorize / @Secured or URL-based rules to restrict access by roles.

The 'Senior' Concept: Seniors care about:

  • Token expiry, refresh tokens, and revocation strategies.
  • Securing secrets: private keys/signing keys environment-specific.
  • Avoid putting sensitive data in JWT payload; understand JWT is signed, not encrypted.
  • Defense in depth: HTTPS, rate limiting, IP allowlisting, audit logging.

Topic: Microservices & System Design

22. Basics of Microservices & Zomato-Like Application

The Question: “You know the basics of microservices, right? If I ask you to create a Zomato-like application in a microservices architecture, how many microservices would you create? Which ones?”

Candidate’s Approach:

  • Struggled to structure the domain.

  • Mentioned something like:

    • Service for accepting orders from users.
    • Another service to send requests to a “main server” and then to restaurants.
  • The answer blurred front-end/back-end responsibilities and missed core microservice boundaries (user, restaurant, order, payment, delivery, etc.).

Evaluation: ❌ Mostly Wrong / very incomplete

The Ideal Answer: Rough microservice decomposition for a Zomato-like system:

  • User Service: Manage users, profiles, authentication.
  • Restaurant Service: Manage restaurants, menus, ratings.
  • Order Service: Create and manage orders, order status.
  • Delivery Service: Assign delivery partners, track delivery status.
  • Payment Service: Handle payments, refunds, invoices.
  • Notification Service: Send SMS/email/push notifications.
  • Gateway/API Gateway: Single entry point for clients, route to proper services.

Each service:

  • Owns its data (separate DB, maybe per service).
  • Communicates via REST or messaging (Kafka/RabbitMQ).
  • Has its own deployment lifecycle.

The 'Senior' Concept: Seniors think about:

  • Bounded Contexts (from DDD) when splitting services.
  • Data consistency: sagas, eventual consistency, idempotent operations.
  • Cross-cutting concerns: logging, metrics, tracing, centralized config, service discovery.
  • Avoiding nano-services; services must be cohesive and meaningful.

Topic: Data Modeling

23. Designing DTO for Delivery Boy

The Question: “How would you design the model/DTO for the delivery boy in this system? What mandatory fields would you add? What about verification details?”

Candidate’s Approach:

  • Mentioned:

    • Delivery boy ID.
    • Name.
    • Availability and timing.
    • Location and distance from restaurant.
    • Contact number, email.
    • City, PIN code.
    • Verification IDs like Aadhaar card.

Evaluation: ✅ Correct direction (good set of fields; could be more structured and normalized)

The Ideal Answer: Example DTO:

public class DeliveryPartnerDto {
    private Long id;
    private String name;
    private String phone;
    private String email;

    private boolean active;
    private boolean currentlyAvailable;

    private double currentLatitude;
    private double currentLongitude;

    private String city;
    private String pinCode;

    private String governmentIdType;   // e.g. AADHAAR, PAN
    private String governmentIdNumber;

    private VehicleDto vehicle; // model, number, type
}

Consider also:

  • rating, totalDeliveries.
  • shiftStartTime, shiftEndTime.
  • maxOrderCapacity or load.

The 'Senior' Concept: Seniors:

  • Separate internal model from external API DTOs.
  • Consider privacy and security (e.g., don’t expose full government ID in APIs).
  • Think about geo-indexing and how location will be used for nearest-delivery search (indexes, geo DB, etc.).

Topic: Version Control & Git

24. Resolving Merge Conflicts

The Question: “Can you tell me how you resolve conflicts while merging in GitLab or GitHub?”

Candidate’s Approach:

  • Said he deals with this daily.

  • Described workflow:

    • Open conflict file in IntelliJ.
    • Compare changes, decide whether to keep or remove lines.
    • Understand what other people changed and merge carefully.

Evaluation: ✅ Correct (practical, though not very structured)

The Ideal Answer: Typical steps:

  1. Pull or fetch latest changes.

  2. When merge conflict occurs:

    • Open conflicting files (in IDE or with git status and git diff).
    • Resolve markers <<<<<<<, =======, >>>>>>>.
    • Decide which parts to keep and adjust code logically.
  3. Run tests / compile to ensure things still work.

  4. git add resolved files.

  5. Commit the merge.

The 'Senior' Concept: Seniors:

  • Proactively minimize conflicts through good branching strategy (short-lived branches, rebasing, feature toggles).
  • Communicate with teammates when conflicts are non-trivial.
  • Understand semantic conflicts (code compiles but logic is wrong) and rely on tests and code review to catch them.

If you’d like, I can now:

  • Turn this into a personal study checklist (topics + links + exercises), or
  • Create flashcard-style Q&A just for Java core, or just for Spring, based on where you want to focus first.