Learning Resources
Top 100 Interview Q&A
The Top 100 Java interview questions and answers, covering every major area of the language — from basics and OOP to Collections, exceptions, multithreading, and the JVM.
Java Interview Questions & Answers
The most frequently asked Java interview questions, covering every major area of the language — basics and the JVM, OOP, strings and wrappers, exceptions, the Collections Framework, multithreading, memory and class loading, and Java 8+ (lambdas, streams, Optional). Each answer is written the way you should say it in an interview.
Java Basics & Language
Q1–Q14Q1 What is Java and how does it differ from C++?
Answer Java is a class-based, object-oriented language that compiles to bytecode and runs on a JVM. Unlike C++, it has no explicit pointers, no multiple class inheritance, automatic garbage collection, a single-root Object hierarchy, and a large standard library. “Write once, run anywhere” comes from the JVM, not from compiling to native code per OS.
Q2 What are JDK, JRE, and JVM?
Answer JVM executes bytecode. JRE is the JVM plus core libraries needed to run programs. JDK is the JRE plus development tools (javac, javadoc, debugger). You need the JDK to compile; end users often need only a JRE/runtime.
Q3 What is bytecode?
Answer An intermediate, platform-neutral instruction set produced by javac (.class files). The JVM interprets it and/or JIT-compiles hot methods to native code. That is why the same .class files can run on any JVM that supports that class-file version.
Q4 What is the structure of a Java program?
Answer Optional package declaration, imports, then one or more types (class/interface/enum). Execution of an application starts at public static void main(String[] args). The source file name must match the public top-level class.
Q5 Why is main static?
Answer The JVM must call it before any instance exists. A static method belongs to the class, so no object construction is required to start the program.
Q6 Primitive types vs reference types?
Answer Primitives (byte, short, int, long, float, double, char, boolean) hold values directly. Reference types hold a reference to an object on the heap (or null). Collections and generics work with references, which is why wrappers exist.
Q7 What is autoboxing / unboxing?
Answer Automatic conversion between primitives and their wrappers (int ↔ Integer). Convenient, but watch NullPointerException when unboxing a null Integer, and extra allocations in tight loops.
Q8 What is a package?
Answer A namespace that groups related types and maps to a directory tree (com.shop.cart → com/shop/cart). Packages also define the default (package-private) access level. Use reverse-DNS names to avoid collisions.
Q9 Access modifiers in Java?
Answer private: class only. default (no modifier): same package. protected: package plus subclasses (even other packages, with care). public: everywhere. Top-level classes are public or package-private only.
Q10 What does final mean on a variable, method, and class?
Answer Variable: assigned once (blank finals in constructors). Method: cannot be overridden. Class: cannot be subclassed (String, Integer). final references cannot be reseated; the object they point to may still be mutable.
Q11 What does static mean?
Answer A static member belongs to the class, not an instance. Static methods cannot use this/super or instance fields. Static blocks run once when the class is initialised. Overused static state is hard to test and is shared across threads.
Q12 Stack vs heap in Java?
Answer Each thread has a stack of frames (locals, partial results). Objects created with new live on the heap and are GC’d when unreachable. Method-area / metaspace holds class metadata. Interviewers expect “objects on the heap, primitives/locals on the stack”.
Q13 What is the difference between == and equals()?
Answer == on references tests identity (same object). equals() is a method; Object’s default is identity, but String, Integer, and well-written value types override it for content. Always override hashCode when you override equals.
Q14 What is type erasure?
Answer Generic type parameters are checked at compile time and then erased to their bounds (usually Object) in bytecode. That is why you cannot new T(), create T[], or overload two methods that differ only by generic type. Runtime you see raw types plus bridges.
OOP — Classes, Inheritance & Polymorphism
Q15–Q32Q15 What is a class in Java?
Answer A blueprint that defines fields (state) and methods (behaviour). Objects are instances created with new. All classes implicitly extend Object if they do not extend something else.
Q16 What is encapsulation?
Answer Keeping fields private and exposing a controlled public API (getters/setters or better, behaviour methods). It protects invariants and lets you change representation without breaking callers.
Q17 What is abstraction?
Answer Showing essential operations while hiding how they are implemented — via interfaces, abstract classes, or well-designed public methods. Callers depend on what, not how.
Q18 Constructor vs method?
Answer A constructor has the class name, no return type, and runs when new is used. It initialises the object. Methods have a return type (possibly void) and are called on an already-constructed object (or statically).
Q19 What is constructor overloading and constructor chaining?
Answer Several constructors with different parameter lists. this(...) calls another constructor in the same class and must be the first statement. super(...) calls a superclass constructor and likewise must be first if present.
Q20 What does this mean?
Answer A reference to the current instance. Used to disambiguate fields from parameters, return this for fluent APIs, and chain constructors. It does not exist in static methods.
Q21 What is inheritance?
Answer A subclass reuses and extends a superclass (extends) — an “is-a” relationship. Java allows single class inheritance and multiple interface implementation. Prefer composition when the relationship is “has-a”.
Q22 super keyword uses?
Answer super.field / super.method() reach the superclass member. super(...) invokes a superclass constructor. Needed when the superclass has no no-arg constructor or you must call a specific one.
Q23 What is polymorphism?
Answer “Many forms”: the same interface with different behaviour. Compile-time: method overloading. Runtime: overriding via a superclass/interface reference whose actual object decides the method (dynamic dispatch).
Q24 Overloading vs overriding?
Answer Overloading: same name, different parameter lists, same class (or inherited), resolved at compile time by the reference type. Overriding: same signature in a subclass, resolved at runtime by the object type. Return type may be covariant.
Q25 Can you override a static or private method?
Answer No. static methods are hidden, not overridden — the reference type wins. private methods are not visible to subclasses, so a same-named method is a new method. final methods cannot be overridden either.
Q26 Abstract class vs interface?
Answer Abstract class: can have constructors, instance fields, and mixed abstract/concrete methods; a class extends only one. Interface: contract — no instance fields (only public static final constants), multiple implementation; Java 8+ adds default/static methods, Java 9+ private methods. Prefer interfaces for capability; abstract class when you share state and a partial implementation.
Q27 What is a default method?
Answer A concrete method in an interface (Java 8) so you can evolve APIs without breaking implementors. If two interfaces provide the same default, the class must override and pick (or call InterfaceName.super.m()).
Q28 Why can an abstract class have a constructor?
Answer Subclasses call it via super(...) to initialise shared fields. You still cannot write new AbstractType() if the class is abstract.
Q29 What is method hiding?
Answer A subclass declares a static method with the same signature as a superclass static method. Calls through a superclass reference use the superclass method — unlike overriding.
Q30 What is the diamond problem and how does Java handle it?
Answer Two interfaces (or an interface plus a class) supply the same default method. Java forces the class to override and disambiguate. Multiple class inheritance is simply forbidden, so the classic C++ diamond of classes does not occur.
Q31 What is Object and which methods do interviews expect?
Answer The root of the class hierarchy. Know equals, hashCode, toString, getClass, clone (protected, rarely used well), wait/notify/notifyAll, and finalize (deprecated — do not use).
Q32 equals and hashCode contract?
Answer If a.equals(b) then a.hashCode() == b.hashCode(). Unequal objects may share a hash. Always override both together. HashMap/HashSet use hashCode to find a bucket and equals to find the entry — a broken pair loses data.
Strings, StringBuilder & Wrappers
Q33–Q42Q33 Why are Strings immutable?
Answer Security (paths, class names), safe sharing in the string pool, hashCode caching for HashMap keys, and simple thread safety. Concatenation therefore creates new objects — use StringBuilder for loops.
Q34 What is the string constant pool?
Answer A heap area (interned strings) where literals are reused. new String("hi") creates a heap object that may point to the pooled char data; intern() returns the pooled instance. == on two literals is often true; == on new String is usually false.
Q35 String vs StringBuilder vs StringBuffer?
Answer String is immutable. StringBuilder is mutable and unsynchronised — default for single-thread building. StringBuffer is mutable and synchronised — rarely needed now; prefer StringBuilder plus external locking if required.
Q36 How does String concatenation work?
Answer Compile-time constant + is folded. Runtime + typically becomes StringBuilder.append in bytecode (or invokedynamic in newer javac). In a loop, reuse one StringBuilder yourself so you do not allocate a builder per iteration.
Q37 Important String methods to know?
Answer length, charAt, substring, indexOf, contains, startsWith/endsWith, split, replace/replaceAll, trim/strip, toLowerCase/toUpperCase, equals/equalsIgnoreCase, compareTo, isEmpty/isBlank, intern, formatted (newer). substring sharing changed after Java 7u6.
Q38 Is String thread-safe?
Answer Yes, because it is immutable — any “change” is a new object. Sharing a String across threads is safe. Sharing a StringBuilder is not.
Q39 char vs Character vs String of length 1?
Answer char is a 16-bit UTF-16 code unit (not always a full Unicode character). Character is the wrapper. A one-character String is an object and supports equals/hashCode as a String.
Q40 What are wrapper classes?
Answer Object counterparts of primitives: Byte, Short, Integer, Long, Float, Double, Character, Boolean. Needed for collections, generics, and APIs that require objects. They are immutable. Prefer valueOf over new Integer (deprecated constructors).
Q41 Integer caching?
Answer Integer.valueOf caches –128 to 127 (JLS). Integer a = 100; Integer b = 100; a == b may be true, while 200 == 200 on boxed values may be false. Never use == for wrapper equality — use equals.
Q42 How do you convert between String and numbers?
Answer Integer.parseInt / Integer.valueOf, Long.parseLong, Double.parseDouble, and Integer.toString / String.valueOf. parseXxx throws NumberFormatException on bad input — handle it. valueOf returns a wrapper; parseXxx returns a primitive.
Exception Handling
Q43–Q52Q43 What is an exception in Java?
Answer An object representing an abnormal condition, thrown with throw and handled with try/catch/finally or declared with throws. The hierarchy is Throwable → Error and Exception. Recoverable problems should be Exceptions, not Errors.
Q44 Checked vs unchecked exceptions?
Answer Checked (Exception minus RuntimeException) must be caught or declared — e.g. IOException, SQLException. Unchecked (RuntimeException and Error) need not be declared — e.g. NullPointerException, IllegalArgumentException. Use checked for recoverable external failures; unchecked for programming bugs.
Q45 Error vs Exception?
Answer Error (OutOfMemoryError, StackOverflowError) means the JVM is in serious trouble — do not catch and “fix” them in normal code. Exception is for application-level problems you may handle.
Q46 throw vs throws vs Throwable?
Answer throw actually raises an instance. throws lists checked exceptions a method might propagate. Throwable is the root type you can throw/catch.
Q47 try / catch / finally rules?
Answer try needs catch, finally, or both. Multiple catch blocks go from most specific to most general. finally runs for cleanup even after return, unless the JVM exits or the thread is killed. Prefer try-with-resources for AutoCloseable.
Q48 What is try-with-resources?
Answer try (var in = new FileInputStream(path)) { ... } auto-closes resources that implement AutoCloseable. Closures happen in reverse order; suppressed exceptions are attached if close() fails after a primary exception.
Q49 Can a constructor throw exceptions?
Answer Yes. If it throws a checked exception, callers (including subclass constructors via super) must handle or declare it. A failed constructor means the object is not successfully created.
Q50 What happens if finally throws?
Answer It can hide the original exception from the try/catch. That is why finally should be simple (close, unlock) and why try-with-resources is preferred.
Q51 Custom exception best practices?
Answer Extend Exception (checked) or RuntimeException (unchecked) with constructors that take a message and a cause. Do not swallow exceptions empty. Wrap lower-level exceptions when you change abstraction level.
Q52 Does Java have a destructor?
Answer No. finalize() is deprecated and unreliable. Use try-with-resources, AutoCloseable, and Cleaner (or PhantomReference) for native/off-heap resources. GC reclaims memory, not file handles, unless you close them.
Collections Framework
Q53–Q68Q53 What is the Java Collections Framework?
Answer A unified set of interfaces (Collection, List, Set, Queue, Deque, Map) plus implementations (ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, ArrayDeque, PriorityQueue) and algorithms in Collections/Arrays. Map is not a Collection but is part of the framework.
Q54 List vs Set vs Map vs Queue?
Answer List: ordered, index access, duplicates allowed. Set: unique elements. Map: unique keys to values. Queue/Deque: producer-consumer / ends access (FIFO, LIFO, priority).
Q55 ArrayList vs LinkedList?
Answer ArrayList: contiguous array, O(1) get, amortised O(1) add at end, O(n) insert in the middle, better cache locality — default List. LinkedList: doubly linked, O(n) get, cheap add/remove at ends, more memory per node. Prefer ArrayList unless you measure a need for LinkedList.
Q56 HashMap vs Hashtable vs ConcurrentHashMap?
Answer HashMap: unsynchronised, one null key, Java 8+ treeifies long collision bins. Hashtable: legacy, fully synchronised, no nulls — avoid. ConcurrentHashMap: thread-safe segmented/CAS design, no nulls, better concurrency than wrapping HashMap.
Q57 HashMap vs TreeMap vs LinkedHashMap?
Answer HashMap: hash table, unordered, average O(1). TreeMap: red-black tree, sorted keys, O(log n), keys must be Comparable or given a Comparator. LinkedHashMap: hash table plus linked list — insertion or access order (useful for simple LRU).
Q58 HashSet internals?
Answer HashSet is a HashMap whose keys are the set elements and whose values are a dummy present object. Uniqueness and hashing behaviour are therefore the same as HashMap.
Q59 How does HashMap handle collisions?
Answer Entries that hash to the same bucket form a linked list; if a bin grows past a threshold and the table is large enough, Java 8+ converts it to a red-black tree (keys should be Comparable for the tree). Always implement hashCode well to avoid degenerate lists.
Q60 What is the load factor?
Answer How full the table may get before resize (default 0.75). Capacity is number of buckets; size is number of entries. Resize rehashes — expensive, so set initialCapacity if you know the size.
Q61 fail-fast vs fail-safe iterators?
Answer fail-fast (ArrayList, HashMap) detect structural modification via modCount and throw ConcurrentModificationException. fail-safe-style iterators (CopyOnWriteArrayList, ConcurrentHashMap keySet) iterate a snapshot or weakly consistent view and do not throw CME for concurrent writes.
Q62 Iterator vs ListIterator vs Enumeration?
Answer Iterator: hasNext/next/remove for any Collection. ListIterator: bidirectional, can set/add on Lists. Enumeration is the legacy Vector/Hashtable iterator — prefer Iterator.
Q63 Comparable vs Comparator?
Answer Comparable.compareTo defines the class’s natural order (used by TreeSet, Collections.sort). Comparator is a separate object (or lambda) for alternate orders. A class should have one natural order; extra orders are Comparators.
Q64 Stack and Queue in Java?
Answer Prefer Deque (ArrayDeque) over the legacy Stack class (it extends Vector). Queue: LinkedList or ArrayDeque for FIFO; PriorityQueue for heap order (not FIFO). offer/poll/peek are the Queue methods that do not throw on empty (vs add/remove/element).
Q65 Why is Map not a Collection?
Answer A Collection is a group of elements; a Map is a group of key–value mappings. You can view a Map as collections via keySet(), values(), and entrySet().
Q66 How do you sort a List?
Answer Collections.sort(list) or list.sort(comparator) (Java 8). Elements must be Comparable or you pass a Comparator. For arrays use Arrays.sort. TimSort is used for objects.
Q67 What is Collections.unmodifiableList?
Answer A read-only view: mutations throw UnsupportedOperationException. The backing list can still change if you keep a reference to it. List.of / Map.of (Java 9+) create truly immutable collections (no nulls).
Q68 Interview tip for collection complexity?
Answer ArrayList get O(1), add-end amortised O(1). HashMap/HashSet average O(1). TreeMap/TreeSet O(log n). LinkedList get O(n). PriorityQueue offer/poll O(log n). Know that HashMap can rehash and that equals/hashCode matter.
Multithreading & Concurrency
Q69–Q80Q69 How do you create a thread in Java?
Answer Extend Thread and override run(), or implement Runnable (preferred — you keep your class free to extend something else) and pass it to new Thread(runnable). Java 8+: a lambda as Runnable. Start with start(), never rely on calling run() yourself.
Q70 start() vs run()?
Answer start() registers the thread with the JVM and eventually invokes run() on the new call stack. Calling run() directly executes on the current thread — no concurrency.
Q71 What is a daemon thread?
Answer A background thread (setDaemon(true) before start). The JVM exits when only daemon threads remain. GC threads are daemons. Do not put work you must finish (I/O flush) only on a daemon.
Q72 sleep vs wait vs join vs yield?
Answer sleep: pause the current thread; does not release a monitor. wait: must hold the monitor; releases it and waits for notify/notifyAll. join: wait for another thread to finish. yield: hint to the scheduler — rarely useful.
Q73 What does synchronized do?
Answer Acquires the intrinsic lock of an object (this for instance methods, Class object for static). Only one thread holds that lock at a time. It provides mutual exclusion and memory visibility (happens-before). Prefer smaller synchronized blocks or java.util.concurrent locks.
Q74 What is volatile?
Answer A volatile field’s reads/writes go to main memory and establish happens-before between a write and a subsequent read. It does not make i++ atomic. Use it for simple flags; use AtomicInteger or locks for compounds.
Q75 What is a race condition?
Answer The outcome depends on interleaving of threads — typically a read-modify-write without atomicity (lost updates on a counter). Fix with synchronized, locks, or atomic classes.
Q76 What is deadlock and how do you avoid it?
Answer Two or more threads each hold a lock the other needs — circular wait. Avoid by locking in a global order, using tryLock with timeout, shrinking critical sections, and preferring higher-level concurrent collections.
Q77 wait / notify / notifyAll?
Answer Used for condition queues on an object’s monitor. Always wait in a loop that re-checks the condition (spurious wakeups). notify wakes one waiter; notifyAll wakes all. Prefer Condition objects or BlockingQueue in new code.
Q78 Runnable vs Callable vs Future?
Answer Runnable.run() returns void and cannot throw checked exceptions. Callable.call() returns a value and may throw. ExecutorService.submit returns a Future to get the result, cancel, or wait.
Q79 What is an ExecutorService?
Answer A thread-pool abstraction (fixed, cached, scheduled, work-stealing). You submit tasks instead of creating raw Threads. Always shut it down (shutdown / shutdownNow) to avoid leaked non-daemon pool threads.
Q80 Thread-safe collections to name in interviews?
Answer ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue implementations (ArrayBlockingQueue, LinkedBlockingQueue), ConcurrentLinkedQueue. Vector/Hashtable are synchronised but outdated. Collections.synchronizedList is a coarse lock wrapper.
JVM, Memory & Class Loading
Q81–Q90Q81 What are the main JVM memory areas?
Answer Heap (objects, generational GC), metaspace/method area (class metadata), per-thread stacks, PC registers, and native/off-heap memory used by JNI and some buffers. Heap is split into young (Eden + survivor) and old generation in HotSpot.
Q82 How does garbage collection work at a high level?
Answer The GC finds objects unreachable from GC roots (stacks, statics, JNI) and reclaims them. Young-gen minor GCs are frequent; old-gen major/full GCs are rarer and more expensive. You do not call free(); System.gc() is only a hint.
Q83 What are GC roots?
Answer References the GC treats as live: local variables, active thread stacks, static fields, JNI references, and a few VM internals. An object is collectable when no path from any root reaches it.
Q84 Young generation vs old generation?
Answer New objects start in Eden. Survivors of minor GCs move between S0/S1; after enough survivals they are tenured to the old generation. Most objects die young — that is the generational hypothesis.
Q85 What is a ClassLoader?
Answer It loads .class bytes and defines Class objects. Hierarchy: bootstrap (core JDK), platform/extension, then application (classpath). Delegation: ask the parent first (usually) to avoid loading core classes twice. Custom loaders enable plugins and isolation.
Q86 What is the class-loading lifecycle?
Answer Loading, linking (verification, preparation, optional resolution), and initialisation (static blocks and static field initialisers). Initialisation is thread-safe and happens before the first active use.
Q87 OutOfMemoryError vs StackOverflowError?
Answer OOM: heap or metaspace cannot allocate (leaks, huge caches). SOE: too-deep recursion or huge stack frames. Fix OOM by finding retained objects; fix SOE by reducing recursion or increasing stack size only as a last resort.
Q88 What is JIT compilation?
Answer HotSpot interprets first, then compiles “hot” methods to native code (C1/C2). That is why long-running servers can be faster than a short javac+run benchmark implies. -XX flags tune this; know the idea, not every flag.
Q89 What is a memory leak in a GC language?
Answer Unintended retained references — static collections that grow, forgotten listeners, ThreadLocals not removed, caches without eviction. The GC cannot collect objects you still reach.
Q90 String intern and memory?
Answer intern() puts/returns the pooled instance. Over-interning many unique strings can fill the heap (historically PermGen). Intern literals are already pooled; intern user input only when you have a closed set of repeats.
Java 8+ — Lambdas, Streams & Modern APIs
Q91–Q100Q91 What is a lambda expression?
Answer A concise implementation of a functional interface: (args) -> body. It captures effectively final locals. Prefer it over anonymous classes for single-method callbacks (Comparator, Runnable).
Q92 What is a functional interface?
Answer An interface with exactly one abstract method (@FunctionalInterface is optional but documents intent). Examples: Runnable, Callable, Comparator, and java.util.function.* (Predicate, Function, Consumer, Supplier).
Q93 What is a method reference?
Answer A shorthand lambda: String::length, list::add, Person::new. Four kinds: static, instance on a particular object, instance on an arbitrary object of a type, and constructor references.
Q94 How do Streams work?
Answer A pipeline of intermediate ops (filter, map, flatMap, distinct, sorted, limit) that are lazy, plus a terminal op (collect, forEach, reduce, count, anyMatch). Source can be a collection, array, or generator. Do not mutate the source while streaming.
Q95 map vs flatMap?
Answer map wraps each element in a new value (1-to-1). flatMap maps each element to a stream and flattens (1-to-many) — e.g. turning Stream<List<T>> into Stream<T>.
Q96 collect(Collectors.toList()) vs toList()?
Answer Collectors.toList() typically returns a mutable ArrayList. Stream.toList() (Java 16+) returns an unmodifiable list. Collectors.toSet / groupingBy / joining are the other interview staples.
Q97 What is Optional and when should you use it?
Answer A container that may be empty. Use it as a return type to avoid returning null. Do not use Optional for fields, parameters, or collections of Optional. Prefer orElseGet over orElse when the default is expensive; avoid get() without isPresent.
Q98 parallelStream — when is it a bad idea?
Answer Small lists, blocking I/O, or shared mutable state. Parallel streams use the common ForkJoinPool and can starve other tasks. Prefer it for large, CPU-bound, stateless pipelines after measuring.
Q99 What new language features came after Java 8 that interviews mention?
Answer Java 9: modules, private interface methods, List.of. Java 10: local-variable var. Java 11: HTTP client, String.isBlank. Java 14/16: records, pattern matching for instanceof. Java 17 (LTS): sealed classes. Java 21 (LTS): virtual threads, pattern switch, sequenced collections. Name the LTS line (8, 11, 17, 21) and one feature each.
Q100 How should you prepare for a Java interview?
Answer Be fluent in OOP (override vs overload, interface vs abstract), String/immutability, equals/hashCode, the main collections and their complexities, checked vs unchecked, threads (start/synchronized/volatile), JVM heap/GC at a high level, and Java 8 streams/lambdas — plus one project you can walk through end-to-end.