100 Core Java Interview Questions and Answers
Before a big exam, most students don't read the textbook one more time. They pick up a stack of old question papers and work through them, because that is how they find out what they actually know. This page is that stack of papers for Java interviews: 100 questions that interviewers really ask, from the first campus round to a senior engineering panel. None of them repeat the 20 questions in the Java Mock Interview, so together you have 120.
How to Practice
- Pick a level with the buttons below: Easy is fresher and campus level, Medium is for 2 to 5 years of experience, and Hard is senior level.
- Read the question and answer it out loud in under 2 minutes, before you open the answer.
- Open the answer and check whether you covered its key points.
- Missed something? Every answer ends with a link to the lesson that explains it. Read it, then come back to the question in a few days.
Easy Questions (1 to 35)
Fresher and campus level: the basics every interviewer checks first.
1. Why is Java called platform independent?
javac compiles source code to bytecode, not machine code. Bytecode runs on any operating system that has a JVM. The JVM itself is platform-specific; your .class files are not. That is "write once, run anywhere". Revise: Bytecode and Platform Independence.
2. Is Java a purely object-oriented language?
No. Java has primitive types (int, double and so on) that are not objects, and static members that belong to no object. Wrapper classes and autoboxing let primitives act like objects when needed. Revise: OOPs Concepts in Java.
3. Why is main declared public static void?
public so the JVM can call it from outside the class; static so it can be called without creating an object; void because nothing is returned to the JVM (use System.exit(code) to return a status). Since Java 25, the launcher also accepts an instance void main() in compact source files. Revise: The Main Method in Java.
4. Can you overload main?
Yes, like any method. The JVM still starts the program from the standard main(String[] args) signature; the other overloads are just ordinary methods. Revise: The Main Method in Java.
5. List the 8 primitive types and their sizes.
byte 1 byte, short 2, int 4, long 8, float 4, double 8, char 2 (a UTF-16 code unit), and boolean, whose size the specification doesn't fix (in practice 1 byte in arrays). Revise: Data Types in Java.
6. What is the difference between local, instance and static variables?
Local variables live inside a method, on the stack, and have no default value. Instance variables belong to each object, live on the heap and get default values. Static variables belong to the class: one copy shared by all objects. Revise: Java Variables.
7. What is the difference between int and Integer?
int is a primitive holding a value; it can't be null. Integer is an object (a wrapper class): it can be null, can be stored in collections, and has utility methods. Integer.valueOf caches values from −128 to 127. Revise: Wrapper Classes in Java.
8. What is autoboxing, and what is its hidden danger?
Autoboxing is the automatic conversion between primitives and wrappers (int to Integer and back). The dangers: unboxing a null throws NullPointerException; comparing wrappers with == compares references; and boxing in hot loops creates garbage. Revise: Autoboxing and Unboxing in Java.
9. What is the difference between break and continue?
break exits the loop (or switch) completely. continue skips the rest of the current iteration and moves on to the next one. Both can take a label to target an outer loop. Revise: Java Break Statement and Java Continue Statement.
10. Can a constructor be private, final, static or abstract?
It can be private (used for singletons, factories and utility classes). It can't be final, static or abstract: constructors aren't inherited, so these modifiers make no sense. Revise: Private Constructors.
11. When does Java provide a default constructor?
Only when the class declares no constructor at all. The compiler then adds a public no-argument constructor that calls super(). Declaring any constructor removes it. Revise: Constructors in Java.
12. What is the difference between this and super?
this refers to the current object: use it to reach its fields or call another constructor of the same class (this(...)). super refers to the parent part of the object: use it to call a parent method or a parent constructor (super(...)). Revise: Java This Keyword and Java Super Keyword.
13. Can you overload a method by changing only its return type?
No. Overloads must differ in their parameter list (number, types or order). Changing only the return type is a compile error, because a call like m(); would be ambiguous. Revise: Method Overloading in Java.
14. Can a static method use instance variables?
Not directly. A static method has no this, so there is no object whose fields it could read. It can use instance variables only through an object reference that it is given or creates. Revise: Static Methods vs Instance Methods.
15. Does final make an object immutable?
No. final on a reference means the variable can't point to a different object. The object itself can still change: final List<String> list can still have items added. Revise: Java Final Keyword.
16. What are the four access modifiers?
private (same class only), default with no keyword (same package), protected (same package plus subclasses) and public (everywhere). Use the most restrictive one that works. Revise: Access Modifiers in Java.
17. What is a package, and why use one?
A package is a namespace that groups related classes, matching a folder structure. It avoids name clashes (com.shop.model.Order vs com.bank.Order), controls access through package-private visibility, and keeps code organized. Revise: Packages in Java.
18. Which kinds of inheritance does Java support with classes?
Single, multilevel and hierarchical. Multiple inheritance of classes is not allowed (it would create the diamond problem), but a class can implement many interfaces. Revise: Types of Inheritance.
19. What is an interface?
A contract: a set of methods that implementing classes promise to provide. It can also hold constants and default, static and private methods, but no instance state. It lets unrelated classes be used through one type. Revise: Interfaces in Java.
20. What is encapsulation?
Keeping an object's data private and exposing only methods that keep it valid. For example, a BankAccount has a private balance and deposit/withdraw methods that reject invalid amounts, rather than a public field anyone can set. Revise: Encapsulation in Java.
21. What is the difference between String, StringBuilder and StringBuffer?
String is immutable. StringBuilder is mutable and fast, but not thread-safe: use it for building strings in one thread. StringBuffer is mutable and synchronized: thread-safe but slower, and rarely needed today. Revise: Difference Between String and StringBuffer.
22. How do you compare strings by content, ignoring case, and for sorting?
a.equals(b) for exact content, a.equalsIgnoreCase(b) to ignore case, and a.compareTo(b) (or compareToIgnoreCase) for ordering, which returns a negative, zero or positive number. Revise: String Comparison in Java.
23. Can you change the size of an array after creating it?
No; an array's length is fixed. To "grow" one, you create a bigger array and copy (Arrays.copyOf). That is exactly what ArrayList does for you internally. Revise: Copying and Cloning Arrays.
24. What causes ArrayIndexOutOfBoundsException and NullPointerException?
The first: using an index below 0 or at or above length. The second: using a null reference as if it pointed to an object (calling a method, reading a field, or unboxing it). Both are unchecked exceptions that usually mean a bug. Revise: Common Exceptions in Java.
25. What is the difference between Error and Exception?
Both extend Throwable. An Exception is a condition an application may reasonably catch and handle. An Error (such as OutOfMemoryError or StackOverflowError) is a serious JVM-level problem that applications usually shouldn't try to handle. Revise: Exception Hierarchy in Java.
26. What does the throws keyword do?
It declares in a method signature which checked exceptions the method may pass on to its caller, for example void load() throws IOException. The caller must then handle or declare them. throw (without the s) actually throws an exception. Revise: Difference Between Throw and Throws.
27. Can you have a try without a catch?
Yes: try-finally, or try-with-resources, which needs neither catch nor finally. Any exception then propagates to the caller after cleanup. Revise: Try-With-Resources in Java.
28. What is the difference between Integer.parseInt and Integer.valueOf?
parseInt returns a primitive int. valueOf returns an Integer object, reusing cached objects for −128 to 127. Use parseInt when you need a number for arithmetic. Revise: Integer.parseInt() vs Integer.valueOf().
29. What does instanceof do?
It checks whether an object is an instance of a type (class, subclass or interface), and returns false for null. Since Java 16 it can also bind a variable: if (shape instanceof Circle c) { c.radius(); }. Revise: Java Instanceof and Pattern Matching.
30. Why are enums better than int constants?
Enums are type-safe (you can't pass 42 where a Status is expected), readable when printed, work in switch statements, and can have fields, methods and constructors. EnumSet and EnumMap are also very fast. Revise: Enums in Java.
31. Name the methods of the Object class.
equals, hashCode, toString, getClass, clone, wait (3 overloads), notify, notifyAll, and the deprecated finalize. Every class inherits them. Revise: Object Class in Java.
32. Can you force garbage collection?
No. System.gc() is only a hint that the JVM may ignore. The GC runs when the JVM decides. If you feel you need to force it, there is usually a design or memory problem to fix instead. Revise: Garbage Collection in Java.
33. What is the difference between List, Set and Map?
A List is ordered and allows duplicates (access by index). A Set holds no duplicates. A Map stores key-value pairs with unique keys. Map does not extend Collection. Revise: Collections in Java.
34. What is a lambda expression?
A short way to write an implementation of a functional interface (an interface with one abstract method): (a, b) -> a + b. It lets you pass behavior as data, for example to sort, filter or forEach. Revise: Lambda Expressions in Java.
35. Is Java still statically typed when you use var?
Yes. var only asks the compiler to infer the type from the initializer at compile time. The variable still has a fixed type and can't later hold a different type. It works only for local variables. Revise: Local Variable Type Inference.
Medium Questions (36 to 70)
For 2 to 5 years of experience: collections, exceptions, generics, streams and the first threading questions.
36. What happens in a HashMap when two different keys have the same hash code?
It's a collision: both entries go into the same bucket, chained in a list (or a tree once the bucket is large). On get, the map finds the bucket by hash and then uses equals to pick the right key. Many collisions make lookups slower, which is why a good hashCode matters. Revise: HashMap Internal Working.
37. Why should HashMap keys be immutable?
The bucket is chosen from the key's hash code at insertion time. If a field used in hashCode changes afterwards, lookups search the wrong bucket and the entry becomes unreachable: a silent bug and a memory leak. String, wrappers and records make good keys. Revise: Object Equality and Hash Codes in Java.
38. How does HashSet work internally?
It is backed by a HashMap: each element is stored as a key, with one shared dummy object as the value. So add, contains and remove are O(1) on average, and uniqueness depends on equals and hashCode. Revise: HashSet Internal Working.
39. When do you use HashMap, LinkedHashMap or TreeMap?
HashMap: fastest, no order. LinkedHashMap: keeps insertion order (or access order, which is useful for LRU caches). TreeMap: keeps keys sorted, O(log n), with range methods such as headMap, ceilingKey and floorEntry. Revise: Choosing the Right Collection.
40. How does ArrayList grow?
A list built with new ArrayList<>() starts with an empty array and allocates capacity 10 on the first add. When it is full, it grows to about 1.5× (old + old >> 1) and copies the elements with Arrays.copyOf. Pass an initial capacity when you know the size, to avoid repeated copying. Revise: ArrayList Internal Working.
41. How do you safely remove elements while iterating over a list?
Use list.removeIf(x -> condition), or an explicit Iterator and its remove() method. Calling list.remove(...) inside a for-each loop triggers ConcurrentModificationException. Revise: ConcurrentModificationException in Java.
42. What is the difference between Collections.unmodifiableList(list) and List.copyOf(list)?
unmodifiableList returns a read-only view: changes to the original list still show through it. List.copyOf makes an independent, truly immutable copy (and rejects null elements). Revise: Unmodifiable vs Immutable Collections.
43. Sort employees by department, then by salary from highest to lowest.
employees.sort(Comparator.comparing(Employee::department)
.thenComparing(Employee::salary, Comparator.reverseOrder()));Chain the comparators instead of writing one long compare method. Revise: Comparator Chaining in Java.
44. What is the difference between Arrays.asList and List.of?
Arrays.asList is a fixed-size view over the array: set works and writes through to the array, add/remove throw, and null is allowed. List.of is fully immutable and rejects null. Revise: Arrays.asList vs List.of.
45. Does iterating over a PriorityQueue give elements in priority order?
No. It is a binary heap, so only the head is guaranteed to be the smallest (by natural order or comparator). To get elements in order, call poll() repeatedly. offer and poll are O(log n). Revise: Queue Interface and PriorityQueue in Java.
46. What are the exception rules when overriding a method?
An overriding method may throw fewer or narrower checked exceptions than the parent method, but not new or broader ones. It may throw any unchecked exceptions. This keeps callers that use the parent type safe. Revise: Exception Handling with Method Overriding.
47. In try-with-resources, in what order are resources closed, and what happens if close() throws?
Resources close in reverse order of declaration. If the body throws and close() also throws, the body's exception is the one thrown, and the close exception is attached as a suppressed exception (getSuppressed()). Revise: Suppressed Exceptions in Java.
48. What happens if a finally block contains a return?
Its return overrides any value returned from try or catch, and silently discards any exception that was being thrown. Never return from finally. Revise: Finally Block in Java.
49. What is exception chaining, and why keep the cause?
Wrapping a low-level exception in a higher-level one while keeping the original: throw new OrderException("Payment failed", e);. The stack trace then shows "Caused by: …", so the root cause isn't lost. Revise: Chained Exceptions in Java.
50. Why isn't List<String> a subtype of List<Object>?
If it were, you could write List<Object> objs = strings; objs.add(42); and break the list of strings. Generics are invariant to prevent this. Use List<? extends Object> for read-only access. Revise: Generics in Java.
51. What is a bounded type parameter?
A type parameter restricted to a type and its subtypes, so you can call that type's methods: <T extends Comparable<T>> T max(List<T> items) can use compareTo. Multiple bounds use &: <T extends Number & Comparable<T>>. Revise: Bounded Type Parameters in Java.
52. Why can't you create a generic array with new T[10]?
Arrays check element types at runtime, but because of erasure T is unknown at runtime, so the check would be unsafe. Use a List<T>, or Array.newInstance(type, n) with a Class<T> argument. Revise: Restrictions of Generics in Java.
53. What is a functional interface? Can it have default methods?
An interface with exactly one abstract method, so lambdas can implement it. It can also have any number of default and static methods. @FunctionalInterface makes the compiler check the rule. Revise: Functional Interfaces in Java.
54. What are the four kinds of method reference?
Static (Integer::parseInt), bound instance (System.out::println), unbound instance where the first argument becomes the receiver (String::length), and constructor (ArrayList::new). Revise: Method References in Java.
55. What does "effectively final" mean, and why do lambdas need it?
A local variable that is never reassigned after initialization. Lambdas capture a copy of local variables, so Java requires that they don't change; otherwise the lambda and the method would see different values. Revise: Effectively Final Variables and Lambda Capture.
56. What is the difference between reduce and collect?
reduce combines elements into one value using immutable operations (sum, max). collect is a mutable reduction into a container such as a list, map or StringBuilder. For grouping or building collections, use collect. Revise: Collectors Class in Java.
57. Count employees per department with streams.
Map<String, Long> perDept = employees.stream()
.collect(Collectors.groupingBy(Employee::department,
Collectors.counting()));58. What happens when Collectors.toMap meets a duplicate key?
It throws IllegalStateException. Pass a merge function to decide what to do, for example toMap(Employee::id, e -> e, (a, b) -> a) to keep the first one. Revise: groupingBy, partitioningBy, toMap and Joining.
59. What is the difference between findFirst and findAny?
findFirst returns the first element in encounter order. findAny may return any element, which is faster in parallel streams. On sequential streams they usually behave the same. Revise: Parallel Streams in Java.
60. How do static and default methods in interfaces differ?
A default method is inherited by implementing classes and can be overridden. A static interface method is not inherited: you call it as InterfaceName.method(). It is useful for factory and helper methods. Revise: Default, Static and Private Methods in Interfaces.
61. Why does an abstract class have a constructor if you can't instantiate it?
Subclass constructors call it through super(...) to initialize the abstract class's own fields and enforce its rules. Every object of a subclass includes the abstract parent's part. Revise: Abstract Classes and Abstract Methods.
62. What is the difference between a shallow and a deep copy?
A shallow copy copies field values, so referenced objects are shared. A deep copy also copies the referenced objects. clone() is shallow by default and awkward to use correctly; prefer copy constructors or static factory methods. Revise: Object Cloning in Java.
63. Why use BigDecimal for money, and why new BigDecimal("0.1") rather than new BigDecimal(0.1)?
double can't represent most decimal fractions exactly, so sums drift. new BigDecimal(0.1) captures that binary approximation (0.1000000000000000055…); the String constructor or BigDecimal.valueOf(0.1) gives exactly 0.1. Compare with compareTo, because equals also compares scale (2.0 ≠ 2.00). Revise: BigInteger and BigDecimal in Java.
64. What does String.intern() do, and when is it useful?
It returns the canonical copy of the string from the String pool, adding it if needed. It can save memory when many equal strings are created at runtime (for example, repeated values parsed from a file), but adds lookup cost. Use it rarely, and measure first. Revise: String Intern Method in Java.
65. What is serialVersionUID for?
It is a version number for a serializable class. When deserializing, the stored and current values must match, or you get InvalidClassException. Declare it explicitly; otherwise the JVM computes one from the class structure, and even small changes break old data. Revise: Serializable Interface and serialVersionUID.
66. What happens to static and transient fields during serialization?
Neither is written. static fields belong to the class, not the object. transient fields are skipped on purpose (for passwords or caches) and come back with default values (null, 0, false). Revise: Transient Keyword in Java.
67. Which date-time type should you store in a database for a timestamp?
An Instant, meaning a point in time in UTC (or OffsetDateTime). Convert to ZonedDateTime only for display in a user's time zone. LocalDateTime has no zone, so it can't represent an exact moment. Revise: ZonedDateTime, ZoneId and Instant.
68. What are the states in a thread's life cycle?
NEW, RUNNABLE, BLOCKED (waiting for a monitor lock), WAITING (wait, join, park), TIMED_WAITING (sleep, waits with a timeout) and TERMINATED, as listed in Thread.State. Revise: Thread Life Cycle in Java.
69. How do you stop a thread properly?
Ask it to stop with thread.interrupt(). The task checks Thread.currentThread().isInterrupted(), or catches InterruptedException, cleans up, and exits (or restores the flag with Thread.currentThread().interrupt()). Thread.stop() was unsafe and no longer works in modern Java. Revise: Interrupting a Thread in Java.
70. What is a daemon thread?
A background thread that doesn't keep the JVM alive: the JVM exits when only daemon threads remain. Set it with setDaemon(true) before start(). Don't use daemon threads for work that must finish, such as writing files. Revise: Daemon Threads in Java.
Hard Questions (71 to 100)
Senior level: the memory model, concurrency, JVM internals and design trade-offs.
71. What does "happens-before" mean in the Java Memory Model? Give examples.
If action A happens-before action B, B is guaranteed to see A's effects. Rules include: releasing a monitor happens-before the next time another thread acquires that same monitor; a volatile write happens-before later reads of that field; Thread.start() happens-before the started thread's actions; a thread's actions happen-before another thread's join() returns. Without such an edge, a thread may see stale or reordered values. Revise: Java Memory Model and Happens-Before.
72. Explain double-checked locking for a singleton, and why the field must be volatile.
private static volatile Config instance;
static Config get() {
if (instance == null) {
synchronized (Config.class) {
if (instance == null) instance = new Config();
}
}
return instance;
}Without volatile, the write of the reference can be reordered before the constructor finishes, so another thread may see a half-built object. The holder idiom or an enum singleton avoid the problem entirely. Revise: Thread-Safe Singleton in Java.
73. How does ConcurrentHashMap stay thread-safe, and are its compound operations atomic?
It uses CAS to fill empty bins and locks only the first node of a bin for other updates, so threads working on different bins don't block each other; reads are mostly lock-free. putIfAbsent, compute, computeIfAbsent and merge are atomic per key. A separate get followed by put is not. Keep the functions you pass short, and never let them modify the map. Revise: Concurrent Collections in Java.
74. In CompletableFuture, what is the difference between thenApply, thenCompose and thenCombine?
thenApply transforms the result (like map). thenCompose chains a step that itself returns a CompletableFuture (like flatMap, which avoids nested futures). thenCombine joins the results of two independent futures. For errors, exceptionally recovers and handle sees both the result and the exception. Revise: CompletableFuture in Java.
75. What happens to an exception thrown inside a task given to an ExecutorService?
With submit, the exception is captured in the Future and only appears when you call get(), wrapped in ExecutionException. If you never call get(), it is silently lost. With execute, it reaches the thread's uncaught-exception handler and is usually logged. Revise: Callable and Future in Java.
76. How do you choose a thread pool size?
For CPU-bound work, about the number of cores (Runtime.getRuntime().availableProcessors()). For I/O-bound work, more: roughly cores × (1 + wait time / compute time). Use bounded queues, measure under real load, and for heavy blocking I/O consider virtual threads instead. Revise: Types of Thread Pools in Java.
77. When do you use ReentrantReadWriteLock, and what does StampedLock add?
A read-write lock lets many readers in at once but only one writer, which suits data that is read often and written rarely. StampedLock adds optimistic reads: read without locking, then validate(stamp) and retry under a real lock if a write happened. It is faster but not reentrant, and harder to use correctly. Revise: Locks in Java.
78. How can ThreadLocal cause memory leaks?
Pool threads live for a long time, so values stored in a ThreadLocal stay alive after the task ends, and can even leak into the next task that runs on that thread. Always call remove() in a finally block. In application servers, this can also keep whole class loaders in memory. Revise: ThreadLocal in Java.
79. Compare CountDownLatch, CyclicBarrier and Semaphore.
A CountDownLatch lets threads wait until N events have happened; it is one-shot. A CyclicBarrier makes N threads wait for each other at a meeting point, and can be reused. A Semaphore limits how many threads can use a resource at the same time (permits). Revise: Synchronizers in Java.
80. What is work stealing in ForkJoinPool, and what uses the common pool?
Each worker has its own task deque; idle workers steal tasks from the tail of busy workers' deques, which balances divide-and-conquer work. Parallel streams and CompletableFuture's *Async methods without an executor use ForkJoinPool.commonPool(). Blocking calls there can starve the whole application, so pass your own executor for I/O. Revise: Fork/Join Framework in Java.
81. When should you avoid virtual threads?
For CPU-bound work (they add no cores); when you would pool them (create one per task instead); with large per-thread ThreadLocal caches (millions of threads means millions of copies); and around long native calls, which pin the carrier thread. Use them for many concurrent blocking I/O tasks. Revise: Virtual Thread Best Practices.
82. What problems do scoped values and structured concurrency solve?
Scoped values (final in Java 25) share immutable context, such as a request ID or user, with called code and child threads for a bounded scope; they are cheaper and safer than ThreadLocal. Structured concurrency (a preview in Java 25) treats a group of subtasks as one unit: if one fails, the others are canceled, and errors and cancellation propagate cleanly. Revise: Scoped Values in Java and Structured Concurrency in Java.
83. What are the phases of class loading, and when is a class initialized?
Loading (find the bytes, create the Class), linking (verify, prepare static fields with defaults, resolve symbols), then initialization (run static initializers). A class is initialized on first active use: creating an instance, calling a static method, reading a non-constant static field, reflection, initializing a subclass, or being the main class. Revise: Class Loaders in Java.
84. What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is a checked exception thrown when code loads a class by name (Class.forName, a class loader) and it isn't found. NoClassDefFoundError is an error thrown when a class that existed at compile time is missing at runtime, or failed its static initialization earlier. Check the classpath, dependency versions and static initializers. Revise: Class Loaders in Java.
85. Name the different OutOfMemoryError messages and what each means.
Java heap space (heap full: a leak, or the heap is too small); Metaspace (too many classes, often a class loader leak); GC overhead limit exceeded (GC runs constantly but frees almost nothing); unable to create native thread (OS thread limit); Direct buffer memory (off-heap buffers). Each one needs a different fix. Revise: OutOfMemoryError Types and Causes.
86. A Java process is at 100% CPU. How do you find the cause?
Find the hot OS threads (top -H -p <pid>), convert their IDs to hex, take a thread dump (jcmd <pid> Thread.print or jstack), and match the nid values to see which code is running. Also check GC logs, because constant GC looks like high CPU. Use JFR or a profiler for a full picture. Revise: Heap Dumps and Thread Dumps.
87. How does generational garbage collection work, and what does G1 add?
New objects go into Eden. Minor GCs copy live objects to survivor spaces, and objects that survive several collections are promoted to the old generation. This works because most objects die young. G1 divides the heap into equal regions, collects young regions, and runs mixed collections that also clean the old regions with the most garbage, aiming for a pause-time target. Revise: How Garbage Collection Works.
88. When do you use soft, weak and phantom references?
Soft: memory-sensitive caches, cleared before an OutOfMemoryError. Weak: data attached to objects without keeping them alive (WeakHashMap keys, listeners), cleared at the next GC. Phantom: cleanup after an object is gone, which is what Cleaner uses instead of finalize. Revise: Strong, Weak, Soft and Phantom References.
89. Why does Java code get faster after it has been running for a while?
Code starts in the interpreter while the JVM collects profiles. Hot methods are compiled by C1, then optimized by C2 using real runtime data (inlining, escape analysis, removing unneeded checks). Class loading and caches also warm up. This is why benchmarks need warm-up, and why AOT caching (Java 24–25) helps startup time. Revise: Tiered Compilation in Java.
90. What can and can't a record do?
It can validate in a compact constructor, add methods and static fields, implement interfaces and be generic. It can't extend a class (it implicitly extends Record and is final), declare instance fields, or have setters. It is only shallowly immutable, so copy mutable components. Revise: Records in Java.
91. Why are sealed types and pattern matching useful together?
A sealed hierarchy lists every subtype, so a switch over it can be checked for exhaustiveness with no default. When you add a new subtype, the compiler shows you every switch that must handle it. This lets you model data cleanly, for example sealed interface Payment permits Card, Upi, Wallet. Revise: Exhaustive Switch with Sealed Types.
92. Give two concrete consequences of type erasure.
You can't overload m(List<String>) and m(List<Integer>), because both erase to m(List). You can't write obj instanceof List<String> or new T(). A third: List<String>.class doesn't exist; there is only List.class. Revise: Type Erasure in Java.
93. Explain PECS using Collections.copy.
Its signature is copy(List<? super T> dest, List<? extends T> src). The source produces T values, so it uses extends; the destination consumes them, so it uses super. That lets you copy a List<Integer> into a List<Number>. Revise: PECS Rule in Java Generics.
94. What are the costs and limits of reflection in modern Java?
It is slower than direct calls (access checks, boxing, harder for the JIT), although Java 18 rebuilt core reflection on method handles. It skips compile-time checks, so errors appear at runtime. Under the module system, setAccessible(true) on a package that isn't opened throws InaccessibleObjectException. Use MethodHandle for hot paths. Revise: Reflection API in Java.
95. How do JDK dynamic proxies work, and where are they used?
Proxy.newProxyInstance creates a class at runtime that implements the given interfaces and sends every call to an InvocationHandler. Frameworks use proxies for transactions, logging, security and remote calls. Spring uses JDK proxies for interfaces, and generated subclasses (via bytecode libraries) for classes. Revise: Dynamic Proxies in Java.
96. Why is equals hard to get right with inheritance?
If ColorPoint extends Point adds a color, using instanceof in equals breaks symmetry: a point can equal a colored point but not the other way round. Options: compare with getClass() (strict), use composition instead of inheritance, or make value classes final (records are final by design). Revise: Object Equality and Hash Codes in Java.
97. How does String.hashCode stay fast, and how does Java 8 limit the damage from hash collisions?
A String caches its hash code in a field after the first calculation, because it is immutable. If many keys collide (even deliberately, in a hash-flooding attack), Java 8+ HashMap turns large buckets into red-black trees, so the worst case is O(log n) instead of O(n) (most effective when keys are Comparable). Revise: HashMap Internal Working.
98. What are the trade-offs of CopyOnWriteArrayList?
Every write copies the whole array, and iterators work on a snapshot, so reads need no locks and never throw ConcurrentModificationException. It is great for read-mostly lists such as event listeners, and terrible for lists that change often. Revise: Concurrent Collections in Java.
99. Is the default hashCode() the object's memory address?
Not necessarily. The identity hash code is generated on first request (HotSpot uses a thread-local random scheme by default) and stored in the object header, so it stays stable even though GC moves objects. Two different objects can even share an identity hash code. Revise: Object Memory Layout in Java.
100. Walk through what happens when you run new Order().
- If
Orderisn't initialized yet, the JVM loads, links and initializes it (static blocks run). - Memory is allocated, usually by bumping a pointer in the thread's TLAB in Eden (fast and lock-free).
- The memory is zeroed, so fields get default values.
- The object header is set (mark word and class pointer).
- The constructor chain runs (
<init>, fromObjectdown toOrder, with field initializers and instance blocks). - The reference is returned. Escape analysis may even remove the allocation if the object never leaves the method.
Revise: Order of Initialization and Object Memory Layout in Java.
What Next
- Rehearse under time pressure with the Java Mock Interview: 20 more questions in 40 minutes, with a timer and a scorecard.
- Go deeper on one area with the topic pages: Core Java Interview Questions, Collections Interview Questions and Multithreading Interview Questions.
- Write code, too. Most interviews also have a coding round, so keep practicing with Java Programs.
Was this tutorial helpful?