Java Interview Questions and Answers
A complete list of 801+ Java interview questions and answers, organized by topic. Click any question to jump straight to its detailed answer with code examples.
9 topics 801 questions
Java Fundamentals
Data Types & Variables
- What are the eight primitive types in Java?
- What is the difference between a primitive and its wrapper class?
- What are autoboxing and unboxing?
- Why does == sometimes return true and sometimes false for equal Integer values?
- What is the difference between == and .equals() in Java?
- Why are Strings immutable in Java?
- What is the String pool (string interning)?
- What is the difference between String, StringBuilder and StringBuffer?
- Is Java pass-by-value or pass-by-reference?
- What are the default values of fields in Java?
- What happens on integer overflow in Java?
- Why is 0.1 + 0.2 not exactly 0.3 in Java?
- What is the char type and how does it relate to int?
- What is the difference between widening and narrowing conversions?
- What is the var keyword and what are its limits?
- What does the final keyword mean for variables?
- What is the difference between static and instance variables?
- How do numeric literals and underscores work in Java?
- What is the ternary operator and a common pitfall with it?
- How are arrays represented in Java?
- How do multidimensional and jagged arrays work?
- How does numeric promotion work in arithmetic expressions?
- What is null and what can and cannot be null in Java?
- What methods does every object inherit from Object?
- What is variable scope in Java?
- When do you need an explicit cast for reference types?
- How do you define a constant in Java?
- How do you convert between Strings and numbers?
- What are the bitwise and shift operators in Java?
- What is the enhanced for loop and its limitations?
- What is the difference between an expression and a statement?
- What are text blocks in Java?
- What are the rules for valid Java identifiers?
Strings
- Why are Strings immutable in Java, and what does that buy you?
- What is the String constant pool?
- What is the difference between String s = "x" and new String("x")?
- What does the intern() method do?
- What is the difference between == and .equals() for Strings?
- How do you compare strings safely when one might be null?
- What is the difference between String, StringBuilder and StringBuffer?
- Why is concatenating strings in a loop with + a problem?
- What does the + operator on strings compile to?
- What is the difference between equals, equalsIgnoreCase and compareTo?
- How does substring work and what are its gotchas?
- How do indexOf, charAt and contains work?
- How does String.split work and what are its surprises?
- What is the difference between replace and replaceAll?
- What is the difference between trim() and strip()?
- What is the difference between isEmpty() and isBlank()?
- Why use char[] instead of String for passwords?
- How do you convert between String, char[] and byte[]?
- How do you convert between Strings and numbers?
- How do String.format, String.join and repeat work?
- What are text blocks in Java?
- How does switch on a String work under the hood?
- How is a String's hashCode computed and why is it cached?
- How do you iterate or process the characters of a String?
Arrays
- What are the ways to declare and initialize an array in Java?
- Is an array a primitive or an object in Java?
- What are the default values of array elements?
- Can you change the size of an array after creation?
- What is the difference between length, length() and size()?
- What happens when you access an index outside an array's bounds?
- What happens if you create an array with a negative size?
- How do multidimensional arrays work in Java?
- What is a jagged (ragged) array?
- How does an array of objects differ from an array of primitives?
- What is array covariance in Java?
- When does ArrayStoreException occur?
- How do you sort an array, including with a Comparator?
- What is Arrays.parallelSort and when would you use it?
- How does Arrays.binarySearch work and what is the catch?
- What do Arrays.fill, Arrays.equals and Arrays.toString do?
- What is the difference between equals/deepEquals and toString/deepToString?
- How do Arrays.copyOf and Arrays.copyOfRange work?
- What is System.arraycopy and how is it different from copyOf?
- Is array clone() a deep or shallow copy?
- What is the gotcha with Arrays.asList?
- How do you convert between an array, a List and a Stream?
- How are varargs related to arrays?
- What is the difference between an array and an ArrayList?
Keywords & Modifiers
- What are the four access modifiers in Java and what do they control?
- What is the difference between private and protected?
- What does the static keyword mean?
- What is the difference between a static member and an instance member?
- What is the difference between a static nested class and an inner class?
- What does final mean for a variable?
- What does final mean for a method or a class?
- What is a blank final and a final parameter?
- Does final make an object immutable?
- How do you define a constant in Java?
- What does the abstract keyword mean for classes and methods?
- Why can't a method be both abstract and final (or abstract and private/static)?
- What does the transient keyword do?
- What does the volatile keyword guarantee?
- What does the synchronized keyword do?
- What is the this keyword used for?
- What is the super keyword used for?
- What does instanceof do, including pattern matching?
- What do the native and strictfp keywords do?
- Which Java keywords are reserved but never used?
- Is var a keyword in Java?
- Can you combine modifiers, and which combinations are illegal?
Java Object-Oriented Programming
Classes & Objects
- What is the difference between a class and an object?
- What is encapsulation and why does it matter?
- What is a constructor and what are its rules?
- How does a constructor differ from a regular method?
- What does the this keyword refer to in Java?
- What is the order of execution when an object is constructed?
- Can a constructor call both this() and super()?
- What are instance and static initializer blocks?
- What does static mean for methods, fields and nested classes?
- What is the difference between instance and static members?
- What does final mean for classes, methods and fields?
- What are the four access modifiers in Java?
- Why use getters and setters instead of public fields?
- What are the types of nested classes in Java?
- What are the ways to create an object in Java?
- When would you make a constructor private?
- How do you design an immutable class?
Inheritance
- What are the four pillars of object-oriented programming?
- What is inheritance and what does Java not allow?
- What is the Object class and what does every class inherit from it?
- What types of inheritance does Java support?
- Why doesn't Java support multiple inheritance of classes?
- What does the super keyword do?
- Are constructors inherited? How are they involved in inheritance?
- What is the difference between upcasting and downcasting?
- What does the instanceof operator do?
- When should you favor composition over inheritance?
- What is the difference between an is-a and a has-a relationship?
- What is the difference between aggregation and composition?
- How do you prevent a class from being subclassed?
- What are cohesion and coupling?
- What is the Liskov Substitution Principle?
- What do the SOLID principles stand for?
Polymorphism
- What is polymorphism and what are its forms?
- What is the difference between overloading and overriding?
- What are the rules for overriding a method?
- What is dynamic method dispatch?
- How does compile-time polymorphism differ from runtime polymorphism?
- What is the difference between static and dynamic binding?
- What is method hiding and how does it differ from overriding?
- What is a covariant return type?
- Can you override a static, final or private method?
- How does the compiler resolve which overload to call?
- How does polymorphism enable programming to an interface?
- How do you call the parent's version of an overridden method?
- How do abstract methods support polymorphism?
- Why is calling an overridable method from a constructor dangerous?
- What practical benefits does polymorphism give you?
Interfaces vs Abstract Classes
- What is abstraction and how is it achieved in Java?
- What is the difference between an abstract class and an interface?
- What is an abstract class and when can't you instantiate one?
- Can an abstract class have a constructor?
- What are default methods in interfaces and why were they added?
- Can an interface have static and private methods?
- Can interfaces have fields? What kind?
- What is a functional interface?
- What is a marker interface?
- Can a class implement multiple interfaces with the same method?
- How do interfaces give Java a form of multiple inheritance?
- How do you decide between an interface and an abstract class?
- If a class extends a class and implements an interface with the same method, which wins?
- What are enums and what can they do beyond constants?
- Can an enum implement an interface or have abstract methods?
equals & hashCode
- What is the difference between == and equals()?
- What is the difference between identity, equality and equivalence?
- What does the default Object.equals() do?
- What is the equals/hashCode contract?
- Why must you override hashCode whenever you override equals?
- What properties must a correct equals() satisfy?
- Should equals() use instanceof or getClass()?
- How do java.util.Objects helpers simplify equals and hashCode?
- Why is it dangerous to use a mutable object as a HashMap key?
- Should compareTo be consistent with equals?
- Why should you compare strings with equals() and not ==?
- Why and how do you override toString?
- How do records implement equals, hashCode and toString?
- What makes a good hashCode implementation?
- What is wrong with Object.clone() and what is the alternative?
Java Generics
Generics Basics
- What are generics and what problem do they solve?
- How do you declare a generic class?
- What are the conventional names for type parameters?
- What is a generic method and how do you declare one?
- How does the compiler infer type arguments for a generic method?
- What is the diamond operator?
- How do you define and implement a generic interface?
- Can a generic type have more than one type parameter?
- How do generics improve type safety over Object?
- What is a raw type and why is it discouraged?
- What is the difference between List, List<Object>, and List<?>?
- Why can't you write new T() inside a generic class?
- Why can't you create a generic array like new T[]?
- Why is List<String> not a List<Object>?
- What is a bounded type parameter?
- When and how do you use @SuppressWarnings("unchecked")?
- How does var interact with generics?
- Can a constructor have its own type parameter?
- Why must a static method declare its own type parameter?
- At a high level, how do generics exist at runtime?
- Why can't you use primitives as type arguments?
- How does the Comparable<T> interface use generics?
Wildcards & Bounded Types
- What is the unbounded wildcard <?> and what does it mean?
- What is the difference between List<?>, List<Object> and a raw List?
- What is an upper-bounded wildcard <? extends T>?
- Why can't you add to a List<? extends Number>?
- What is a lower-bounded wildcard <? super T>?
- What can you read back from a List<? super T>?
- What is the PECS principle?
- When should you use a bounded type parameter <T extends Number> vs a wildcard?
- How do multiple bounds <T extends A & B> work?
- Why does <T extends Comparable<T>> appear so often?
- What is wildcard capture and the capture-helper pattern?
- Why are arrays covariant but generics invariant?
- How do wildcards restore the flexibility lost to invariance?
- Why is Collections.max declared with both extends and super wildcards?
- How does Collection.addAll use wildcards?
- Can you use a wildcard when creating an object with new?
- Why are wildcards discouraged in return types?
- How do nested wildcards like List<List<?>> behave?
- Why does a bounded type parameter, not a wildcard, let you return the element type?
- Why do sort and Comparator parameters use <? super T>?
- What is the get-and-put principle and how does it relate to PECS?
Type Erasure
- What is type erasure in Java generics?
- Why did Java implement generics using type erasure?
- How exactly does the compiler erase generic types?
- What does a bounded type parameter erase to?
- What is the difference between reifiable and non-reifiable types?
- Why is List<String>.class not allowed?
- Why can't you write new T() inside a generic class?
- Why can't you create a generic array like new T[] or new List<String>[]?
- What is heap pollution and how do generic arrays cause it?
- Why can't you use instanceof with a parameterized type?
- What are bridge methods and why does the compiler generate them?
- How can you tell a bridge method apart from a real one?
- Why won't two methods that differ only by generic type parameter compile?
- What is the Class<T> type token pattern and why is it useful?
- How do super type tokens (TypeReference) capture generic types at runtime?
- Why can't a static field or static context use the class type parameter?
- What are the restrictions on generics with exceptions?
- What generic type information actually survives erasure?
- What does @SafeVarargs do and how does it relate to erasure?
- What is an unchecked warning and why does erasure cause it?
- How does Java's erasure differ from reified generics in languages like C#?
Java Collections
Lists, Maps & Sets
- What is the Java Collections Framework?
- What is the difference between List, Set and Map?
- What is the difference between ArrayList and LinkedList?
- How does HashMap work internally?
- What are capacity and load factor in a HashMap?
- What is the difference between HashMap, Hashtable and ConcurrentHashMap?
- What is the difference between HashSet, LinkedHashSet and TreeSet?
- How do HashMap, LinkedHashMap and TreeMap differ?
- What is a fail-fast iterator and ConcurrentModificationException?
- What is the difference between Comparable and Comparator?
- What is the difference between Iterator and ListIterator?
- How does ArrayList grow, and what is amortized O(1)?
- Why are generics used in collections?
- What is type erasure?
- What do the ? extends and ? super wildcards mean (PECS)?
- What are Queue and Deque, and which implementations are common?
- How do you create immutable collections?
- Which collections allow null and which do not?
- What does the Collections utility class provide?
- What are the pitfalls of Arrays.asList()?
- How does a HashSet decide that two elements are duplicates?
- What happens if you use a mutable object as a HashMap key?
- How do you safely remove entries from a Map while iterating?
- Why are Vector and Stack discouraged?
- What do getOrDefault, computeIfAbsent and merge do?
- How does a PriorityQueue work?
- What is the difference between synchronized and concurrent collections?
- When would you use CopyOnWriteArrayList?
- Why must equals and hashCode be consistent for collections to work?
- What navigation methods do TreeMap and TreeSet provide?
- What are EnumSet and EnumMap and why use them?
- How do you build collections from a Stream?
- What is the trap with List.remove and an int argument?
- How do you choose the right collection for a task?
HashMap Internals
- How does a HashMap work internally?
- What is the spread (perturbation) function and why does HashMap apply it?
- How does HashMap convert a hash into a bucket index?
- Why must HashMap capacity always be a power of two?
- Walk through what happens on a put() call.
- Walk through what happens on a get() call.
- How does HashMap handle hash collisions?
- What is treeification and when does it happen?
- What are the default initial capacity and load factor, and what do they mean?
- What happens during a HashMap resize?
- What is the hashCode/equals contract and why must HashMap keys honor it?
- How can a bad hashCode degrade HashMap to O(n)?
- Can a HashMap store null keys and null values?
- What are fail-fast iterators and ConcurrentModificationException?
- Why is HashMap not thread-safe, and what was the infinite-loop bug?
- Why should HashMap keys be immutable?
- What is the difference between HashMap, LinkedHashMap and TreeMap?
- What is the difference between HashMap, Hashtable and ConcurrentHashMap?
- How does ConcurrentHashMap achieve thread safety without a global lock?
- What happens when treeified keys are not Comparable?
- How is HashSet implemented on top of HashMap?
- How should you size a HashMap to avoid resizing?
Set Implementations
- What is the Set interface and what is its core contract?
- How does a Set decide that two elements are duplicates?
- How does HashSet work internally?
- How is LinkedHashSet different from HashSet?
- How does TreeSet work and what ordering does it give?
- What does TreeSet require of its elements?
- Compare HashSet, LinkedHashSet and TreeSet.
- What is the difference between SortedSet and NavigableSet?
- What do floor, ceiling, higher and lower do on a NavigableSet?
- What do headSet, tailSet and subSet return, and are they live views?
- How do you iterate a TreeSet in reverse order?
- Can a TreeSet contain null?
- What is EnumSet and why is it so fast?
- How do you make a Set thread-safe?
- When would you use CopyOnWriteArraySet?
- How do you compute the union of two sets?
- How do you compute the intersection of two sets?
- How do you compute the difference between two sets?
- Why can mutating an element break a HashSet?
- What does Set.of return and what happens with duplicates?
- What ordering guarantees do the different Sets give during iteration?
- Why is HashSet.contains so much faster than List.contains?
Queue & Deque
- What is the Queue interface in Java?
- What are the two method families on Queue (throwing vs returning)?
- What is a Deque and how does it differ from a Queue?
- What are the end-specific methods on Deque?
- How do you use a Deque as a stack?
- Why is ArrayDeque preferred over the legacy Stack class?
- What is the difference between ArrayDeque and LinkedList as a Deque?
- Why does ArrayDeque not allow null elements?
- What is a PriorityQueue and how is it ordered?
- How do you build a max-heap or custom-ordered PriorityQueue?
- Does iterating a PriorityQueue return elements in sorted order?
- What are the time complexities of PriorityQueue operations?
- What is the difference between a bounded and an unbounded queue?
- What is a BlockingQueue and what does it add?
- What are the main BlockingQueue implementations?
- How does a BlockingQueue implement the producer-consumer pattern?
- What is ConcurrentLinkedQueue and when would you use it?
- When do you choose a BlockingQueue over a ConcurrentLinkedQueue?
- Why do most Queue implementations forbid null elements?
- How can you iterate a Deque in both directions?
- What is returned when you poll or peek an empty queue versus remove or element?
Comparable & Comparator
- What is the difference between Comparable and Comparator?
- How do you make a class sortable with Comparable?
- What is the contract of compareTo / compare?
- Why is "return a - b;" a bad way to implement a comparator?
- How does Comparator.comparing build a comparator from a key?
- How do you sort by multiple fields with thenComparing?
- How do you reverse a comparator's order?
- What do Comparator.naturalOrder and reverseOrder return?
- How do you handle null values when sorting?
- Why use comparingInt / comparingLong / comparingDouble?
- What is the difference between Collections.sort and List.sort?
- How does Arrays.sort work with comparators?
- How do you sort a stream?
- How do TreeMap and TreeSet use a comparator?
- How does a PriorityQueue use a comparator?
- What does "consistent with equals" mean for compareTo?
- Why does TreeSet use compareTo instead of equals to detect duplicates?
- What is a stable sort and which Java sorts are stable?
- How do lambdas and method references express comparators?
- Should you store comparators as constants and reuse them?
Java Streams & Functional
Lambdas & Functional Interfaces
- What is a lambda expression in Java?
- What are the different lambda syntax forms?
- What is a functional interface?
- What does the @FunctionalInterface annotation do?
- What are the core interfaces in java.util.function?
- What is the Function interface used for?
- What is the difference between Supplier and Consumer?
- What is the Predicate interface?
- What is the difference between andThen and compose on Function?
- How do you combine predicates with and, or, and negate?
- What is a method reference and what are its four kinds?
- What is the difference between a bound and unbound instance method reference?
- What does "effectively final" mean for variables captured by a lambda?
- Why can't a lambda mutate a captured local variable, and what's the workaround?
- What is the difference between a lambda and an anonymous inner class?
- How are lambdas compiled — do they create a class file?
- What is target typing for a lambda?
- How do you handle checked exceptions in a lambda?
- Why does java.util.function have primitive specializations like IntFunction?
- How are lambdas and method references used to build Comparators?
- What does `this` refer to inside a lambda?
Stream API
- What is a Stream in Java and how does it differ from a collection?
- What are the common ways to create a Stream?
- What is the difference between intermediate and terminal operations?
- What does it mean that streams are lazy?
- What is short-circuiting in a stream pipeline?
- What does the filter operation do?
- What does the map operation do?
- What is flatMap and when do you use it instead of map?
- What do distinct and sorted do, and what is special about them?
- What do limit and skip do?
- What is peek used for and why is it controversial?
- What is reduce and what are its three forms?
- How do count, min, and max work as terminal operations?
- What is the difference between anyMatch, allMatch and noneMatch?
- What is the difference between findFirst and findAny?
- How do you turn a stream back into a collection or array?
- What are IntStream, LongStream and DoubleStream and why use them?
- What is the difference between stateless and stateful operations?
- Why can't a stream be reused, and what happens if you try?
- What are parallel streams and when do they help or hurt?
- Why should you avoid side effects and stateful lambdas in streams?
Collectors & Grouping
- What does the collect() terminal operation do?
- What are the four components of a Collector?
- How do toList, toSet and toCollection differ?
- What is the difference between Collectors.toList() and Stream.toList()?
- How do you collect into an unmodifiable collection?
- How does Collectors.toMap work?
- What is the merge function in toMap and when do you need it?
- What does Collectors.groupingBy do?
- What is a downstream collector in groupingBy?
- How do you transform group elements with the mapping downstream collector?
- How do you count elements per group?
- How do you do multi-level (nested) grouping?
- What is partitioningBy and how does it differ from groupingBy?
- How does Collectors.joining work?
- What do the summing and averaging collectors return?
- What is summarizingInt and IntSummaryStatistics?
- When would you use the reducing collector instead of Stream.reduce?
- What does collectingAndThen do?
- What are the filtering and flatMapping downstream collectors?
- What is the teeing collector?
- What are Collector characteristics?
- How do you write a custom Collector with Collector.of?
Optional
- What is Optional and what problem does it solve?
- How do you create an Optional with Optional.of?
- What are Optional.ofNullable and Optional.empty?
- What do isPresent and isEmpty do?
- Why should you avoid calling get on an Optional?
- What does ifPresent do?
- What is ifPresentOrElse?
- How does Optional.map work?
- When do you use flatMap instead of map?
- What does Optional.filter do?
- What is the difference between orElse and orElseGet?
- What does orElseThrow do?
- What does the or method do?
- How does Optional.stream bridge to the Stream API?
- What are OptionalInt, OptionalLong and OptionalDouble?
- Why shouldn't you use Optional for fields or method parameters?
- Why shouldn't you wrap a collection in Optional?
- Why should a method that returns Optional never return null?
- Is Optional serializable, and why does that matter?
- What is the performance cost of Optional?
Java Exceptions
Exception Handling
- What is an exception in Java?
- What does the Java exception hierarchy look like?
- What is the difference between checked and unchecked exceptions?
- What is the difference between Error and Exception?
- What are try, catch and finally blocks?
- Does finally always run? Are there exceptions?
- What is try-with-resources?
- What is AutoCloseable and how do you use it?
- What is multi-catch and when is it useful?
- What is the difference between throw and throws?
- How do you create a custom exception?
- What is exception chaining (the cause)?
- What does it mean to "swallow" an exception and why is it bad?
- Why does catch block order matter?
- What causes a NullPointerException and how do you prevent it?
- How does Optional help with null handling?
- What is a stack trace and how do you read it?
- What happens when both try and finally have a return?
- What are suppressed exceptions?
- What are the ways to rethrow an exception?
- What are best practices for exception handling?
- Why are exceptions expensive, and what is the cost?
- Should a custom exception be checked or unchecked?
- Why should you avoid catching Throwable or Exception broadly?
- What is exception translation across layers?
- What is the assert keyword and how does it relate to exceptions?
- How do nested try blocks and exception propagation work?
- What happens to an uncaught exception in a thread?
- When do you use IllegalArgumentException vs IllegalStateException?
- Why is manual finally cleanup error-prone compared to try-with-resources?
- What is more precise rethrow analysis (Java 7+)?
- What happens if an exception is thrown in a static initializer?
- Should you log and throw, or just one?
try-with-resources
- What is try-with-resources and what problem does it solve?
- What did the equivalent cleanup code look like before try-with-resources?
- What is the AutoCloseable interface?
- What is the difference between Closeable and AutoCloseable?
- Why does AutoCloseable.close() declare a broader exception than Closeable.close()?
- What does it mean that Closeable.close() must be idempotent?
- How does the compiler translate try-with-resources?
- In what order are multiple resources closed?
- How do you manage multiple resources in one try-with-resources statement?
- What are suppressed exceptions?
- How does try-with-resources fix the "lost exception" bug of try/finally?
- What are getSuppressed() and addSuppressed()?
- What is the effectively-final resource form added in Java 9?
- Can try-with-resources have catch and finally blocks?
- How do you write your own AutoCloseable resource?
- What happens if close() throws and the body completes normally?
- Are resources closed if the body returns early or throws?
- What happens if a later resource's constructor throws during initialization?
- Compare try-with-resources with try/finally.
- What happens if a resource expression evaluates to null?
- Why is try-with-resources not a drop-in replacement for lock/unlock?
Custom Exceptions
- Why would you create a custom exception instead of using a built-in one?
- Which class should a custom exception extend?
- What are the four standard constructors a custom exception should provide?
- How do you decide between a checked and an unchecked custom exception?
- What is the argument against checked exceptions?
- What is exception chaining and why does it matter?
- What is the difference between the cause constructor and initCause()?
- What does getCause() return and when is it useful?
- How can you accidentally lose a stack trace, and how do you preserve it?
- What does it mean to swallow an exception and why is it dangerous?
- How do you add custom data to an exception?
- What is the naming convention for exception classes?
- Why should a custom exception be serializable and how?
- Should custom exceptions be immutable?
- Why should you not extend Throwable or Error directly?
- When is creating a custom exception overkill?
- Can you throw an exception from a constructor, and what are the implications?
- What does it mean to rethrow an exception?
- What is exception translation and why is it a best practice?
- What is the difference between business and technical exceptions?
- Why do many modern Java codebases default to unchecked exceptions?
Java Concurrency
Threads & Synchronization
- What are the ways to create a thread in Java?
- What is the difference between start() and run()?
- What are the states in a thread's lifecycle?
- What is a race condition?
- What does the synchronized keyword do?
- What does volatile do and what does it not do?
- What is the difference between synchronized and volatile?
- What is a deadlock and how do you prevent it?
- What are livelock and starvation?
- How do wait(), notify() and notifyAll() work?
- What is the difference between sleep() and wait()?
- What is an ExecutorService and why use a thread pool?
- What thread pool types does Executors provide?
- What is the difference between Runnable and Callable, and what is a Future?
- What is CompletableFuture and how does it improve on Future?
- What are the atomic classes and how do they work?
- What is compare-and-swap (CAS)?
- What is ReentrantLock and how does it compare to synchronized?
- What is a ReadWriteLock?
- What is ThreadLocal and when is it used?
- What is the Java Memory Model and happens-before?
- What does it mean for code to be thread-safe?
- How do you implement the producer-consumer pattern?
- What are CountDownLatch and CyclicBarrier?
- What is a daemon thread?
- How does thread interruption work?
- Why is ConcurrentHashMap preferred over synchronized maps?
- What is false sharing?
- How do thread priorities work?
- What is the difference between a synchronized instance method and a static one?
- What is double-checked locking and why does it need volatile?
- What is the difference between blocking and non-blocking algorithms?
- What are virtual threads (Project Loom)?
- What is lock contention and how do you reduce it?
- How do you properly shut down an ExecutorService?
Synchronization & Locks
- What is synchronization and what problem does it solve?
- What is a critical section?
- How does the synchronized keyword work?
- What is the difference between a synchronized method and a synchronized block?
- What object does a synchronized method lock on?
- What does it mean that intrinsic locks are reentrant?
- What memory visibility guarantee does a lock provide?
- How do wait(), notify() and notifyAll() work?
- Why must wait() be called inside a while loop?
- When do you get IllegalMonitorStateException?
- What is the Lock interface and why use it over synchronized?
- Why must you unlock a ReentrantLock in a finally block?
- What does tryLock() do?
- What is lockInterruptibly() and why does it matter?
- What is lock fairness and what is its trade-off?
- What is a ReadWriteLock and when is it useful?
- What is StampedLock and how does it differ from ReadWriteLock?
- How do Condition objects compare to wait/notify?
- What is a deadlock and what four conditions cause it?
- How do you prevent deadlock with lock ordering?
- What are livelock and starvation?
- What object should you synchronize on?
- What are synchronized collections and their limits?
- What is lock granularity (coarse vs fine-grained locking)?
Executors & Thread Pools
- Why use a thread pool instead of creating a new thread per task?
- What is the Executor / ExecutorService / ScheduledExecutorService hierarchy?
- What thread pools do the Executors factory methods create?
- Why is using Executors.* often discouraged in favor of ThreadPoolExecutor?
- What are the core constructor parameters of ThreadPoolExecutor?
- How does a task flow through core pool, queue and max pool?
- What are the four rejection policies and when is a task rejected?
- How do you size a thread pool for CPU-bound vs IO-bound work?
- What is the difference between submit() and execute()?
- What is the difference between Runnable and Callable?
- What is a Future and what can you do with it?
- How are exceptions from a submitted task surfaced?
- What do invokeAll and invokeAny do?
- What problem does CompletableFuture solve over Future?
- What is the difference between thenApply, thenCompose and thenCombine?
- How do you handle errors in a CompletableFuture pipeline?
- What do CompletableFuture.allOf and anyOf do?
- What is the difference between shutdown, shutdownNow and awaitTermination?
- What is the recommended graceful shutdown pattern for an executor?
- How does ScheduledExecutorService schedule periodic tasks?
- How do virtual threads change thread-pool thinking in Java 21?
Concurrent Collections
- Why use java.util.concurrent collections instead of Collections.synchronizedX?
- What goes wrong if multiple threads use a plain HashMap?
- How does ConcurrentHashMap achieve thread-safety?
- Why does ConcurrentHashMap forbid null keys and values?
- What atomic operations does ConcurrentHashMap provide?
- Why is ConcurrentHashMap.size() considered approximate?
- What is the difference between fail-fast and weakly consistent iterators?
- How does CopyOnWriteArrayList work and when should you use it?
- What is CopyOnWriteArraySet?
- What is a BlockingQueue and what makes it "blocking"?
- What are the main BlockingQueue implementations and their differences?
- What is a SynchronousQueue and where is it used?
- What is a DelayQueue?
- How is ConcurrentLinkedQueue different from a BlockingQueue?
- What is ConcurrentSkipListMap and when would you use it?
- What are the atomic classes in java.util.concurrent.atomic?
- How does compareAndSet (CAS) work?
- When should you use LongAdder instead of AtomicLong?
- If each method is thread-safe, why can a sequence of calls still be a race?
- How do you get a concurrent Set in Java?
volatile & Memory Model
- What is the visibility problem in multithreaded Java?
- What is the Java Memory Model and why does it exist?
- What is the happens-before relationship?
- What does the volatile keyword guarantee?
- Why doesn't volatile make count++ thread-safe?
- What is the difference between volatile and synchronized?
- What is the difference between atomicity, visibility, and ordering?
- What is instruction reordering and why is it allowed?
- What is the as-if-serial / single-thread guarantee?
- What is the volatile flag pattern?
- Why does the double-checked-locking singleton need volatile?
- What is safe publication and how do you achieve it?
- What guarantees do final fields provide across threads?
- Why can reads and writes of long and double be non-atomic?
- What are memory barriers (fences) and how do they relate to volatile?
- Does declaring an array volatile make its elements volatile?
- Why doesn't making fields volatile make a multi-field invariant safe?
- When should you use an Atomic class instead of volatile?
- Does synchronized also provide visibility, or only mutual exclusion?
- How does happens-before transitivity enable safe publication?
Java JVM Internals
Memory — Heap & Stack
- What is the difference between the heap and the stack in the JVM?
- What exactly is stored on the stack for each method call?
- Does an object reference live on the stack or the heap?
- How is the Java heap divided internally?
- What is Metaspace and how does it differ from PermGen?
- What causes a StackOverflowError?
- What causes OutOfMemoryError: Java heap space?
- What do -Xms and -Xmx control?
- What is escape analysis and how does it affect heap allocation?
- Why are local variables thread-safe without synchronization?
- What does every Java object carry in memory beyond its fields?
- What is the difference between a Minor GC and a Full GC?
- Where does the String pool live and how does it affect memory?
- What are compressed ordinary object pointers (compressed oops)?
- What is a TLAB (Thread-Local Allocation Buffer)?
- How do soft, weak, and phantom references interact with heap memory?
- What are GC roots and why do they matter?
- When and how would you tune the thread stack size?
- What is native (off-heap) memory in the JVM and what uses it?
- How do you take and analyze a heap dump to diagnose a memory leak?
- What is the weak generational hypothesis and why does it guide GC design?
Garbage Collection
- What is garbage collection in Java and why is it needed?
- How does the mark-and-sweep GC algorithm work?
- Why do modern JVMs use generational garbage collection?
- What is the Serial GC and when is it appropriate?
- What is the Parallel GC and how does it differ from Serial?
- What was the CMS GC and why was it removed?
- How does the G1 garbage collector work?
- What makes ZGC different from G1 and when would you choose it?
- What is Shenandoah GC and how does it compare to ZGC?
- What is a stop-the-world pause in GC and why can't it be fully avoided?
- What are GC roots and why are they the starting point for collection?
- What is finalization in Java and why is it discouraged?
- How do you enable and read GC logs in Java 11+?
- What are the most important GC tuning flags and what do they control?
- When and how does an object get promoted from Young Gen to Old Gen?
- How do soft, weak, and phantom references affect GC behaviour?
- What is a concurrent mode failure in G1 and how do you fix it?
- How do you choose between a throughput-oriented and a latency-oriented GC?
- What does System.gc() do and why should you avoid it?
- What is a safepoint in the JVM and how does it relate to GC?
Class Loading
- What is class loading in the JVM?
- What are the built-in ClassLoaders in the JVM and what does each load?
- What is the parent-delegation model for class loading?
- What are the three phases of class loading — loading, linking, and initialisation?
- What is class identity in the JVM and why can two classes with the same name be different?
- What is the difference between ClassNotFoundException and NoClassDefFoundError?
- Why would you write a custom ClassLoader and how do you do it?
- When does the JVM unload a class and why is this important for dynamic systems?
- What guarantees does the JVM provide about class initialisation and static initialisers?
- What does Class.forName() do and what are its overloads?
- How did the Java 9 module system change class loading?
- What is ServiceLoader and how does it relate to class loading?
- What is a ClassLoader leak and how do you detect and fix it?
- Why does String.class.getClassLoader() return null?
- How does Java support hot-swapping or dynamic class reloading?
Java Modern Java
Records
- What is a record in Java and what problem does it solve?
- What are record components and what does the compiler generate from them?
- Are records immutable? What are the caveats?
- What is a canonical constructor and how can you customise it?
- Can a record have additional constructors beyond the canonical one?
- What are the restrictions that make records different from regular classes?
- Can a record implement an interface?
- How do records compare to Lombok's @Data or @Value?
- How do you use records with Jackson for JSON serialisation?
- How do records interact with pattern matching in switch expressions?
- How do records behave with Java serialisation?
- Can records be generic?
- Can records have static fields and methods?
- Why are records good candidates for Map keys or Set elements?
- Can records be declared locally inside a method?
Sealed Classes
- What are sealed classes in Java and what problem do they solve?
- What is the permits clause and when can it be omitted?
- What modifiers must a permitted subtype carry?
- What is the difference between a sealed class and an abstract class?
- Can interfaces be sealed?
- How do sealed classes enable exhaustive switch expressions?
- How do sealed classes combine with pattern matching?
- When would you use a sealed class instead of an enum?
- Can sealed classes be generic?
- How can you inspect a sealed class's permitted subtypes at runtime?
- How would you model a Result type (success or failure) using sealed classes?
- Why would you mark a permitted subtype as non-sealed?
- What compile errors do sealed classes prevent?
- Does the JDK itself use sealed classes?
Switch Pattern Matching
- What is the difference between a switch statement and a switch expression?
- What is the difference between arrow (→) and colon (:) case labels in switch?
- What does the yield keyword do in a switch expression?
- What is a type pattern in a switch expression?
- What are guarded patterns (when clause) in switch?
- How does pattern matching enforce exhaustiveness for sealed types?
- How does switch handle null in Java 21?
- How do record deconstruction patterns work in switch?
- What is pattern matching for instanceof and how does it relate to switch patterns?
- What is dominance in switch pattern matching and how do you order cases?
- What types can be used as switch selectors in modern Java?
- How do you match multiple values in a single switch case?
- When should you prefer a switch expression over an if-else chain?
- When should you use switch pattern matching versus polymorphism?
Text Blocks
- What are text blocks in Java and what problem do they solve?
- What are the rules for the opening and closing """ delimiters?
- What is incidental whitespace and how does the compiler strip it?
- How does Java handle line endings in text blocks?
- What new escape sequences were introduced for text blocks?
- How do you interpolate values into a text block?
- Is a text block a different type from String?
- Show a realistic example of a text block used for SQL.
- What happens to trailing whitespace on lines inside a text block?
- Show a realistic example of a text block used for HTML.
- How do you control indentation in the output of a text block programmatically?
- In which Java version did text blocks become a standard feature?
instanceof Pattern Matching
- What is pattern matching for instanceof and what problem does it solve?
- What is the scope of the binding variable in instanceof pattern matching?
- How does instanceof pattern matching work with negation?
- Can you combine instanceof pattern matching with other conditions?
- What does instanceof return for null?
- Can a pattern variable shadow an existing variable?
- Why is the old instanceof + cast pattern considered bad practice now?
- Can you use instanceof pattern matching in a ternary expression?
- How does instanceof pattern matching improve the equals() override?
- How does instanceof pattern matching relate to switch pattern matching?
- Can you reassign a pattern binding variable?
- How does instanceof pattern matching work with generic types?
Virtual Threads
- What are virtual threads in Java and what problem do they solve?
- How do virtual threads differ from platform threads?
- What is a carrier thread and how does the JVM schedule virtual threads?
- How do virtual threads enable the thread-per-request model?
- What is thread pinning in virtual threads and how do you avoid it?
- How does ThreadLocal behave with virtual threads and what is the alternative?
- What is structured concurrency and how does it relate to virtual threads?
- When should you NOT use virtual threads?
- What are the different ways to create virtual threads in Java?
- How do you observe and debug virtual threads?
- How do you migrate an existing thread-pool application to virtual threads?
- Do virtual threads replace reactive programming (Project Reactor, RxJava)?
- How can you check at runtime if a thread is a virtual thread?
Record Patterns
- What are record patterns in Java?
- How do record patterns work in switch expressions?
- What are nested record patterns and when are they useful?
- Can you use var in a record pattern?
- How do generic records work with record patterns?
- Can you add a when guard to a record pattern in switch?
- How do record patterns help replace the Visitor pattern?
- What is the scope of variables bound in a record pattern instanceof?
- What happens when a record pattern is matched against null?
- How do record patterns interact with exhaustiveness checking in switch?
- When should you use a record pattern versus calling accessors?
Sequenced Collections
- What are sequenced collections and why were they added in Java 21?
- What methods does SequencedCollection add?
- What is SequencedSet and which classes implement it?
- What is SequencedMap and what methods does it add?
- Which existing Java collections implement the new sequenced interfaces?
- What does the reversed() method return?
- Is list.getFirst() just a synonym for list.get(0)?
- How does SequencedCollection relate to Deque?
- Do Collections.unmodifiableList() and List.of() support SequencedCollection?
- What were the workarounds for getting first/last elements before Java 21?
- When should you use SequencedCollection as a method parameter type?
More ways to practice
The self-quiz is live. Get notified when mock interviews and new question packs drop.
or
Join our WhatsApp Channel