← Back to Home

Java Interview Hub

A quick-reference collection of 150 core Java interview questions with crisp, accurate answers for fast revision.

1. What is Java?

Answer:

Java is a high-level, object-oriented, platform-independent programming language used to develop robust, secure, and portable applications.

2. Why is Java platform independent?

Answer:

Java code is compiled into bytecode, which runs on the JVM (Java Virtual Machine). The JVM converts bytecode into machine-specific code, making Java platform independent.

3. What are the main features of Java?

Answer:

  • Object-Oriented
  • Platform Independent
  • Secure
  • Robust
  • Multithreaded
  • High Performance
  • Distributed

4. What is the difference between JDK, JRE, and JVM?

Answer:

  • JVM: Executes bytecode
  • JRE: JVM + core libraries (runtime environment)
  • JDK: JRE + development tools (compiler, debugger)

5. What is the main() method in Java?

Answer:

The main() method is the entry point of a Java program where execution starts.

public static void main(String[] args)

6. What is Object-Oriented Programming (OOP)?

Answer:

OOP is a programming paradigm based on objects and classes. Core principles: Encapsulation, Inheritance, Polymorphism, Abstraction.

7. What is the difference between == and .equals()?

Answer:

  • == compares object references
  • .equals() compares object content (logical equality)

8. What is Encapsulation?

Answer:

Encapsulation is the process of wrapping data and methods together and restricting direct access using access modifiers (private fields with public getters/setters).

9. What is the difference between Array and ArrayList?

Answer:

  • Array: Fixed size, faster, can store primitives
  • ArrayList: Dynamic size, slower than array, stores only objects

10. What is Exception Handling in Java?

Answer:

Exception handling is a mechanism to handle runtime errors using try, catch, finally, throw, and throws to maintain normal program flow.

11. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

  • String: Immutable
  • StringBuilder: Mutable, not thread-safe, faster
  • StringBuffer: Mutable and thread-safe, slower than StringBuilder

12. What is the final keyword in Java?

Answer:

final can be used to make a variable constant, prevent method overriding, or prevent class inheritance.

13. What is method overloading?

Answer:

Method overloading allows multiple methods with the same name but different parameter lists within the same class.

14. What is method overriding?

Answer:

Method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass.

15. What is the difference between static and non-static members?

Answer:

  • static: Belongs to the class, shared across objects
  • non-static: Belongs to the object, requires object creation

16. What is a constructor?

Answer:

A constructor is a special method used to initialize objects. It has the same name as the class and no return type.

17. What is the this keyword?

Answer:

this refers to the current object of the class and is used to differentiate instance variables from local variables.

18. What is the difference between abstract class and interface?

Answer:

  • Abstract class: Can have abstract and non-abstract methods, supports constructors
  • Interface: Supports only abstract methods (before Java 8), supports multiple inheritance

19. What is the super keyword?

Answer:

super is used to access parent class variables, methods, or constructors.

20. What is garbage collection in Java?

Answer:

Garbage collection is the automatic memory management process that removes unused objects to free heap memory.

21. What are access modifiers in Java?

Answer:

Access modifiers control the visibility of classes, methods, and variables. Java provides public, protected, default (package-private), and private.

22. What is the difference between HashMap and Hashtable?

Answer:

  • HashMap: Not synchronized, allows one null key and multiple null values
  • Hashtable: Synchronized, does not allow null keys or values

23. What is the difference between ArrayList and LinkedList?

Answer:

  • ArrayList: Faster for read operations
  • LinkedList: Faster for insert and delete operations

24. What is Autoboxing and Unboxing?

Answer:

Autoboxing converts primitives to wrapper objects automatically, while unboxing converts wrapper objects back to primitives.

25. What is the Object class in Java?

Answer:

The Object class is the root class of all Java classes. All classes implicitly extend it.

26. What is the difference between checked and unchecked exceptions?

Answer:

  • Checked exceptions: Checked at compile time (e.g., IOException)
  • Unchecked exceptions: Occur at runtime (e.g., NullPointerException)

27. What is the purpose of the finally block?

Answer:

The finally block executes regardless of whether an exception occurs and is typically used for cleanup operations.

28. What is a package in Java?

Answer:

A package is a namespace that organizes related classes and interfaces and prevents naming conflicts.

29. What is immutability in Java?

Answer:

An immutable object cannot be modified after creation. String is a common immutable class in Java.

30. What is the difference between throw and throws?

Answer:

  • throw: Used to explicitly throw an exception
  • throws: Declares exceptions that a method may pass to the caller

31. What is method hiding in Java?

Answer:

Method hiding occurs when a subclass defines a static method with the same signature as a static method in its superclass. Static methods are resolved at compile time.

32. What is the difference between Comparable and Comparator?

Answer:

  • Comparable: Defines natural ordering using compareTo() in the same class
  • Comparator: Defines custom ordering using compare() in a separate class

33. What is a marker interface?

Answer:

A marker interface has no methods and is used to provide metadata to the JVM (e.g., Serializable, Cloneable).

34. What is the transient keyword?

Answer:

The transient keyword prevents a variable from being serialized during object serialization.

35. What is serialization?

Answer:

Serialization is the process of converting an object into a byte stream for storage or transmission.

36. What is deserialization?

Answer:

Deserialization is the process of converting a byte stream back into an object.

37. What is the difference between List, Set, and Map?

Answer:

  • List: Allows duplicates and maintains order
  • Set: Does not allow duplicates
  • Map: Stores key–value pairs with unique keys

38. What is a memory leak in Java?

Answer:

A memory leak occurs when objects are no longer needed but still referenced, preventing garbage collection.

39. What is the Java heap and stack memory?

Answer:

  • Heap: Stores objects and class instances
  • Stack: Stores method calls and local variables

40. What is the difference between wait() and sleep()?

Answer:

  • wait(): Releases the lock and waits for notification
  • sleep(): Does not release the lock and pauses execution for a fixed time

41. What is a Functional Interface?

Answer:

A Functional Interface is an interface that contains exactly one abstract method and is primarily used with lambda expressions (e.g., Runnable, Callable).

42. What are Lambda Expressions?

Answer:

Lambda expressions provide a concise way to represent anonymous functions and enable functional programming in Java.

43. What is the Stream API?

Answer:

The Stream API allows processing collections in a declarative manner using operations like filter, map, and reduce.

44. What is the Optional class?

Answer:

Optional is a container object used to avoid NullPointerException by explicitly handling the presence or absence of values.

45. What is the difference between map() and flatMap()?

Answer:

  • map(): Transforms each element into one result
  • flatMap(): Flattens nested structures into a single stream

46. What is method reference?

Answer:

A method reference is a shorthand notation of a lambda expression that calls an existing method using ::.

47. What is the volatile keyword?

Answer:

The volatile keyword ensures visibility of changes to variables across threads by preventing caching inconsistencies.

48. What is the difference between synchronized and Lock?

Answer:

  • synchronized: Implicit locking, simpler syntax
  • Lock: Explicit locking with advanced features like try-lock and fairness

49. What is the Executor Framework?

Answer:

The Executor Framework simplifies thread management by providing a pool of threads for executing asynchronous tasks.

50. What is the Fork/Join Framework?

Answer:

The Fork/Join Framework supports parallel task execution by recursively splitting tasks and combining results.

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

Answer:

The Java Memory Model defines how threads interact through memory, specifying visibility, ordering, and atomicity of shared variables.

52. What is a Deadlock in Java?

Answer:

Deadlock occurs when two or more threads are blocked forever, each waiting for a resource held by another thread.

53. What is Thread Starvation?

Answer:

Thread Starvation happens when a thread does not get CPU time or resources due to low priority or poor scheduling.

54. What is a Race Condition?

Answer:

A race condition occurs when multiple threads access shared data simultaneously and the final result depends on execution order.

55. What is CopyOnWriteArrayList?

Answer:

CopyOnWriteArrayList is a thread-safe variant of ArrayList where modifications create a new copy of the underlying array.

56. What is ConcurrentHashMap?

Answer:

ConcurrentHashMap is a thread-safe map designed for high concurrency without locking the entire map.

57. What is the difference between HashSet and TreeSet?

Answer:

  • HashSet: No ordering, faster
  • TreeSet: Sorted order, slower due to tree structure

58. What is the default method in an interface?

Answer:

A default method is a method with implementation in an interface, introduced in Java 8, using the default keyword.

59. What is the Optional.orElse() vs orElseGet() difference?

Answer:

  • orElse(): Always evaluates the argument
  • orElseGet(): Evaluates lazily when value is absent

60. What is Reflection in Java?

Answer:

Reflection allows inspection and modification of classes, methods, and fields at runtime.

61. What is the try-with-resources statement?

Answer:

try-with-resources automatically closes resources like files or database connections that implement AutoCloseable, reducing memory leaks.

62. What is the difference between finalize() and close()?

Answer:

  • finalize(): Called by the garbage collector (deprecated, unreliable)
  • close(): Explicitly called to release resources (recommended)

63. What is the purpose of the assert keyword?

Answer:

assert is used to perform runtime checks during development to validate assumptions and detect logical errors.

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

Answer:

  • Shallow copy: Copies object references
  • Deep copy: Copies actual object data, creating independent objects

65. What is the Cloneable interface?

Answer:

Cloneable is a marker interface that indicates an object can be cloned using the clone() method.

66. What is the difference between String.intern() and normal String objects?

Answer:

intern() stores strings in the String Constant Pool to optimize memory and enable reference reuse.

67. What is the purpose of the enum in Java?

Answer:

enum defines a fixed set of constants and provides type safety compared to traditional constant definitions.

68. What is the difference between break and continue?

Answer:

  • break: Exits the loop completely
  • continue: Skips the current iteration and continues with the next

69. What is the Strictfp keyword?

Answer:

strictfp ensures consistent floating-point calculations across different platforms.

70. What is the difference between ClassNotFoundException and NoClassDefFoundError?

Answer:

  • ClassNotFoundException: Occurs at runtime when a class is not found dynamically
  • NoClassDefFoundError: Occurs when the class was present at compile time but missing at runtime

71. What is the Comparable contract and why is it important?

Answer:

The Comparable contract defines consistency rules for compareTo() (antisymmetry, transitivity, consistency). It is important to ensure correct sorting behavior in collections like TreeSet and Collections.sort().

72. What is fail-fast vs fail-safe behavior in Java collections?

Answer:

  • Fail-fast: Throws ConcurrentModificationException if collection is modified during iteration (e.g., ArrayList).
  • Fail-safe: Works on a cloned copy and does not throw exceptions (e.g., CopyOnWriteArrayList).

73. What is the difference between Iterator and ListIterator?

Answer:

  • Iterator: Forward traversal only, works with all collections.
  • ListIterator: Bidirectional traversal, allows add/modify elements, works only with List.

74. What is the purpose of the equals() and hashCode() contract?

Answer:

If two objects are equal according to equals(), they must return the same hashCode(). This contract is essential for correct behavior in hash-based collections.

75. What is a WeakHashMap?

Answer:

WeakHashMap stores keys as weak references, allowing entries to be garbage-collected when keys are no longer referenced.

76. What is the difference between Arrays.asList() and List.of()?

Answer:

  • Arrays.asList(): Fixed-size list backed by array
  • List.of(): Immutable list (Java 9+)

77. What is the purpose of the Spliterator?

Answer:

Spliterator is used to traverse and partition elements for efficient parallel processing in streams.

78. What is the difference between Callable and Runnable?

Answer:

  • Runnable: Does not return a result, cannot throw checked exceptions
  • Callable: Returns a result and can throw checked exceptions

79. What is the CompletableFuture?

Answer:

CompletableFuture supports asynchronous programming with non-blocking callbacks and chaining of dependent tasks.

80. What is the difference between System.gc() and garbage collection?

Answer:

System.gc() only requests garbage collection; actual execution is controlled by the JVM and not guaranteed.

81. What is the Java ClassLoader hierarchy?

Answer:

Java uses a hierarchical class loading mechanism: Bootstrap → Extension (Platform) → Application ClassLoader, ensuring core classes are loaded first and preventing malicious overrides.

82. What is the Java Module System (JPMS)?

Answer:

JPMS (introduced in Java 9) organizes code into modules with explicit dependencies, improving encapsulation, security, and startup performance.

83. What are Java Records?

Answer:

Records are immutable data carriers (Java 16+) that automatically generate constructors, getters, equals(), hashCode(), and toString().

84. What are Sealed Classes?

Answer:

Sealed classes restrict which classes can extend or implement them, improving design control and safety (Java 17+).

85. What is Pattern Matching for instanceof?

Answer:

Pattern matching simplifies type checks by combining instanceof and casting into a single, readable expression.

86. What is the var keyword in Java?

Answer:

var enables local variable type inference (Java 10+), allowing the compiler to infer the variable type at compile time.

87. What are Text Blocks in Java?

Answer:

Text Blocks (""") allow multi-line string literals, improving readability for JSON, XML, and SQL (Java 15+).

88. What is the difference between File and Path (NIO)?

Answer:

  • File: Legacy API with limited features
  • Path (NIO): Modern, flexible API supporting symbolic links, better exception handling, and scalability

89. What is JIT compilation in Java?

Answer:

Just-In-Time (JIT) compilation converts frequently executed bytecode into native machine code at runtime for better performance.

90. What are Java Annotations?

Answer:

Annotations provide metadata about code (e.g., @Override, @Deprecated) and are used by the compiler, runtime, or frameworks for behavior control.

91. What is the Java Security Manager and its current status?

Answer:

The Security Manager enforced runtime security policies (permissions). It is deprecated for removal in recent Java versions as modern security relies on OS/container isolation and JVM hardening.

92. What are JVM memory pools?

Answer:

JVM memory is divided into pools such as Eden, Survivor, Old Generation, Metaspace, and Code Cache, each serving different allocation and lifecycle purposes.

93. What is class unloading in Java?

Answer:

Class unloading removes classes from memory when their defining ClassLoader becomes unreachable, helping free Metaspace and reduce memory usage.

94. What is JNI (Java Native Interface)?

Answer:

JNI allows Java code to interact with native code written in C/C++, typically for performance optimization or accessing OS-level features.

95. What is SPI (Service Provider Interface)?

Answer:

SPI enables pluggable implementations discovered at runtime (via META-INF/services), commonly used in drivers and extensible frameworks.

96. What is NIO Selector?

Answer:

A Selector allows a single thread to manage multiple non-blocking I/O channels, improving scalability for high-concurrency network applications.

97. What is Java Profiling?

Answer:

Profiling analyzes application performance (CPU, memory, threads) using tools like JVisualVM or JFR to identify bottlenecks and leaks.

98. What is JVM warm-up?

Answer:

JVM warm-up is the period where JIT optimizes hot code paths; performance improves after initial executions as bytecode becomes native code.

99. What is garbage collector tuning?

Answer:

GC tuning adjusts JVM options (heap size, GC algorithm, pause targets) to balance throughput and latency based on application needs.

100. What is Java Logging API?

Answer:

The Java Logging API (java.util.logging) provides configurable logging levels, handlers, and formatters for application diagnostics.

101. What is Project Loom in Java?

Answer:

Project Loom introduces virtual threads (lightweight threads) to simplify concurrent programming and improve scalability without the complexity of thread pools.

102. What are Virtual Threads?

Answer:

Virtual Threads are JVM-managed threads that are much lighter than platform threads, allowing millions of concurrent tasks with minimal resource usage.

103. What is Structured Concurrency?

Answer:

Structured Concurrency treats multiple concurrent tasks as a single unit of work, improving readability, error handling, and lifecycle management.

104. What is the ScopedValue API?

Answer:

ScopedValue provides a safe and efficient way to share immutable data across threads within a defined execution scope.

105. What is Java Flight Recorder (JFR)?

Answer:

Java Flight Recorder is a low-overhead profiling and diagnostics tool used to collect runtime performance data in production systems.

106. What is GraalVM?

Answer:

GraalVM is a high-performance runtime that supports ahead-of-time (AOT) compilation, polyglot programming, and faster startup times.

107. What is Native Image in Java?

Answer:

Native Image compiles Java applications into platform-specific executables using GraalVM, reducing startup time and memory footprint.

108. What is the Z Garbage Collector (ZGC)?

Answer:

ZGC is a low-latency garbage collector designed to handle large heaps with pause times typically under 10 milliseconds.

109. What is Shenandoah GC?

Answer:

Shenandoah is a concurrent garbage collector that minimizes pause times by performing most GC work concurrently with application threads.

110. What is the Vector API?

Answer:

The Vector API enables SIMD (Single Instruction, Multiple Data) operations for high-performance numerical and data-processing workloads.

111. What is the Foreign Function & Memory API?

Answer:

It provides a safe, efficient way for Java to interoperate with native code and memory without using JNI, improving performance and safety.

112. What is the Structured Task Scope?

Answer:

Structured Task Scope groups related concurrent tasks and manages their lifecycle together, simplifying cancellation, error handling, and completion logic.

113. What is the HttpClient API in Java?

Answer:

The HttpClient API (Java 11+) supports synchronous and asynchronous HTTP calls with HTTP/2 and WebSocket support.

114. What is Java Ahead-of-Time (AOT) compilation?

Answer:

AOT compilation converts Java bytecode into native binaries before runtime to reduce startup time and memory usage.

115. What is JVM ergonomics?

Answer:

JVM ergonomics automatically selects GC algorithms, heap sizes, and runtime settings based on system resources and workload.

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

Answer:

  • SoftReference: Cleared under memory pressure
  • WeakReference: Cleared eagerly by GC
  • PhantomReference: Used for post-GC cleanup tracking

117. What is Java Desugaring?

Answer:

Desugaring rewrites newer Java language features into compatible bytecode for older JVMs, commonly used in Android builds.

118. What is the Role of the Code Cache?

Answer:

The Code Cache stores JIT-compiled native code to speed up execution of frequently used methods.

119. What is Java CDS (Class Data Sharing)?

Answer:

Class Data Sharing allows sharing preloaded class metadata across JVM instances to reduce startup time and memory usage.

120. What is JVM Safepoint?

Answer:

A safepoint is a JVM state where all threads pause so GC or other JVM operations can safely execute.

121. What is a Switch Expression in Java?

Answer:

Switch Expressions (Java 14+) allow switch to return a value using -> syntax or yield, making code more concise and less error-prone than traditional switch statements.

122. What is Pattern Matching for switch?

Answer:

Pattern Matching for switch extends switch expressions to perform type checks and binding in a single construct, improving readability and reducing casting.

123. What are Preview Features in Java?

Answer:

Preview Features are new language or JVM features introduced for early feedback. They must be explicitly enabled and may change or be removed in later releases.

124. What is Escape Analysis?

Answer:

Escape Analysis is a JIT optimization that determines if an object escapes a method or thread, enabling stack allocation and lock elimination for better performance.

125. What is Tiered Compilation?

Answer:

Tiered Compilation combines client (C1) and server (C2) JIT compilers to balance fast startup with long-term optimized performance.

126. What is Biased Locking?

Answer:

Biased Locking is a JVM optimization that reduces synchronization overhead by biasing a lock toward the first thread that acquires it.

127. What are Compact Strings?

Answer:

Compact Strings store String data in either Latin-1 or UTF-16 internally, reducing memory usage when characters fit in a single byte.

128. What is String Deduplication?

Answer:

String Deduplication (with G1 GC) identifies duplicate String objects and makes them share the same underlying character array to save memory.

129. What is a VarHandle?

Answer:

VarHandle provides low-level, fine-grained control over variable access (similar to Unsafe) with defined memory ordering semantics.

130. What is the MethodHandles API?

Answer:

MethodHandles provide strongly typed, fast, and flexible method invocation used internally by the JVM and in dynamic language implementations.

131. What is a Memory Barrier in Java?

Answer:

A memory barrier (fence) is a mechanism that enforces ordering and visibility of memory operations between threads, ensuring correctness in concurrent programs.

132. What is Lock Elimination?

Answer:

Lock Elimination is a JIT optimization that removes unnecessary synchronization when it detects that a lock is not shared across threads.

133. What is Lock Coarsening?

Answer:

Lock Coarsening combines multiple adjacent synchronized blocks into a single lock to reduce locking overhead and improve performance.

134. What is the difference between ThreadLocal and shared variables?

Answer:

  • ThreadLocal: Each thread has its own independent copy
  • Shared variables: Same instance accessed by multiple threads, requiring synchronization

135. What is a Daemon Thread?

Answer:

A daemon thread is a background thread that does not prevent JVM shutdown (e.g., garbage collector).

136. What is the difference between start() and run() in Thread?

Answer:

  • start(): Creates a new thread and executes run() asynchronously
  • run(): Executes like a normal method on the current thread

137. What is the purpose of Thread.join()?

Answer:

join() makes the current thread wait until another thread completes its execution.

138. What is a ReentrantLock?

Answer:

ReentrantLock allows the same thread to acquire the same lock multiple times and provides advanced features like fairness and try-lock.

139. What is the difference between notify() and notifyAll()?

Answer:

  • notify(): Wakes one waiting thread
  • notifyAll(): Wakes all waiting threads

140. What is a Thread Pool?

Answer:

A Thread Pool reuses a fixed number of threads to execute multiple tasks efficiently, reducing thread creation overhead.

141. What is the difference between Future and CompletableFuture?

Answer:

  • Future: Blocking, limited composition
  • CompletableFuture: Non-blocking, supports chaining, callbacks, and combination of async tasks

142. What is a BlockingQueue?

Answer:

A BlockingQueue supports thread-safe producer–consumer patterns by blocking on put() when full and take() when empty.

143. What is the difference between ArrayBlockingQueue and LinkedBlockingQueue?

Answer:

  • ArrayBlockingQueue: Fixed size, array-backed
  • LinkedBlockingQueue: Optionally bounded, linked-node based

144. What is the ForkJoinPool work-stealing algorithm?

Answer:

Idle threads steal tasks from busy threads’ queues to balance load and improve parallel execution efficiency.

145. What is the purpose of Phaser?

Answer:

Phaser is a flexible synchronization barrier that supports dynamic registration of parties and multiple phases.

146. What is the difference between CountDownLatch and CyclicBarrier?

Answer:

  • CountDownLatch: One-time use; threads wait until count reaches zero
  • CyclicBarrier: Reusable barrier; threads wait for each other at a point

147. What is StampedLock?

Answer:

StampedLock provides read/write/optimistic locking with better throughput for read-heavy workloads.

148. What is the purpose of LongAdder?

Answer:

LongAdder reduces contention under high concurrency by maintaining striped counters and summing them when needed.

149. What is the difference between AtomicInteger and LongAdder?

Answer:

  • AtomicInteger: Single atomic variable, higher contention
  • LongAdder: Better scalability under contention

150. What is the Unsafe class and why is it discouraged?

Answer:

Unsafe provides low-level operations (memory access, CAS) but is discouraged due to safety risks and lack of portability; prefer standard APIs.