Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Thursday, July 2, 2026

200+ Java Interview Questions & Answers: Core, Spring, AI & Business Problem Solving (2026) | FreeLearning365

200+ Java Interview Questions & Answers: Core, Spring, AI & Business Problem Solving (2026) | FreeLearning365

Imagine walking into your next Java interview with absolute confidence. You’re not just reciting definitions—you’re telling stories of real business problems you solved, demonstrating modern AI integrations, and writing code that scales. This guide transforms you into that developer. Each question is crafted as a story-driven scenario, just like a senior engineer would answer.

☕ Section 1: Core Java (Beginner to Intermediate)

💼 Business Story You're building a backend service for a fintech startup. Interviewer wants solid Java fundamentals.

Q1: What makes Java platform‑independent, and why is that a business advantage?
Answer: Java compiles to bytecode, which runs on any JVM. I’ve deployed the same jar on Windows dev machines, Linux servers, and cloud containers without change, reducing infrastructure costs and time.
Q2: JVM, JRE, JDK – how do you explain them to a non‑tech stakeholder?
Answer: JVM runs Java programs, JRE includes JVM + libraries to execute, JDK adds development tools. For the business, JDK is for building, JRE for running. Our Docker images use slim JRE to save space.
Q3: public static void main – each keyword’s purpose.
Answer: public so JVM can call it, static to run without object, void because no return value, main the entry point, String[] args for command‑line arguments.
Q4: Primitive vs reference types – memory and performance.
Answer: Primitives store values on stack (fast); references store pointers to heap objects. In latency‑sensitive trading apps, I prefer primitives to avoid boxing overhead.
Q5: Autoboxing and unboxing – a hidden performance pitfall.
Answer: Automatic conversion between primitives and wrappers. In a loop summing Integers, autoboxing created 2 million objects; switching to int improved speed 5×.
Q6: String immutability – how it helps security and caching.
Answer: Strings cannot be changed, so they are safe for passwords and hash maps. I’ve used String.intern() to reduce duplicate string memory in a large dataset service.
Q7: StringBuilder vs StringBuffer – when each is appropriate.
Answer: StringBuilder is unsynchronized (fast, single‑thread); StringBuffer is synchronized (thread‑safe). In a web server’s response builder, I use StringBuilder for performance.
Q8: equals() vs == – the critical difference.
Answer: == compares references (memory addresses); equals() compares content. Overriding equals() is essential for value objects like Money. Forgot once, and duplicate orders weren’t detected.
Q9: hashCode contract – why you must override both equals and hashCode.
Answer: If two objects are equal, they must have the same hash. Breaking this contract in a HashSet led to duplicate user entries, a severe business bug.
Q10: static keyword – variables, methods, blocks, nested classes.
Answer: static belongs to class, not instance. I use static factory methods for object creation (e.g., LocalDate.now()) and static initializers for config loading.
Q11: final keyword – variables, methods, classes.
Answer: final variables cannot be reassigned, final methods can’t be overridden, final classes can’t be subclassed. I mark security‑related methods final to prevent tampering.
Q12: Access modifiers – when to use protected vs package‑private.
Answer: protected allows subclass and same package access. In a library, I use protected for hooks that subclasses may override, keeping the API clean.
Q13: Abstract class vs interface – since Java 8+.
Answer: Abstract classes can have state and constructors; interfaces now support default/static methods. I use interfaces for contracts (e.g., PaymentProcessor) and abstract classes for shared code.
Q14: Exception handling – checked vs unchecked, and a business rule.
Answer: Checked exceptions force handling; unchecked indicate programming errors. In our payment integration, we wrap checked IOException in a custom PaymentException to keep business logic clean.
Q15: try‑with‑resources – cleaner resource management.
Answer: Auto‑closeable resources (files, DB connections) are closed automatically. I always use it for JDBC connections to avoid leaks.
Q16: Generics – type safety and a real collection misuse.
Answer: Generics prevent ClassCastException. Before generics, we had to cast objects from a List, leading to runtime errors. Now List catches mistakes at compile time.
Q17: Wildcards in generics – ? extends and ? super.
Answer: ? extends for reading (producer), ? super for writing (consumer). PECS rule. I used List to process mixed numeric lists in a reporting engine.
Q18: Lambda expressions – how they simplify business logic.
Answer: Instead of anonymous inner classes, I use list.forEach(item -> process(item)). In a data pipeline, lambdas made the code 40% shorter and more readable.
Q19: Stream API – filter, map, reduce in a transaction summary.
Answer: transactions.stream().filter(t -> t.isCredit()).map(Transaction::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add) computes total credits concisely.
Q20: Functional interfaces – Predicate, Consumer, Function.
Answer: I use Predicate for validation rules, Consumer for side effects (logging), Function for transformations. They allow passing behavior as parameters.
Q21: Optional – avoiding null pointer exceptions elegantly.
Answer: I return Optional from repository methods instead of null. The caller must handle absence explicitly, reducing NPE bugs by 90%.
Q22: Date/Time API (java.time) – why it’s better than legacy Date.
Answer: Immutable, thread‑safe, and clear. I use LocalDate for birthdays, ZonedDateTime for global events. Migrated an old calendar system, cutting bugs related to timezone confusion.
Q23: Records (Java 16+) – DTOs and value objects.
Answer: A record public record UserDTO(String name, String email) {} automatically provides constructor, equals, hashCode. I use them for API responses, slashing boilerplate.
Q24: Pattern matching for instanceof – cleaner type checks.
Answer: if (obj instanceof String s) { return s.length(); } eliminates redundant casting. It made my protocol handler code much cleaner.
Q25: Switch expressions – using yield for business rules.
Answer: I replaced complex if‑else discount logic with a switch expression that returns the discount percentage. More compact and exhaustive.
Q26: Sealed classes (Java 17) – controlling inheritance.
Answer: I define a sealed interface PaymentMethod permits CreditCard, PayPal so no unknown subtypes can appear. Ensures exhaustive pattern matching in switch.
Q27: Text blocks – multi‑line strings for SQL/JSON.
Answer: Using """ ... """ I write readable embedded SQL queries without concatenation. Great for prototyping and tests.
Q28: Java modules (JPMS) – when would you modularize a monolithic app?
Answer: To enforce boundaries and reduce coupling. I modularized a large banking app into services, each module exporting only its API, which improved build times and code ownership.
Q29: Garbage collection basics – how to avoid memory leaks.
Answer: GC reclaims unreachable objects. Leaks happen when references are kept unintentionally (e.g., static collections). I once fixed a memory leak by clearing a cache that held old user sessions.
Q30: JVM memory areas – heap, stack, metaspace.
Answer: Heap for objects, stack for method calls/primitives, metaspace for class metadata. Tuning heap with -Xmx prevents OutOfMemoryErrors; I set appropriate values for container limits.
Q31: OutOfMemoryError types – and how you handled one.
Answer: Java heap space, Metaspace, GC overhead limit. I diagnosed a heap OOM by analyzing a heap dump (jmap), found a huge list accumulating events without limit.
Q32: ClassLoader hierarchy – why you might write a custom one.
Answer: Bootstrap, Extension, Application. I wrote a custom ClassLoader for a plugin system that loads encrypted classes, extending application functionality dynamically.
Q33: Reflection – power and performance considerations.
Answer: Allows runtime inspection. I used it to build a flexible JSON mapper, but it’s slower. In high‑throughput services, I cache reflective access.
Q34: Annotations – custom annotation for audit logging.
Answer: I created @Auditable and used AOP (Spring) to log method calls. This reduced boilerplate and ensured consistent logging.
Q35: Enum – methods, fields, and implementing interfaces.
Answer: Enums are classes. I defined a ShippingMethod enum with a calculateCost(Order) method, replacing a giant switch.
Q36: Comparing objects – Comparable vs Comparator.
Answer: Comparable defines natural order (e.g., by ID); Comparator for alternative orders (by date). I pass a comparator to Collections.sort() for dynamic sorting in a report UI.
Q37: Cloning – shallow vs deep copy, and cloning alternatives.
Answer: clone() is tricky; I prefer copy constructors or builders. In a data migration tool, I used serialization/deserialization for deep cloning complex object graphs.
Q38: Internationalization (i18n) with ResourceBundle.
Answer: I externalized strings into properties files per locale. For a global e‑commerce site, the Java app automatically loaded the correct bundle based on user language.
Q39: File I/O – NIO vs classic IO.
Answer: NIO offers non‑blocking, channels, buffers, and improved performance for large files. I rewrote a file importer using Files.lines() and streams, processing huge CSVs with low memory.
Q40: Serialization – security risks and the transient keyword.
Answer: Serialization can expose internals; I mark sensitive fields transient. For external APIs, I prefer JSON over Java serialization due to vulnerabilities.
Q41: Var keyword (Java 10) – where you use it.
Answer: Local variable type inference. I use var to reduce verbosity when the type is obvious, e.g., var users = new ArrayList();, but avoid when clarity is lost.
Q42: Text formatting – MessageFormat vs String.format().
Answer: String.format for simple patterns; MessageFormat for i18n with plural rules. In invoice generation, I used MessageFormat to handle currency formatting per locale.
Q43: Shutdown hooks – graceful resource cleanup.
Answer: Runtime.getRuntime().addShutdownHook(thread) to flush logs or close connections when JVM exits. Essential for data integrity.
Q44: Java command line tools – jps, jstat, jmap.
Answer: I use jps to list processes, jstat for GC stats, jmap for heap dumps. These helped me diagnose a memory leak in production without restarting.
Q45: Assertions – when to use them in production code.
Answer: I use assertions for internal invariants during development/testing. In production, they are disabled, so I never put business logic inside assertions.
Q46: BigInteger and BigDecimal – financial precision.
Answer: I always use BigDecimal for monetary calculations to avoid floating point errors. BigDecimal.TEN with appropriate scale and rounding prevents penny discrepancies.
Q47: EnumSet and EnumMap – performance for enums.
Answer: Highly optimized bit‑vector based implementations. I used an EnumMap for storing configuration flags per enum constant, faster than HashMap.
Q48: WeakHashMap – caching without memory leaks.
Answer: Keys are weakly reachable; they get GC'd when no strong references exist. I used it for a temporary metadata cache tied to object lifecycle.
Q49: Thread‑safe singleton patterns – enum and static holder.
Answer: The enum singleton pattern is the simplest: enum ConfigManager { INSTANCE; }. It’s serialization‑safe and thread‑safe. I use it for global configuration.
Q50: Difference between throw and throws – exception propagation.
Answer: throw actually raises an exception; throws declares a method may throw one. In a service layer, I throw exceptions and let the controller handle them via a global exception handler.

🧱 Section 2: OOP & Design Patterns (Intermediate)

Q51: SOLID principles applied to a real Java project.
Answer: Single Responsibility: separated OrderValidator from OrderRepository. Open/Closed: added new discount types via extension not modification. Liskov: subclasses of Payment could substitute parent. Interface Segregation: slim service interfaces. Dependency Inversion: high‑level modules depend on abstractions.
Q52: Composition over inheritance – a report generator example.
Answer: Instead of inheriting from BaseReport, a Report class uses a DataFetcher and a Renderer object, making it flexible to change data sources or output formats.
Q53: Factory Method pattern – creating database connectors.
Answer: Define ConnectorFactory.create(type) returning Connector interface. Subclasses decide concrete class. I used it to support multiple databases without changing client code.
Q54: Abstract Factory – UI toolkit for different platforms.
Answer: An interface for creating families of related objects. In a cross‑platform app, a WindowsFactory and MacFactory produce buttons, scrollbars that look native.
Q55: Singleton pattern – when and why to avoid.
Answer: Ensures a single instance. I avoid if possible because it hides dependencies and hinders testing. Instead, I use Spring’s singleton beans managed by DI.
Q56: Builder pattern – creating complex immutable objects.
Answer: I use it for DTOs with many optional fields. Order.builder().id(1).status(Status.NEW).build() makes construction clear and prevents constructor telescoping.
Q57: Prototype pattern – cloning cached objects.
Answer: Instead of re‑initializing heavy objects, I clone a prototype. In a game server, I cloned a pre‑configured room template to save setup time.
Q58: Adapter pattern – integrating a legacy payment system.
Answer: I created an adapter that implements our PaymentGateway interface and wraps the legacy API, so the rest of the system remains unchanged.
Q59: Decorator pattern – adding logging and metrics.
Answer: A decorator implements the same interface and wraps the original object, adding behavior before/after delegation. I decorated a NotificationService with logging without altering core logic.
Q60: Observer pattern – event‑driven order status updates.
Answer: Subject notifies observers. I implemented it using PropertyChangeSupport so that UI components refresh when the order model changes.
Q61: Strategy pattern – shipping cost calculation.
Answer: Define ShippingStrategy interface; different implementations for FedEx, UPS. The context chooses the strategy at runtime, making it easy to add new carriers.
Q62: Command pattern – undo functionality in a text editor.
Answer: Encapsulate a request as an object. I built an UndoableCommand interface with execute/undo, allowing a history stack. Used in a document processing pipeline.
Q63: Template Method – report generation skeleton.
Answer: Abstract class defines the algorithm’s steps; subclasses fill in specifics. A ReportGenerator with a template method generate() calls abstract fetchData(), format().
Q64: Facade pattern – simplifying a complex subsystem.
Answer: I built a PaymentFacade that hides the interactions between fraud check, inventory, and payment processor behind a single method processOrder().
Q65: Proxy pattern – lazy loading and access control.
Answer: A virtual proxy loads heavy images on demand; a protection proxy controls access. I used a dynamic proxy (InvocationHandler) to add security checks transparently.
Q66: Chain of Responsibility – request filtering.
Answer: Multiple handlers in a chain; each decides to process or pass. I implemented authentication, validation, and logging as chain links for incoming HTTP requests.
Q67: State pattern – order lifecycle management.
Answer: An order’s behavior changes with its state. I created OrderState interface with implementations like PendingState, ShippedState. The order delegates to state, preventing complex conditionals.
Q68: Memento pattern – saving and restoring editor snapshots.
Answer: Memento captures internal state without violating encapsulation. I used it in a workflow designer where users can undo/redo changes.
Q69: Flyweight pattern – reducing memory with shared glyphs.
Answer: In a text rendering engine, I reused character style objects for thousands of text chunks, drastically cutting memory.
Q70: Dependency Injection in Java – manual vs framework.
Answer: I inject dependencies via constructor, making classes testable. In Spring, the container handles wiring. Without framework, I use a manual DI container or factories.
Q71: Immutable objects – design rules and business benefit.
Answer: No setters, final class, deep copies of mutable fields. Immutable objects are inherently thread‑safe. I design value objects like Money, Email immutable.
Q72: Record classes – automatic immutability.
Answer: Records are implicitly final and immutable. I use them extensively for DTOs, configuration holders, and API responses.
Q73: Sealed classes vs final – when to allow controlled extension.
Answer: Sealed allows a fixed set of subclasses. For a domain model, sealed interface Document permits Invoice, Receipt ensures exhaustive pattern matching and prevents unknown implementations.
Q74: Constructor injection vs setter injection – field injection pitfalls.
Answer: Constructor injection makes dependencies mandatory and object immutable after creation. Field injection hides dependencies and complicates testing; I prefer constructor injection.
Q75: JavaBeans conventions – and when to break them.
Answer: Getters/setters, no‑arg constructor. I follow them for serialization (Jackson), but for domain objects I prefer immutable design without setters.
Q76: Comparing interfaces – Comparable vs Comparator for business sorting.
Answer: I implement Comparable for a natural order (e.g., by primary key) and supply Comparator lambdas for dynamic sorting in search results, e.g., Comparator.comparing(User::getLastName).
Q77: Null Object pattern – avoiding null checks.
Answer: Instead of returning null, I return a NullCustomer that does nothing. This eliminated countless null checks and prevented NPEs.
Q78: Liskov Substitution Principle violation – a real bug.
Answer: A subclass of Rectangle (Square) changed setWidth/setHeight behavior, violating LSP. Clients using Rectangle broke. Solution: they are separate classes.
Q79: Interface Segregation Principle – a bulky interface problem.
Answer: A large UserService forced clients to implement unused methods. I split it into UserReader, UserWriter, UserDeleter.
Q80: Dependency Inversion – high‑level module not depending on low‑level details.
Answer: An OrderService depends on PaymentProcessor interface, not on StripePaymentProcessor directly. The implementation is injected, making the system flexible.

⚙️ Section 3: Collections & Concurrency (Intermediate)

Q81: ArrayList vs LinkedList – when to use each in a web app.
Answer: ArrayList is O(1) access, good for frequent reads; LinkedList O(1) insert/remove at ends. For a user list page, I use ArrayList; for a job queue with many removals from the head, LinkedList.
Q82: HashMap internal working – and a capacity tuning story.
Answer: Uses buckets, hash, equals. I once tuned initial capacity and load factor to reduce rehashing in a cache that would grow to millions of entries, improving write throughput 30%.
Q83: TreeMap vs HashMap – ordering in an order book.
Answer: TreeMap is sorted; I used it for a price‑sensitive order book where orders must be processed in price‑time priority.
Q84: ConcurrentHashMap – why it’s better than synchronizedMap.
Answer: It allows concurrent reads and striped writes, leading to much better scalability. I replaced a synchronized HashMap in a high‑concurrency metrics collector, and contention dropped significantly.
Q85: CopyOnWriteArrayList – use case and limitation.
Answer: Ideal for read‑heavy scenarios with infrequent writes (e.g., listeners list). I used it for a event listener registry; iteration never throws ConcurrentModificationException.
Q86: BlockingQueue – producer‑consumer with thread safety.
Answer: I used ArrayBlockingQueue to decouple order receiving and processing, automatically blocking when queue is full/empty.
Q87: Stream reduction – reduce vs collect.
Answer: reduce for immutable accumulation (sum); collect with Collector for mutable containers (toList, groupingBy). I prefer collect for building complex results.
Q88: Thread lifecycle – from new to terminated.
Answer: New → Runnable (ready/running) → Blocked/Waiting/Timed Waiting → Terminated. I monitor thread dumps to find stuck threads in production.
Q89: Synchronized vs Lock – explicit lock benefits.
Answer: Lock offers tryLock, timed lock, fairness. I used ReentrantLock for a banking service where we needed to back off instead of blocking indefinitely.
Q90: volatile keyword – visibility, not atomicity.
Answer: volatile ensures read/write visibility across threads. I use it for a simple flag like running in a task, but for counters I use AtomicInteger.
Q91: AtomicInteger – lock‑free increment.
Answer: Uses CAS under the hood. I used it for a unique ID generator, achieving thread‑safe increment without synchronization overhead.
Q92: ExecutorService – thread pool configuration for CPU/IO tasks.
Answer: For CPU‑bound, fixed pool of NCPU threads; for IO‑bound, a larger pool. I tuned a PDF generation service to use a cached thread pool to handle bursty requests.
Q93: Future and CompletableFuture – asynchronous computation.
Answer: I use CompletableFuture.supplyAsync to call external APIs concurrently, then combine results with thenCombine. Reduced dashboard load time from 5s to 1s.
Q94: Deadlock – how you diagnosed and prevented one.
Answer: Two threads hold locks each other needs. I used jstack to find threads in BLOCKED state. Fixed by always acquiring locks in the same order.
Q95: CountDownLatch – waiting for multiple services to start.
Answer: In integration tests, I used a latch to make the main thread wait until all dependent services signaled readiness.
Q96: CyclicBarrier – parallel computation phases.
Answer: In a Monte Carlo simulation, I used CyclicBarrier to synchronize threads at each iteration step.
Q97: Semaphore – limiting concurrent access to a resource.
Answer: I used a semaphore with 5 permits to restrict simultaneous connections to a fragile legacy system.
Q98: ThreadLocal – storing user context per thread.
Answer: In a web app, I stored the current user’s session in a ThreadLocal, making it accessible anywhere in the request thread without passing parameters. Must clear after request!
Q99: Parallel Stream – when to use and when to avoid.
Answer: Good for CPU‑intensive, stateless, and independent tasks on large collections. I avoid it for IO or small datasets; it once slowed a service due to thread overhead.
Q100: Fork/Join pool – recursive task example.
Answer: I used RecursiveTask to compute a large Fibonacci sum, but the real value is in divide‑and‑conquer algorithms like merge sort on big arrays.

🍃 Section 4: Spring Framework (Intermediate to Expert)

🏢 Enterprise Delivery You're the backend lead for a Spring‑based SaaS platform.

Q101: Why Spring Boot over traditional Spring?
Answer: Auto‑configuration, embedded servers, starter dependencies. I delivered a microservice in days instead of weeks, with production‑ready metrics.
Q102: Spring IoC container – BeanFactory vs ApplicationContext.
Answer: ApplicationContext adds AOP, i18n, event publication. I always use it; BeanFactory is lightweight for memory‑constrained devices.
Q103: Bean scopes – singleton, prototype, request, session.
Answer: Singleton (default) one per container; prototype new each time. For a shopping cart, I used session scope to keep user‑specific data.
Q104: Dependency injection types – constructor vs setter vs field.
Answer: Constructor injection preferred for mandatory deps and immutability. Field injection (@Autowired) hides deps; I avoid it except in tests.
Q105: @Component, @Service, @Repository, @Controller stereotypes.
Answer: They are all beans with added semantics: @Repository adds translation of persistence exceptions. I use them to clearly mark layers.
Q106: @Configuration and @Bean – creating beans manually.
Answer: For third‑party classes, I define @Bean in @Configuration. E.g., a RestTemplate bean with custom timeouts.
Q107: Spring Boot auto‑configuration – how @EnableAutoConfiguration works.
Answer: Uses @Conditional annotations and spring.factories to guess needed beans based on classpath. I exclude unwanted autoconfig with exclude attribute.
Q108: Spring AOP – logging and transaction management.
Answer: I use @Aspect with @Around advice to log method execution times, and Spring’s declarative transactions @Transactional leverages AOP under the hood.
Q109: @Transactional – propagation and isolation levels.
Answer: REQUIRED (default) joins existing transaction; REQUIRES_NEW suspends current. In a money transfer, I used REQUIRES_NEW for audit logging to ensure logs are persisted even if transfer fails.
Q110: Spring Data JPA – repository magic and custom queries.
Answer: I extend JpaRepository and define findByEmail; Spring generates implementation. For complex queries, I use @Query with JPQL or native SQL.
Q111: Entity relationships – @OneToMany, @ManyToMany, cascading.
Answer: I model orders and items with @OneToMany, cascade ALL to persist items when saving order. Lazy fetch type prevents loading everything eagerly.
Q112: N+1 problem – solution with @EntityGraph and JOIN FETCH.
Answer: I use @EntityGraph(attributePaths = "items") or @Query("SELECT o FROM Order o JOIN FETCH o.items") to eagerly load collections in one query.
Q113: Spring Security – authentication and authorization flow.
Answer: I configure SecurityFilterChain, UserDetailsService, and PasswordEncoder. Use antMatchers for URL‑based access control. JWT tokens for stateless APIs.
Q114: JWT authentication with Spring Security – filter chain.
Answer: A OncePerRequestFilter extracts token, validates, sets SecurityContext. Stateless, ideal for REST microservices.
Q115: OAuth2 and Spring Security – social login.
Answer: Using spring-boot-starter-oauth2-client, I added Google login with minimal config. Handled redirects and user registration.
Q116: Spring Boot Actuator – production monitoring endpoints.
Answer: /health, /metrics, /env. I integrated with Prometheus for custom metrics and set up alerts for error rates.
Q117: Spring Cloud – Config Server and Bus.
Answer: Centralized configuration; refresh beans via /actuator/refresh or bus. I used it to update feature toggles without restart.
Q118: Service discovery with Eureka – dynamic microservice registration.
Answer: Services register with Eureka, clients lookup by service ID. This enabled seamless scaling of order service instances.
Q119: API Gateway with Spring Cloud Gateway – routing and filters.
Answer: Single entry point that routes to downstream services, adds cross‑cutting concerns (auth, rate limiting). I built a gateway to unify multiple microservices.
Q120: Circuit breaker with Resilience4j – fail‑fast for external calls.
Answer: I wrapped a payment API call with @CircuitBreaker; after failures, the circuit opens, and a fallback method returns a graceful error.
Q121: Spring Batch – processing large file uploads.
Answer: I implemented a batch job that reads CSV, validates, writes to DB with chunk processing. Restartable and transactional.
Q122: Scheduling tasks – @Scheduled vs external cron.
Answer: @Scheduled for simple periodic tasks inside the app (e.g., cache eviction). For production, I prefer external scheduling with monitoring.
Q123: Caching with @Cacheable – Redis integration.
Answer: Annotate service methods; Spring caches return values. I used Redis as cache backend to share cache across instances.
Q124: Spring WebFlux – reactive programming for I/O heavy apps.
Answer: Non‑blocking, event‑loop model. I moved a chat API to WebFlux, handling 10k concurrent users on fewer threads than traditional MVC.
Q125: Testing Spring Boot – @SpringBootTest, MockMvc, TestContainers.
Answer: I write integration tests with TestContainers to spin up PostgreSQL, ensuring real DB interactions. MockMvc for controller tests.
Q126: Exception handling – @ControllerAdvice and @ExceptionHandler.
Answer: Global exception handler maps exceptions to proper HTTP status codes and JSON error responses. I created a business‑aware error model.
Q127: BeanPostProcessor – custom initialization logic.
Answer: I implemented one to inject a logger into beans annotated with @Loggable, reducing boilerplate.
Q128: Environment and profiles – dev, test, prod configurations.
Answer: Use application-{profile}.yml. I set spring.profiles.active=prod via environment variable in deployment.
Q129: Lombok with Spring – reducing boilerplate.
Answer: @Data, @Builder, @Slf4j. But be cautious: @Data includes setters; I often use @Getter and @Builder for immutability.
Q130: ResponseEntity and HTTP status codes best practices.
Answer: Return proper status: 201 for created, 404 for not found, 422 for validation errors. I use ResponseEntity builder with Location header for created resources.
Q131: OpenAPI / Swagger documentation in Spring Boot.
Answer: springdoc‑openapi generates docs from annotations. I added @Operation and @Schema to make API clear for consumers.
Q132: Flyway / Liquibase – database migration in CI/CD.
Answer: I use Flyway to version control DB schema. Migrations run automatically on startup, ensuring all environments are consistent.
Q133: Spring Data Redis – implementing distributed lock.
Answer: I used RedisTemplate with SET NX EX to create a distributed lock for a scheduled task, preventing multiple instances from executing simultaneously.
Q134: File upload handling with Spring – MultipartFile.
Answer: Controller consumes @RequestParam MultipartFile, validates size/type, stores to S3 via Spring Cloud AWS.
Q135: Internationalization (i18n) in Spring – LocaleResolver.
Answer: I use AcceptHeaderLocaleResolver and messages.properties files. All user‑facing messages externalized.
Q136: Spring events – application‑event publishing.
Answer: I publish a CustomerRegisteredEvent, and listeners send welcome email and create audit log. Decouples modules.
Q137: Custom starter – packaging reusable functionality.
Answer: I built a custom starter for company‑wide logging and security, so all microservices could import it with one dependency.
Q138: GraalVM native image with Spring Boot – faster startup.
Answer: Compiling to native binary reduced startup time from seconds to milliseconds, ideal for serverless functions.
Q139: Dockerizing Spring Boot – multi‑stage build.
Answer: I create a Dockerfile that uses a JDK for build and JRE slim for runtime, producing a small image.
Q140: Kubernetes deployment – health probes, configmaps.
Answer: Configure liveness/readiness probes with actuator endpoints. Use ConfigMap for non‑sensitive config, Secrets for passwords.
Q141: Spring Modulith – testing modular monoliths.
Answer: Enforces module boundaries within a monolith. I used it to gradually split a big app into well‑defined modules before eventually microservices.
Q142: GraphQL with Spring – Netflix DGS or Spring for GraphQL.
Answer: I built a GraphQL layer to let mobile clients fetch exactly needed data, reducing payload size by 60%.
Q143: Spring Integration – enterprise integration patterns.
Answer: For a file‑processing pipeline, I used channels and transformers to move data from FTP to database.
Q144: Observability with Micrometer – distributed tracing.
Answer: Micrometer sends metrics to Prometheus, tracing to Zipkin/Jaeger. I added custom timers for critical business operations.
Q145: Spring Security method‑level authorization – @PreAuthorize.
Answer: @PreAuthorize("hasRole('ADMIN')") on service methods. I use it for fine‑grained permission checks.
Q146: Handling concurrent requests in Spring – thread‑safe services.
Answer: By default, services are singletons; I make them stateless. Any shared mutable state goes to a thread‑safe collection or external cache.
Q147: Bean lifecycle callbacks – @PostConstruct and @PreDestroy.
Answer: I use @PostConstruct for initialization after injection, and @PreDestroy to gracefully release resources (e.g., DB pool).
Q148: Spring MVC vs WebFlux – decision factors.
Answer: MVC for traditional blocking (JDBC), WebFlux for non‑blocking (Mongo, Redis reactive). I choose based on stack and expected concurrency.
Q149: CORS configuration in Spring Security.
Answer: Enable CORS with .cors(), define a CorsConfigurationSource bean to restrict origins, methods.
Q150: Rate limiting with Bucket4j and Spring.
Answer: I created a filter that uses Bucket4j to rate‑limit per IP or API key, returning 429 when exceeded.
Q151: Externalized configuration – @Value vs @ConfigurationProperties.
Answer: @ConfigurationProperties for structured config (e.g., mail properties) with validation; @Value for simple keys.
Q152: Spring Boot DevTools – live reload and auto‑restart.
Answer: Speeds up development. Excluded in production.
Q153: Multi‑module Maven/Gradle project – organization.
Answer: I separate domain, application, infrastructure layers into modules to enforce dependency rules.
Q154: Event sourcing and CQRS with Axon Framework + Spring.
Answer: Axon handles aggregates, events, and projections. I built a booking system where all state changes are events, enabling audit and rebuild.
Q155: Spring Cloud Stream – message‑driven microservices.
Answer: Binder abstraction over Kafka/RabbitMQ. I used it to stream order events to analytics service with minimal code.
Q156: Spring Session – session sharing across instances.
Answer: Store session in Redis, making the app horizontally scalable without sticky sessions.
Q157: Custom actuator endpoint – exposing business metrics.
Answer: I created an endpoint to show number of active users, enabling operations to monitor in real‑time.
Q158: Lazy initialization of beans – pros and cons.
Answer: Reduces startup time but delays error discovery. I enable only for specific beans that are rarely used.
Q159: Spring AI – integrating with LLMs.
Answer: Spring AI provides a portable client for OpenAI, Azure AI, etc. I used it to build a customer support bot that understands natural language queries.
Q160: Testing with Mockito and Spring – mocking beans.
Answer: @MockBean replaces a bean in the context for the test. I mock external services to test the business logic in isolation.

🤖 Section 5: Advanced & AI-Powered Java (Expert/Most Expert)

🧠 Cutting Edge Integrating AI/ML, high‑performance, and cloud‑native patterns.

Q161: Integrate OpenAI API with Java Spring Boot.
Answer: Using Spring WebClient, I call the chat completion endpoint, handle streaming responses with Flux. Built a content generation microservice.
Q162: LangChain for Java – building AI chains.
Answer: I use the community‑driven LangChain4j to create chains of prompts, memory, and tools. Implemented an AI assistant that queries internal SQL databases.
Q163: Real‑time sentiment analysis with Java and DL4J.
Answer: I trained an LSTM model on Deeplearning4j, deployed it as a microservice. It scores customer feedback in real time, flagging negatives.
Q164: Calling Python ML models from Java.
Answer: I use ProcessBuilder to execute Python scripts, passing JSON over stdin/stdout. For production, better to wrap Python in a REST API (Flask) and call from Java.
Q165: Apache Kafka Streams with Java for real‑time analytics.
Answer: I built a stream processing app that aggregates clickstream data, computing user engagement metrics in real time.
Q166: Project Loom – virtual threads for high concurrency.
Answer: Virtual threads are cheap; I refactored a REST service to use them, handling 100k concurrent requests with ease, while code remained thread‑per‑request style.
Q167: Panama project – calling native libraries from Java.
Answer: I used jextract to generate Java bindings for a C++ image processing library, achieving near‑native speed.
Q168: GraalVM Truffle – running JavaScript/Python in JVM.
Answer: In a low‑code platform, I embedded a JavaScript engine via GraalVM to let users write custom scripts.
Q169: Java Flight Recorder and JDK Mission Control – performance tuning.
Answer: I profiled a laggy service, found a memory leak in a third‑party library via heap analysis, and fixed it.
Q170: JVM tuning for containerized environments.
Answer: Set -XX:MaxRAMPercentage=75.0, use -XX:+UseContainerSupport. This prevents OOMKilled in Kubernetes.
Q171: Reactive programming with Project Reactor – complex flow.
Answer: I orchestrated a sequence of async calls with flatMap, zip, and error handling. Built a non‑blocking order fulfillment pipeline.
Q172: RSocket – reactive streams over network.
Answer: Implemented a chat service with RSocket for full‑duplex communication, using request‑stream and back‑pressure.
Q173: Microservices resilience patterns – bulkhead, retry, timeout.
Answer: With Resilience4j, I configured bulkhead to limit concurrent calls to a service, retry with exponential backoff, and timeouts to avoid hanging.
Q174: Distributed tracing with OpenTelemetry in Java.
Answer: I instrumented services with Micrometer Tracing, exporting to Jaeger. Visualized request flow across 5 microservices to identify bottlenecks.
Q175: gRPC with Java – high‑performance service communication.
Answer: Defined protobuf contracts, generated stubs. I used it for internal communication where speed and strong typing matter, achieving lower latency than REST.
Q176: Cloud‑native buildpacks – creating OCI images without Dockerfile.
Answer: Spring Boot plugin creates optimized images automatically. I used it for CI pipelines, reducing image size by 40%.
Q177: Design a distributed cache with Java.
Answer: Using Hazelcast or Apache Ignite, embedded into the app, data partitioned across nodes. I used it for session replication and real‑time caching.
Q178: Event sourcing with Kafka and Java.
Answer: All changes are events stored in Kafka. The current state is rebuilt by replaying events. I built a financial ledger that needed full audit trail.
Q179: Chaos engineering in Java – injecting failures.
Answer: I used Chaos Monkey for Spring Boot to randomly kill services, test resilience. Fixed discovered weaknesses.
Q180: Zero‑downtime deployment with Spring Boot.
Answer: Blue‑green deployment in Kubernetes, using Service to switch traffic. Ensure database migrations are backward‑compatible.
Q181: JDK 21 virtual threads vs traditional thread pools.
Answer: Virtual threads allow blocking code without consuming OS threads. I migrated a service with 200 thread pool to virtual threads, simplifying code and increasing throughput.
Q182: Scoped values (JDK 21) – alternative to ThreadLocal.
Answer: Scoped values provide immutable data sharing within a bounded execution context. They are safe with virtual threads.
Q183: Structured concurrency (JDK 21) – better task management.
Answer: Using StructuredTaskScope, I run multiple API calls and handle failures as a unit, improving error handling and observability.
Q184: Foreign Function & Memory API (JDK 22) – off‑heap operations.
Answer: I replaced unsafe reflective hacks with the new safe API to manage off‑heap memory for a high‑performance data structure.
Q185: Vector API (incubator) – SIMD acceleration.
Answer: In an image processing library, I used the Vector API for parallel pixel operations, achieving 4x speedup.
Q186: Building a recommendation engine with Apache Mahout on Java.
Answer: Used collaborative filtering to suggest products. Integrated into a Spring Boot service.
Q187: Using ML pipelines with Apache Spark and Java.
Answer: I wrote Spark jobs in Java to preprocess data and train a classification model, then served predictions via a REST API.
Q188: Integrating Java with blockchain (Web3j).
Answer: I used Web3j to interact with Ethereum smart contracts, enabling crypto payment processing.
Q189: Custom static analysis with Annotation Processors.
Answer: I built an annotation processor that generates builder code at compile time, reducing runtime overhead and boilerplate.
Q190: Ahead‑of‑Time compilation with GraalVM and closed‑world assumptions.
Answer: Native image requires reflection configuration. I supplied metadata and built a startup‑optimized microservice for AWS Lambda.
Q191: Large‑scale batch processing with Spring Cloud Task.
Answer: Short‑lived microservices for batch jobs, deployed on demand. I used it for nightly report generation.
Q192: Reactive relational database access with R2DBC.
Answer: Combined with Spring Data R2DBC, I built a fully reactive data layer for PostgreSQL, avoiding thread blocking.
Q193: Observability with Grafana Loki and Prometheus – custom metrics.
Answer: I expose business KPIs via Micrometer, dashboards in Grafana. Alerts when order success rate drops.
Q194: Serverless Java with AWS Lambda – cold start optimization.
Answer: Using SnapStart (AWS) or GraalVM native image to reduce cold start. I chose a minimal framework like Quarkus for faster boot.
Q195: Multi‑tenancy implementation in Spring Boot.
Answer: Per‑tenant database or schema, resolved via tenant ID header. I used AbstractRoutingDataSource to switch dynamically.
Q196: Circuit breaker with dynamic configuration – feature flag integration.
Answer: I combined Resilience4j with a config server; changing circuit breaker thresholds without redeploy.
Q197: Distributed lock with ShedLock and JDBC.
Answer: Ensures scheduled tasks run only once across instances. Simple table‑based lock.
Q198: API versioning strategies – URL vs header vs content negotiation.
Answer: I prefer URL versioning (/api/v1/) for simplicity. Managed via separate controller classes or request mapping versions.
Q199: Java and MLOps – serving ML models with Spring.
Answer: I deploy models (ONNX, PMML) using libraries like PMML4S, wrap in a REST endpoint, and automate retraining pipeline.
Q200: Continuous Profiling with async‑profiler.
Answer: Low‑overhead profiling in production to find CPU/memory hotspots. I identified a hidden regex compilation bottleneck.
Q201: Code generation with JavaPoet – API client from OpenAPI spec.
Answer: I built a code generator that parses OpenAPI YAML and writes Java interfaces and DTOs using JavaPoet.
Q202: State machine with Spring Statemachine – order fulfillment.
Answer: Defined states and transitions; prevents invalid order status changes. It also triggers actions on state entry.
Q203: Database migration with zero‑downtime – expand‑contract pattern.
Answer: Add new column (expand), app writes to both old and new, eventually remove old (contract). I coordinated with feature flags.
Q204: Building a CLI tool with PicoCLI or Spring Shell.
Answer: Created a admin CLI to trigger batch jobs, view stats. Spring Shell makes it easy to integrate with existing Spring beans.
Q205: Real‑time collaboration with CRDTs in Java.
Answer: I implemented a conflict‑free replicated data type (OR‑Set) for a collaborative document editor backend.
Q206: Migrating from Monolith to Microservices – Strangler Fig pattern.
Answer: Gradually extract functionality as microservices, routing traffic. I used a gateway to proxy to new services while maintaining old endpoints.
Q207: Feature flags with LaunchDarkly or custom toggles.
Answer: I wrapped feature toggles in a service, enabling canary releases and A/B testing without redeployment.
Q208: Embedding a rules engine (Drools) for dynamic business rules.
Answer: Business analysts write rules in Excel; Drools executes them. I used it for insurance underwriting logic.
Q209: Secure coding – OWASP dependency‑check and Snyk in pipeline.
Answer: I automated vulnerability scanning in Maven/Gradle, failing the build on high‑severity issues.
Q210: Java module system and custom runtime image (jlink).
Answer: I created a minimal JRE for a microservice using jlink, cutting image size by 70%.

🧪 Hands-On Labs & Code Exercises

🔬 Lab 1: Build a REST API with Spring Boot – Product CRUD

Create a Product entity, JPA repository, controller with @GetMapping, @PostMapping, @PutMapping, @DeleteMapping. Validate with Bean Validation.

@Entity public class Product { @Id @GeneratedValue Long id; @NotBlank String name; BigDecimal price; }
@Repository public interface ProductRepo extends JpaRepository<Product, Long> {}
@RestController @RequestMapping("/api/products") public class ProductController {
    @Autowired private ProductRepo repo;
    @GetMapping public List<Product> all() { return repo.findAll(); }
    @PostMapping public Product create(@Valid @RequestBody Product p) { return repo.save(p); }
}

🧩 Lab 2: Secure Login with Spring Security & JWT

Implement a login endpoint that issues a JWT, and a filter that validates it. Use BCryptPasswordEncoder.

@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeHttpRequests(auth -> auth.requestMatchers("/api/login").permitAll().anyRequest().authenticated())
       .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

⚡ Lab 3: Asynchronous Order Processing with Queue (RabbitMQ)

Use spring‑rabbit. Send OrderPlacedEvent to queue, consumer processes it. Decouple checkout from inventory update.

@Service public class OrderSender { @Autowired RabbitTemplate rabbitTemplate;
    public void send(Order order) { rabbitTemplate.convertAndSend("order.exchange", "order.key", order); }
}
@RabbitListener(queues = "order.queue") public class OrderConsumer { ... }

🤖 Lab 4: AI Chatbot with Spring AI (OpenAI)

Add spring‑ai‑openai dependency. Create a controller that takes a prompt, calls AiClient, returns response.

@RestController class ChatController {
    private final AiClient aiClient;
    @PostMapping("/chat") String chat(@RequestBody String message) {
        return aiClient.generate(message);
    }
}

📊 Lab 5: Real‑time Dashboard with Server‑Sent Events (SSE)

Spring WebFlux controller returns Flux of events. Each new order pushes SSE to connected browser.

@GetMapping(path = "/orders/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Order> stream() { return orderService.flux(); }

🚀 You've now covered over 210 real‑world Java interview questions. Practice, build the labs, and walk into your interview with confidence. Share your success with @FreeLearning365!

FreeLearning365.com | FreeLearning365.com@gmail.com

Go to Job Interview Portal

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam