Top 40 Java OOP Interview Questions | Must-Prepare before interview.

Top 40 Java OOP Interview Questions | Must-Prepare before interview Work through these 40 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.

  1. Explain the happens-before relationship in the Java Memory Model.

    Thread A writes x=1 without sync; Thread B reads x may see 0 forever. volatile x or synchronized block creates happens-before. Classic DCL singleton needs volatile instance...

    Full answer

  2. Explain the difference between == and .equals() in Java.

    For primitives, == compares values. For objects, == asks if two references point to the same instance. equals() compares content when overridden — String overrides it for...

    Full answer

  3. What is dependency injection and why does Spring use it?

    DI supplies collaborators from outside the class — typically via constructor. Problem solved: tight coupling to concrete classes, hard unit tests, scattered object...

    Full answer

  4. @RestController vs @Controller?

    @Controller is for traditional MVC — return "user/list" view name. @RestController adds @ResponseBody so return types become JSON/XML body — standard for REST APIs. Use...

    Full answer

  5. What is the difference between Comparable and Comparator?

    Comparable built into the type — Employee implements compareTo by id. Comparator external — sort by name or salary without changing Employee. Use...

    Full answer

  6. What is the difference between JPA and Hibernate?

    JPA is the API contract; Hibernate is the engine under Spring Boot by default. You write @Entity per JPA spec; Hibernate handles SQL generation. Spring Data JpaRepository adds...

    Full answer

  7. Explain method overloading vs overriding.

    Overload print(int) and print(String) in one class — compiler picks at compile time. Override toString in subclass — JVM calls subclass version via virtual method table....

    Full answer

  8. Explain sealed classes and their purpose in Java 17+.

    sealed interface Shape permits Circle, Rectangle limits who implements Shape. Compiler verifies switch (Shape s) covers all cases — no default needed. Use for domain variants...

    Full answer

  9. What is the Java Platform Module System (JPMS) and who needs it?

    Use modules when building custom JDK images or publishing strict API boundaries. Typical microservice: no module-info — Spring Boot repackages classpath. Watch for illegal...

    Full answer

  10. How does Bean Validation work in Spring Boot 3?

    DTO fields: @NotBlank, @Email, @Size. Controller: createUser(@Valid @RequestBody UserDto dto). Global @RestControllerAdvice maps MethodArgumentNotValidException to 400 + field...

    Full answer

  11. Explain @ConfigurationProperties vs @Value.

    @ConfigurationProperties(prefix = "app.payment") record PaymentProps(int timeout, String apiUrl) {} — validated, testable, grouped. Use @Value only for single feature flags....

    Full answer

  12. BeanFactoryPostProcessor vs BeanPostProcessor — explain both.

    BFPP: replace ${placeholder} in definitions via PropertySourcesPlaceholderConfigurer. BPP: @Autowired injection, @PostConstruct detection, AOP proxy wrapping. Custom BPP can...

    Full answer

  13. When use @Query native SQL vs JPQL in Spring Data JPA?

    JPQL for standard entity fetches and portable logic. Native for PostgreSQL-specific jsonb queries, recursive CTEs, or performance-tuned index hints after EXPLAIN. Interface...

    Full answer

  14. What is Metaspace and how do class loading issues cause memory leaks?

    Production set MaxMetaspaceSize 256m with monitoring. Investigate Metaspace OOM: heap dump + classloader histogram. Avoid generating unlimited dynamic proxies. OSGi/script...

    Full answer

  15. What do Java Records provide and their limitations?

    DTO: record UserResponse(String id, String name) {} — JSON mapping works. Service layer immutable value objects. Not for entities needing setters/lazy proxies yet. Combine with...

    Full answer

  16. Why does Context re-render every consumer, and how do you keep RBAC/theme from stalling the tree?

    AuthProvider holds user with useMemo. Permission checks go through can(permission) from a hook that reads a stable access object. Theme is a separate provider. High-frequency...

    Full answer

  17. What do Error Boundaries catch, and what do they miss?

    Route-level boundary with a retry that resets the error state. Widget-level boundary around a risky chart. Query/mutation errors stay in the data layer (toast + field errors)....

    Full answer

  18. A table of 10,000 rows janks on scroll. What do you change first?

    I first ask if the API can page or cursor. If the UX needs a long scroll, I virtualize, give each row a stable id, and keep cell renderers pure. I profile with React DevTools —...

    Full answer

  19. What are hidden classes in JDK 15, and which runtime frameworks rely on them?

    I do not write hidden classes in business code. I know JDK 15+ lambdas and several proxy libraries use them so generated bytecode unloads cleanly. If a heap dump shows...

    Full answer

  20. What are sequenced collections in JDK 21, and which calls replace fragile index access?

    I reach for getFirst/getLast on lists and deques instead of magic indexes. For a recent-activity map I use LinkedHashMap as a SequencedMap and pollFirstEntry to evict oldest....

    Full answer

  21. What did generational ZGC change in JDK 21, and when would you pick it over G1?

    For a large-heap, latency-sensitive API I trial generational ZGC in staging: p99 pause, allocation rate, and RSS. I keep G1 if throughput or CPU is the SLO. I never flip...

    Full answer

  22. JDK 25 ScopedValue vs ThreadLocal — what changes in a thread-pool or virtual-thread service?

    Request tenant, correlation id, and security principal go in a ScopedValue.where(CTX, ctx).run(...) around the work. I do not set ThreadLocal in a filter and hope finally runs....

    Full answer

  23. What are compact source files and instance main methods in JDK 25, and would you use them at work?

    I would use compact mains for katas, jbang-style tools, and interview warm-ups. I would not structure a payment service that way. On a panel I say: JDK 25 made this standard so...

    Full answer

  24. Why would a team pin JDK 25 LTS after 21, and what would you verify in staging besides language features?

    I pin 25 when the Boot version supports it, agents are certified, and staging GC/heap histograms look at least as good as 21. I turn on compact headers in a canary if we care...

    Full answer

  25. JDK 27 is not LTS. What do you inherit on upgrade without writing new application code?

    I would not pin 27 as LTS — 25 is still the pin. On a 27 canary I inherit G1 in CI that used to pick Serial, compact headers, and hybrid TLS if the JDK terminates TLS. I...

    Full answer

  26. Why did JDK 27 make G1 the default GC everywhere, and when would you still pick Serial or ZGC?

    First I check the collector in the new CI log. If it flipped Serial → G1, that is JEP 523 — not a 27 regression. I keep G1 in prod with equal heap and a pause goal. I only...

    Full answer

  27. What does hybrid post-quantum TLS in JDK 27 change for a Spring Boot service, and what does it not change?

    If we terminate TLS in the JVM, 27 can negotiate hybrid ML-KEM without a code change — I capture handshake size and CPU. If the edge terminates TLS, I upgrade the ingress...

    Full answer

  28. What is AiServices, and why is it better than calling chat.completions() from a controller?

    AiServices is a typed facade over ChatLanguageModel. I declare TicketAssistant with @SystemMessage and @UserMessage, register it as a singleton @Bean, and the controller never...

    Full answer

  29. HashMap vs ConcurrentHashMap — when and why?

    HashMap for single-threaded or external synchronization. ConcurrentHashMap for shared concurrent maps — finer-grained locking than Hashtable. Cannot store null keys/values in...

    Full answer

  30. What is the difference between ArrayList and LinkedList?

    ArrayList: dynamic array, great for get(i) and iteration, amortized append. LinkedList: node chain, costly random access, only wins for frequent insert/remove in middle with...

    Full answer

  31. Explain immutability and why String is immutable.

    Immutable objects cannot change after build — thread-safe without synchronization. String immutability allows intern pool, caching hashCode, and security when used as...

    Full answer

  32. volatile vs synchronized — when to use each?

    volatile for single-writer flags (shutdown, initialized) where no read-modify-write. synchronized or java.util.concurrent locks when multiple threads update shared state. For...

    Full answer

  33. Explain garbage collection basics in the JVM.

    New objects allocate in Eden; minor GC copies survivors to survivor spaces, then old gen. When old gen fills, major/full GC runs — longer pauses. Tune -Xmx, choose G1 for...

    Full answer

  34. What is Optional and when should you use it?

    Use Optional as return type when absence is expected — findById returns Optional<User>. Chain with map/flatMap/orElseThrow. Do not use for fields, method parameters, or Jackson...

    Full answer

  35. How does Stream API parallel stream work?

    parallelStream() splits work across common pool threads. Good for CPU-heavy map on large in-memory collections. Bad for small lists, IO inside stream, or ordered stateful...

    Full answer

  36. What is an ExecutorService and why use it?

    Instead of new Thread per task, submit Runnable to fixed pool sized to CPU/IO profile. Handle Future results and exceptions. On shutdown hook call shutdown() and...

    Full answer

  37. What are virtual threads in Java 21 and when should you use them?

    Virtual threads excel when code blocks on IO — HTTP clients, JDBC, file reads — allowing one platform thread to serve thousands of concurrent requests. For CPU-heavy parallel...

    Full answer

  38. What is pattern matching for switch (Java 21)?

    Instead of if (obj instanceof String s) { ... }, use switch (obj) { case String s when s.length() > 5 -> ...; case String s -> ...; case null -> ...; default -> ... }. Works...

    Full answer

  39. Why is ThreadLocal problematic with virtual threads?

    Libraries storing per-request state in ThreadLocal allocate one entry per virtual thread — catastrophic memory with 100k concurrent requests. Prefer ScopedValue for request...

    Full answer

  40. How do CompletableFuture and virtual threads compare for concurrency?

    Use virtual threads when business logic is naturally blocking — call DB, call HTTP, return. Use CompletableFuture when composing multiple independent async results with...

    Full answer

Java OOP Interview Questions and Answers · Top 50 Java OOP Interview Questions and Answers (2026 Edition) · Java OOP Interview Questions Every Fresher Must Know · Java OOP Interview Questions for 2–3 Years

All interview question lists · Interview guides · Home · Support the platform