Home › Interview questions
Java & Spring Boot interview questions
179 questions with a short answer, a full explanation and the mistakes interviewers listen for. Every question has a difficulty level from I (Beginner) to V (Expert).
How Java Runs — JDK, JRE, JVM & Your First Program · Java Foundations — Zero to Basics
- What is the difference between the JDK, the JRE and the JVM?I
- What does 'write once, run anywhere' mean and how does Java achieve it?I
- Walk through what happens from a .java file to a running program.II
- Explain the signature `public static void main(String[] args)` piece by piece.I
- Why must a public class's file name match the class name?I
- What is bytecode, and how is it different from machine code?I
- At a beginner level, what is the difference between the stack and the heap?I
- Which Java versions matter, and what is an LTS release?I
Variables, Data Types & Operators · Java Foundations — Zero to Basics
- Java is often described as 'pass-by-value' even for objects. Explain what that actually means and a bug it commonly causes.II
- Why can comparing two Integer objects with == sometimes return true and sometimes false?II
- When would you choose BigDecimal over double, and what is the one mistake people make constructing it?II
- What is integer overflow in Java, why is it silent, and how do you guard against it in production?III
- Explain the difference between the stack and the heap and how it relates to garbage collection and escape analysis.IV
- Why is char a numeric type in Java, and what breaks when you treat a String as a sequence of chars for non-Latin text?III
Control Flow — Loops, Conditionals & Switch · Java Foundations — Zero to Basics
- Compare a traditional switch statement with a switch expression (Java 14+). When would you reach for the new form?II
- What is the difference between break, labeled break, and continue, and when is a labeled break actually justified?II
- Why can an enhanced for-each loop throw ConcurrentModificationException, and how do you remove elements correctly?II
- Explain switch pattern matching (Java 21) and how it changes the way you'd write type-dispatch code.III
- What pitfalls come from comparing floating-point or wrapper values in loop conditions and switch?II
- Why does fall-through exist in switch at all, and how do you exploit it deliberately versus accidentally?II
- What is the difference between an array's length and a String's length in Java?I
- How do you correctly compare the contents of two arrays, and why doesn't == work?I
OOP I — Classes, Objects, Constructors · Java Foundations — Zero to Basics
- Walk through the exact order of initialization when 'new SubClass()' runs, including static and instance initializers.III
- Why is it dangerous to call an overridable method from a constructor?III
- When would you make a class immutable, and what does it take to do it correctly?III
- What problem do static factory methods solve that constructors cannot, and what's the trade-off?III
- Explain what a record is, what it generates, and where a record is the wrong choice.II
- What is the difference between shallow and deep copying, and how does it interact with a copy constructor?II
OOP II — Inheritance, Polymorphism, Interfaces · Java Foundations — Zero to Basics
- Compare composition and inheritance. Why is 'favor composition over inheritance' such a strong rule?II
- Explain method overriding versus overloading, including how the rules differ at compile time versus runtime.II
- What are covariant return types, and what rules constrain an overriding method's signature, exceptions, and visibility?III
- Since Java 8 interfaces can have default methods. Why were they added, and how is the diamond conflict resolved?II
- When should you use an abstract class versus an interface in a modern (Java 8+) codebase?II
- What is the Liskov Substitution Principle, and give a concrete way code violates it.III
OOP III — Encapsulation, Abstraction, Enums · Java Foundations — Zero to Basics
- Encapsulation is more than private fields. What does proper encapsulation actually protect, and how do getters leak it?II
- Why are Java enums the recommended way to implement a singleton, and what else makes enums more than named constants?III
- Explain the difference between abstraction and encapsulation, since interviewers often conflate them.II
- Why should you prefer EnumMap and EnumSet over HashMap and HashSet when keys are enums?II
- What is constant-specific behavior in an enum, and when would you use it instead of a switch?III
- How do access modifiers (private, package-private, protected, public) shape API design, and what's the danger of protected?II
Strings, StringBuilder & String Pool · Java Foundations — Zero to Basics
- Explain the String pool (string interning) and when intern() actually helps versus hurts.III
- Why is repeated String concatenation in a loop a performance problem, and what does the compiler do for non-loop concatenation?II
- Why must String be immutable, and what would break if it weren't?II
- Compare equals(), ==, equalsIgnoreCase(), and compareTo() for Strings, and what's the locale gotcha?II
- What's the difference between StringBuilder and StringBuffer, and when does capacity tuning matter?II
- Why can holding a substring or splitting large strings cause memory issues, and how do you avoid related leaks?IV
Exception Handling & Custom Exceptions · Java Foundations — Zero to Basics
- Explain checked versus unchecked exceptions and the modern argument for preferring unchecked in many designs.II
- Walk through how try-with-resources works and why it's strictly better than finally-based cleanup.II
- What does it mean to 'swallow' an exception, and what are the correct patterns for translation and chaining?II
- How should you design a custom exception hierarchy, and what belongs in the exception itself?III
- What are the performance and correctness costs of exceptions, and why shouldn't you use them for control flow?III
- What is a suppressed exception and when do you encounter one in practice?III
Generics — Wildcards, Bounded Types, PECS · Java Foundations — Zero to Basics
- Explain PECS (Producer Extends, Consumer Super) with a concrete example of choosing the right wildcard.III
- What is type erasure, what does it cost you at runtime, and how do you work around it?III
- Why can't you assign a List<String> to a List<Object>, even though String is an Object?II
- Compare a bounded type parameter <T extends Number> with a wildcard <? extends Number>. When do you need each?III
- Why does Java warn about generic varargs (heap pollution), and what does @SafeVarargs actually assert?IV
- What is a recursive generic bound like <T extends Comparable<T>>, and where does it show up?III
Efficiency & Big-O — Measuring Speed From Zero · Java Foundations — Zero to Basics
- What does Big-O notation actually describe?I
- Why do we drop constants and lower-order terms, so O(2n + 5) becomes O(n)?I
- Which is faster for large n: O(n) or O(n^2), and why?I
- How do you find the Big-O of a piece of code by reading it?II
- What is the difference between time complexity and space complexity?I
- Why do we usually quote the worst case, and what are best/average cases?II
- Why is building a String in a loop with + considered O(n^2)?II
- Give an example where choosing the right data structure changes the Big-O.II
Collections Deep Dive — List, Set, Map, Queue · Java Foundations — Zero to Basics
- Compare ArrayList and LinkedList honestly. Why is LinkedList almost never the right choice in practice?II
- Walk through how HashMap works internally, including resizing and the treeification introduced in Java 8.III
- What exactly is the contract between equals() and hashCode(), and what breaks when you violate it?II
- When would you choose a TreeMap or LinkedHashMap over a plain HashMap?II
- Why is ConcurrentModificationException best-effort, and how do concurrent collections differ from synchronized wrappers?III
- Compare ArrayDeque, Stack, and the various queue choices. What should you actually use for a stack or queue today?II
- How does a HashMap find a value in O(1) on average instead of scanning every entry?II
- What is a hash collision and how does Java's HashMap resolve it?II
- What is the load factor, and what happens when a HashMap exceeds it?II
- Why must equal objects have equal hash codes, and what breaks if they don't?II
Java 8 — Optional, Date/Time API, Method Refs · Java Foundations — Zero to Basics
- What is Optional actually for, and what are the anti-patterns interviewers want you to avoid?II
- Why was java.time introduced to replace Date and Calendar, and what are its key design wins?II
- Distinguish the four method reference forms and when each applies.II
- Why is using the wrong temporal type (e.g., LocalDateTime for a timestamp) a production hazard?III
- Compare Duration and Period, and why does adding a Duration of '24 hours' differ from adding '1 day'?III
- Why is the old SimpleDateFormat dangerous, and what replaced it?II
File I/O — java.io, NIO2 & Files API · Java Foundations — Zero to Basics
- Compare the old java.io streams with NIO.2 (java.nio.file). When do you still reach for streams?II
- Why is buffering critical for I/O performance, and what does a BufferedReader actually save you?II
- What's the difference between Files.lines(), Files.readAllLines(), and Files.readString() for reading a file?II
- How do you walk a directory tree safely, and what are the pitfalls of Files.walk versus Files.walkFileTree?III
- Why should you prefer Path.resolve and avoid string concatenation for file paths, and what's the security angle?III
- What does StandardCopyOption.ATOMIC_MOVE give you, and why does it matter for safe file writes?III
JVM Architecture · JVM Internals & Runtime
- Walk me through the difference between class loading, linking, and initialization, and why the JVM separates them.III
- What is the parent-delegation model and what concrete problems does it prevent?III
- Why does PermGen's removal in Java 8 matter, and what changed operationally with Metaspace?III
- Which runtime data areas are per-thread versus shared, and why does that distinction matter?III
- Why does deep recursion throw StackOverflowError rather than OutOfMemoryError?II
- When and why would you deliberately break parent delegation with a custom or child-first class loader?IV
Collections & Equals/HashCode Contracts · Core & Modern Java (8 -> 21)
- Walk through how HashMap stores and finds an entry, and why a bad hashCode degrades it to O(n).II
- Why must hashCode be consistent with equals, and what breaks if you override one but not the other?II
- What goes wrong if you mutate an object after using it as a HashMap key or HashSet element?II
- Why is implementing compareTo as a.value - b.value a bug, and what should you do instead?III
- When should you reach for a concurrent or copy-on-write collection instead of synchronizing a plain one?III
- Why prefer ArrayDeque over Stack and LinkedList, and List.of over Collections.unmodifiableList?II
IoC, DI & Bean Lifecycle · Spring & Spring Boot
- Walk me through constructor vs setter vs field injection and which you'd use in production.II
- Explain the Spring bean lifecycle from instantiation to destruction, and where AOP proxies appear.III
- What's the difference between @Component, @Service, @Repository, and @Controller? Does the framework treat them differently?II
- You @Autowire a prototype-scoped bean into a singleton service. Why does each call return the same instance, and how do you fix it?III
- How does Spring resolve a dependency when multiple beans implement the same interface, and what are @Primary, @Qualifier, and parameter-name matching doing?II
- Why is @PostConstruct preferred over doing initialization work in the constructor, and what can go wrong if you don't?II
- How does Spring handle circular dependencies, and why is a constructor cycle a design smell rather than something to patch with @Lazy?III
SQL Mastery & Joins · Databases & Persistence
- Explain the difference between INNER, LEFT, RIGHT, and FULL OUTER JOIN, and when an unmatched-row requirement forces an outer join.I
- What's the difference between WHERE and HAVING, and how does that relate to the logical order of query evaluation?II
- How do GROUP BY and aggregate functions handle NULLs, and what surprises people about COUNT?II
- When would you use a correlated subquery versus a JOIN or a window function, and what's the performance concern?III
- Explain window functions and how they differ from GROUP BY, with a concrete example.III
- What's the difference between UNION and UNION ALL, and why does it matter for performance?I
- How do CTEs and self-joins help, and when is a recursive CTE the right tool?III
Scalability Fundamentals · System Design
- When would you scale vertically instead of horizontally, and what makes horizontal scaling harder?II
- A user adds an item to their cart, refreshes, and the cart is empty. What's the likely cause and the fix?III
- How do CAP and its practical cousin PACELC actually drive a design decision?IV
- Why prefer Least Connections over Round Robin, and when do sticky sessions hurt you?III
- You add read replicas and a user reports they don't see their own write. What's happening and how do you fix it?III
- What makes a bad shard key, and why is resharding so painful?III
Microservice Patterns & Architecture · Distributed Systems & Messaging
- A team wants to split a young product into microservices. What pushback and guidance would you give?IV
- Explain circuit breaker states and the specific failure it prevents.III
- How do you handle a request that needs data from five services without killing tail latency?III
- Each microservice owns its data, but a feature needs a join across three services. How do you design it?IV
- What's the difference between liveness and readiness checks in a service mesh / orchestrator, and why conflate them at your peril?IV
- How do you migrate a monolith to microservices with the strangler-fig pattern, and which piece do you extract first?III
Docker & Containers · DevOps: Docker, Kubernetes & Helm
- Why does ordering of Dockerfile instructions matter, and how do you exploit layer caching for a Java build?II
- What does a multi-stage build buy you for a Spring Boot service beyond a smaller image?III
- Your container is PID 1 and doesn't shut down cleanly on a Kubernetes rolling update. What's wrong?III
- Why must you set JVM heap relative to the container memory limit, and what's the failure if you don't?III
- Why run as non-root and what other hardening do you apply to a production image?III
- When should you use a named volume vs a bind mount, and why are containers themselves a bad place to keep data?II
Linux Essentials & Shell · Linux, Networking & Observability
- A Java service is pegging CPU in production. Walk me through diagnosing it on the box with command-line tools.III
- Explain load average versus CPU utilization and why the distinction matters.III
- What is a file descriptor, and how does the 'too many open files' error happen and get fixed?III
- What's the difference between kill -15 and kill -9 for a Spring Boot app, and why prefer one?II
- Why is structured pipeline analysis better than grep alone, and show a couple of one-liners you'd actually use.III
- How do you run a Spring Boot app as a managed service and read its logs without a custom PID script?III
Multi-Module Maven Project Design · Real-World Java Backend Architecture
- Why split a backend into a multi-module Maven build instead of one module, and what's the typical layout?III
- Explain dependencyManagement versus dependencies in a parent POM and why it matters.III
- What is a Maven BOM and how does importing the Spring Boot BOM help?III
- How do you actually enforce module boundaries so they don't erode over time?IV
- How does a clean multi-module layout make a future move to microservices easier or harder?IV
- Should the domain module depend on Spring, and why do people insist it shouldn't?III
Creational Design Patterns · Design Patterns in Java
- Walk me through implementing a thread-safe Singleton, and why is the GoF Singleton often called an anti-pattern?III
- Compare Factory Method, Abstract Factory, and Builder — when would you pick each?III
- In a Spring application, how often do you actually write GoF creational patterns by hand, and why?II
- You see a Builder on a two-field DTO. What's your reaction, and when is a Builder genuinely warranted?IV
- Someone asks you to 'implement clone()' for an object with a mutable list field. How do you respond?III
- When is Prototype the right choice, and how does Spring's @Scope('prototype') relate to it?III
- You're choosing between an object pool and just allocating fresh objects. How do you decide?III
Strings — Practice Programs · Practice Programs — Master Every Pattern
- How do you reverse a string in Java, and which approach is best?I
- What does String.compareTo return, and how does it order strings?I
- Why should you never compare strings with == , and when is it a subtle trap?II
- How do you check if two strings are anagrams efficiently?II
- How do you find the first non-repeating character in a string?II
JVM Internals — Top Interview Q&A · Interview Rapid-Fire — Top Q&A
- What is the difference between Heap and Stack memory?I
- How does the JVM memory model work?III
- Explain the Class Loading lifecycle.III
- What are Bootstrap, Platform, and Application ClassLoaders?II
- How does Garbage Collection work internally?III
- G1 GC vs ZGC vs Serial GC?III
- What triggers a Full GC?III
- How do you identify memory leaks in production?IV
- What is a Heap Dump and when would you analyze it?IV
- How does the JIT Compiler improve performance?II
- What is Escape Analysis?III
- What is Metaspace and how is it different from PermGen?III
- How do you troubleshoot OutOfMemoryError?III
- How do you troubleshoot high CPU usage in JVM applications?IV
- What tools do you use for JVM performance analysis?IV
Start Here — Build Your First AI Feature · Build AI Features as a Java Backend Engineer
- In one or two sentences, what actually happens when an LLM 'answers' a question, and why does that mental model matter for backend design?II
- What is a token, and why do engineers care about tokenization when they are just trying to ship a feature?II
- What is a context window, and how do you design around it when your data is bigger than it?II
- Explain time-to-first-token versus total latency, and why streaming responses to the client is worth the extra complexity.III
- What is the difference between a system prompt and a user prompt, and how do you reliably get structured output like JSON out of a model?II
- How do you evaluate an LLM feature, and why don't ordinary unit tests work?III
- When should you NOT use an LLM, and how do you defend that decision to a product manager who wants AI everywhere?III
- Why can the same prompt give different answers, and what levers control that variability in a backend service?IV
Reading answers is not the same as giving them. Practise out loud with a timed mock interview, flashcards and an AI interviewer — free to start.
Start practising