Top 25 Java Interview Questions for Experienced Developer

Java interview questions with clear explanations, examples and best-practice notes

These answers are expanded with concise examples, common pitfalls, and practical usage notes to increase user value, dwell time, and search relevance. Use canonical links and internal anchors when integrating into your site.

1. What is the difference between abstract classes and interfaces in Java?

Short answer: Abstract classes can have both concrete and abstract methods and state; interfaces (since Java 8) can declare default and static methods but cannot hold instance state. A class can extend only one abstract class but implement multiple interfaces.

When to use: Use an abstract class for shared state or common implementation; use interfaces for capability-based design and multiple inheritance of type.

// Abstract class example public abstract class Animal { protected String name; public Animal(String name){ this.name = name; } public abstract void speak(); public void sleep(){ System.out.println("zzz"); } }

// Interface example public interface Flyable { void fly(); default void land(){ System.out.println("landing"); } }

2. How does Java handle memory leaks despite having garbage collection?

Garbage collection reclaims unreachable objects, but memory leaks occur when references remain unintentionally reachable. Common causes: static collections that grow, listener callbacks not removed, caches without eviction, or ThreadLocal values not cleared.

Fixes: use weak/soft references for caches, close resources, remove listeners, and profile with heap analyzers to find retained dominators.

3. What is the difference between fail-fast and fail-safe iterators?

Fail-fast: Detects concurrent modification and throws ConcurrentModificationException (e.g., ArrayList iterator). Fail-safe: Iterates over a clone or snapshot (e.g., CopyOnWriteArrayList), allowing modification of the underlying collection without exception but with potential staleness.

4. Explain the use of the Optional class in Java 8

Use: Wrap possibly-null values to avoid NullPointerException and to express intent in APIs. Prefer Optional as return type for methods that might not return a value; avoid using Optional for fields or collections.

Optional findName(){ return Optional.ofNullable(fetchName()); } findName().ifPresent(name -> System.out.println(name));

5. What is the difference between Callable and Runnable?

Runnable: run() returns void and cannot throw checked exceptions. Callable: call() returns a value and can throw checked exceptions. Use Callable with ExecutorService to get Future results.

6. How does the volatile keyword differ from synchronized?

volatile: ensures visibility of writes to a variable across threads but does not provide atomicity for compound actions. synchronized: establishes a happens-before relationship, provides mutual exclusion and atomicity for the guarded block or method.

7. What is the difference between HashSet and TreeSet?

HashSet: Unordered, constant-time add/contains on average; uses hashCode/equals. TreeSet: Sorted order, backed by a Red-Black tree, O(log n) operations; requires elements to be Comparable or a Comparator.

8. What is the use of transient and static keywords in serialization?

transient: Marks fields to be skipped by default serialization. static: Class-level fields not serialized because they are not part of instance state. For custom control, implement writeObject/readObject.

9. What is the difference between equals() and hashCode()?

Contract: equal objects must have equal hashCodes. equals() checks logical equality; hashCode() returns integer for hash-based collections. When overriding equals(), always override hashCode().

10. What is the Java Memory Model (JMM)?

The JMM defines semantics of multithreaded execution: visibility, ordering guarantees, and atomicity rules for volatile, synchronized, and final fields. It determines when writes by one thread become visible to others and how reordering is permitted.

11. What is the difference between wait(), notify(), and notifyAll()?

wait() releases the monitor and suspends the thread until notified. notify() wakes a single waiting thread; notifyAll() wakes all waiting threads so they can contend for the lock. Use notifyAll() to avoid missed notifications in complex conditions.

12. What is the role of the final keyword in Java?

final variables cannot be reassigned, final methods cannot be overridden, and final classes cannot be subclassed. final fields with proper construction can provide safe publication guarantees.

13. How does Java handle exception propagation?

When an exception occurs, the runtime searches up the call stack for a matching catch block. If not found, the thread terminates. Checked exceptions must be declared or handled; unchecked exceptions (RuntimeException) need not be declared.

14. What is the difference between throw and throws?

throw actually raises an exception instance. throws declares that a method may propagate certain checked exceptions to its caller.

15. What is the use of ThreadLocal in Java?

ThreadLocal provides thread-confined variables: each thread gets its own independent value. Useful for per-thread state like formatters or transaction contexts, but remember to remove values to prevent leaks in thread pools.

16. What is the difference between deep copy and shallow copy?

Shallow copy duplicates references; deep copy duplicates the entire object graph. Deep copy avoids shared mutable state but can be expensive; consider copy constructors or serialization-based cloning with caution.

17. What is the purpose of the enum type in Java?

enum provides type-safe constants with the ability to add fields, methods, and constructors. Use enums for finite sets of values and attach behavior directly to each constant.

18. What are method references in Java 8?

Method references are concise lambda shorthand. Forms: Class::staticMethod, instance::instanceMethod, Class::instanceMethod. They improve readability when directly delegating to existing methods.

19. What is the difference between Stream and ParallelStream?

Stream executes operations sequentially on a single thread; ParallelStream splits work across the ForkJoinPool to execute in parallel. Use parallelism when tasks are CPU-bound, stateless, and order independence is acceptable.

20. What is the use of CompletableFuture?

CompletableFuture supports non-blocking asynchronous programming with methods to chain, combine, and handle results or exceptions. It integrates well with Executor frameworks for scalable async pipelines.

21. What is the difference between SoftReference, WeakReference, and PhantomReference?

SoftReference: retained until memory is low (good for caches). WeakReference: eligible for GC on next cycle when only weak refs remain. PhantomReference: used with ReferenceQueue for post-mortem cleanup actions after finalize phase.

22. What is the use of java.util.concurrent package?

Provides high-level concurrency utilities: ExecutorService, ThreadPoolExecutor, ConcurrentHashMap, CountDownLatch, Semaphore, and more. Prefer these tools over manual thread and lock management.

23. What is the difference between synchronized block and method?

Synchronized method locks the entire method (this or class), while a synchronized block locks a specific object, reducing contention by narrowing the locked section.

24. What is the role of ClassLoader in Java?

ClassLoader loads classes at runtime and follows a delegation model (Bootstrap → Extension → Application). Custom ClassLoaders enable dynamic module loading and plugin systems but require care for security and visibility.

25. What is the difference between instanceof and isInstance()?

instanceof is a compile-time keyword for type checking against a known type. Class.isInstance(object) performs dynamic runtime checking when the Class object is only available at runtime.