Best Top 10 Lists

Best top 10 list of all time

280 Core Java interview questions and answers for freshers and experienced

  BestTop      

Most of core Java interview questions and answers


280+ Core Java interview questions and answers that cover key concepts often asked during Java interviews.

Core Java interview questions and answers for freshers and experienced


1. What is Java?

Answer: 

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle) in 1995. It is platform-independent thanks to the Java Virtual Machine (JVM), which allows Java programs to run on different hardware and operating systems.

2. What are the main features of Java?

Answer: 

Key features include:

Object-Oriented

Platform Independent (via JVM)

Simple and Familiar Syntax

Robust (memory management, exception handling)

Secure (e.g., no pointers)

Multithreaded

Portable

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

Answer:

JDK (Java Development Kit): A software development kit to develop Java applications.

JRE (Java Runtime Environment): Provides libraries and JVM to run Java applications.

JVM (Java Virtual Machine): Abstract machine that enables Java applications to run on different platforms.

4. What is the difference between a JIT compiler and a JVM interpreter?

Answer:

JVM interpreter executes bytecode line by line, while the JIT (Just-In-Time) compiler converts bytecode into native machine code, reducing the execution time.

5. What is the main method in Java?

Answer: 

The main method is the entry point of any Java application:

public static void main(String[] args)

public: accessible to JVM

static: does not require an object to invoke

void: does not return any value

String[] args: accepts command-line arguments

6. What is an object in Java?

Answer: 

An object is an instance of a class. It contains state (fields) and behavior (methods).

7. What is a class in Java?

Answer: 

A class is a blueprint or template that defines the structure and behavior (methods and variables) of objects.

8. What is the difference between constructor and method in Java?

Answer: 

A constructor is used to initialize objects, while a method is used to define the behavior of an object. Constructors do not have a return type and are called when an object is instantiated.

9. What are the types of constructors in Java?

Answer: 

Two types:

Default constructor: No parameters.

Parameterized constructor: Takes arguments to initialize the object.

10. What is the default constructor?

Answer: 

A default constructor is automatically created by the compiler if no other constructors are defined. It initializes object fields with default values.

11. What are access modifiers in Java?

Answer: 

Access modifiers define the visibility of classes, methods, and variables:

private: Accessible only within the class.

default (no modifier): Accessible within the package.

protected: Accessible within the package and subclasses.

public: Accessible from anywhere.

12. What is the ‘this’ keyword in Java?

Answer: 

this refers to the current instance of the class.

13. What is the ‘super’ keyword in Java?

Answer: 

super refers to the parent class object. It is used to access parent class methods, fields, and constructors.

14. What is inheritance in Java?

Answer: 

Inheritance allows a class to inherit properties and behavior from another class. It promotes code reuse.

15. What are the types of inheritance in Java?

Answer:

Single inheritance

Multilevel inheritance

Hierarchical inheritance

Java does not support multiple inheritance to avoid ambiguity.

16. What is method overloading?

Answer: 

Method overloading allows a class to have multiple methods with the same name but different parameters (different type, number, or both).

17. What is method overriding?

Answer: 

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its parent class.

18. What is the difference between method overloading and method overriding?

Answer:

Overloading: Same method name, different parameters within the same class.

Overriding: Same method signature, redefined in subclass.

19. What is polymorphism in Java?

Answer: 

Polymorphism allows objects to be treated as instances of their parent class. It can be achieved through method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).

20. What is an abstract class in Java?

Answer: 

An abstract class cannot be instantiated and may contain abstract methods that need to be implemented by subclasses.

21. What is an interface in Java?

Answer: 

An interface is a reference type that contains only abstract methods (until Java 8), static methods, and default methods (Java 8+).

22. Can a class implement multiple interfaces?

Answer: 

Yes, a class can implement multiple interfaces, enabling a form of multiple inheritance in Java.

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

Answer:

Abstract class: Can have abstract and non-abstract methods, instance variables, and a constructor.

Interface: All methods are abstract by default (until Java 8); no instance variables allowed.

24. What is encapsulation?

Answer: 

Encapsulation is the wrapping of data (variables) and methods (code) together as a single unit, typically achieved using private fields and public getter/setter methods.

25. What is the ‘final’ keyword in Java?

Answer:

final class: Cannot be subclassed.

final method: Cannot be overridden.

final variable: Its value cannot be changed (constant).

26. What is the difference between ‘final’, ‘finally’, and ‘finalize’?

Answer:

final: Used to define constants, prevent inheritance, and prevent method overriding.

finally: A block in exception handling that gets executed regardless of whether an exception is handled.

finalize(): A method invoked before an object is garbage collected.

27. What is a static variable in Java?

Answer: 

A static variable is shared among all instances of a class and belongs to the class, not the individual objects.

28. What is a static method?

Answer: 

A static method belongs to the class rather than any instance. It can be called without creating an object of the class.

29. What is a static block in Java?

Answer: 

A static block is used for static initializations of a class and is executed once, when the class is first loaded.

30. What is garbage collection in Java?

Answer: 

Garbage collection is the process by which Java programs perform automatic memory management by reclaiming memory used by objects that are no longer referenced.

31. What is a package in Java?

Answer: 

A package is a namespace that organizes classes and interfaces, helping to avoid name conflicts and to control access. Examples include java.util, java.io.

32. What is the difference between import and import static?

Answer:

import: Imports classes or entire packages.

import static: Imports static members (fields or methods) of a class, allowing them to be used without class qualification.

33. What is the Java Collections Framework?

Answer: 

It is a set of classes and interfaces that implement commonly reusable collection data structures, such as lists, sets, queues, and maps. It provides algorithms to manipulate collections.

34. What is the difference between ArrayList and LinkedList?

Answer:

ArrayList: Uses a dynamic array; provides fast random access but slow insertions/removals in the middle.

LinkedList: Uses a doubly-linked list; provides faster insertions/removals but slower random access.

35. What is a HashMap in Java?

Answer: 

HashMap is a part of the Java Collections Framework that stores key-value pairs. It allows null keys and values and does not maintain any order.

36. What is the difference between HashMap and Hashtable?

Answer:

HashMap: Not synchronized, allows null keys and values, generally faster.

Hashtable: Synchronized, does not allow null keys or values.

37. What is a Set in Java?

Answer: 

A Set is a collection that does not allow duplicate elements. Implementations include HashSet, LinkedHashSet, and TreeSet.

38. What is a TreeSet?

Answer: 

TreeSet is a Set implementation that stores elements in a sorted (natural order or via a comparator) and navigable manner.

39. What is a Queue in Java?

Answer: 

A Queue is a collection designed for holding elements prior to processing, typically following FIFO (First-In-First-Out) order. Implementations include LinkedList, PriorityQueue.

40. What is a PriorityQueue?

Answer:

PriorityQueue is a queue where elements are ordered based on their natural ordering or a specified comparator, not strictly FIFO.

41. What are iterators in Java?

Answer: 

Iterators provide a way to traverse collections. They allow elements to be accessed sequentially without exposing the underlying structure.

42. What is the difference between Iterator and ListIterator?

Answer:

Iterator: Can traverse forward and remove elements.

ListIterator: Extends Iterator to allow bidirectional traversal and element modification.

43. What is autoboxing and unboxing in Java?

Answer:

Autoboxing: Automatic conversion of primitive types to their corresponding wrapper classes (e.g., int to Integer).

Unboxing: Automatic conversion of wrapper classes back to primitive types.

44. What are wrapper classes in Java?

Answer: 

Wrapper classes provide object representations for primitive data types. Examples include Integer, Double, Boolean, etc.

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

Answer:

==: Checks for reference equality (whether two references point to the same object).

equals(): Checks for value equality (whether two objects are logically equal).

46. What is the StringBuilder class?

Answer: 

StringBuilder is a mutable sequence of characters, designed for efficient string manipulation without creating multiple immutable String objects.

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

Answer:

String: Immutable; concatenation creates new objects.

StringBuilder: Mutable and not synchronized; faster for single-threaded scenarios.

StringBuffer: Mutable and synchronized; thread-safe but slower.

48. What is serialization in Java?

Answer: 

Serialization is the process of converting an object into a byte stream to save it to a file or send it over a network. Deserialization is the reverse process.

49. How do you make a class serializable?

Answer: 

Implement the java.io.Serializable interface. It's a marker interface with no methods.

50. What is the transient keyword?

Answer: 

The transient keyword indicates that a field should not be serialized.

51. What is exception handling in Java?

Answer: 

Exception handling is a mechanism to handle runtime errors, maintaining the normal flow of the application. It uses try, catch, finally, throw, and throws.

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

Answer:

Checked exceptions: Must be either caught or declared in the method signature (e.g., IOException).

Unchecked exceptions: Inherit from RuntimeException and do not need to be explicitly handled (e.g., NullPointerException).

53. What is the finally block?

Answer: 

A finally block contains code that is always executed after a try block, regardless of whether an exception was thrown or caught. It's typically used for resource cleanup.

54. What is the throw keyword?

Answer: 

throw is used to explicitly throw an exception from a method or block of code.

55. What is the throws keyword?

Answer: 

throws is used in a method signature to declare that the method may throw certain exceptions, allowing callers to handle them.

56. What is a custom exception?

Answer: 

A user-defined exception class that extends Exception or RuntimeException, allowing developers to create meaningful exception types specific to their applications.

57. What is multithreading in Java?

Answer: 

Multithreading allows concurrent execution of two or more threads for maximum utilization of CPU. It enables multiple tasks to run simultaneously within a program.

58. How do you create a thread in Java?

Answer:

By extending the Thread class:
class MyThread extends Thread {
    public void run() {
        // Code to execute
    }
}
By implementing the Runnable interface:
able implements Runnable {
    public void run() {
        // Code to execute
    }
}

59. What is the difference between start() and run() methods in threads?

Answer:

start(): Creates a new thread and invokes the run() method.

run(): Executes the code in the current thread without creating a new one.

60. What is synchronization in Java?

Answer: 

Synchronization controls access to shared resources by multiple threads to prevent data inconsistency. It can be achieved using the synchronized keyword.

61. What is a deadlock?

Answer: 

A deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a resource.

62. What are thread priorities?

Answer: 

Thread priorities determine the order in which threads are scheduled for execution. Higher priority threads are generally executed before lower priority ones.

63. What is the volatile keyword?

Answer: 

The volatile keyword ensures that a variable's value is always read from main memory, providing visibility guarantees across threads.

64. What is the Callable interface?

Answer: 

Callable is similar to Runnable but can return a result and throw checked exceptions. It uses the call() method.

Callable<Integer> callable = () -> {

    // computation

    return 123;

};

65. What is the Future interface?

Answer:

Future represents the result of an asynchronous computation. It provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result.

66. What is the Executor framework?

Answer: 

The Executor framework provides a high-level API for managing and controlling thread execution, simplifying concurrent programming by decoupling task submission from thread management.

67. What is a daemon thread?

Answer: 

A daemon thread is a background thread that does not prevent the JVM from exiting when all user threads finish execution. Examples include garbage collection threads.

68. What are thread-safe classes?

Answer: 

Thread-safe classes are designed to be safely used by multiple threads simultaneously without causing data inconsistency or corruption. Examples include Vector, Hashtable, and classes in java.util.concurrent package.

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

Answer:

synchronized method: Locks the entire method, restricting access to one thread at a time.

synchronized block: Locks only a specific block of code, allowing finer-grained synchronization and potentially better performance.

70. What is the java.util.concurrent package?

Answer:

It provides a framework for building concurrent applications, including thread pools, concurrent collections, synchronization utilities, and higher-level abstractions like Future, Callable, and ExecutorService.

71. What is the difference between Executor and ExecutorService?

Answer:

Executor: A simple interface for executing Runnable tasks.

ExecutorService: Extends Executor with additional lifecycle management methods, such as shutting down and submitting tasks that return results.

72. What is the Fork/Join framework?

Answer: 

Introduced in Java 7, the Fork/Join framework facilitates parallel processing by recursively breaking tasks into smaller subtasks, executing them in parallel, and combining their results.

73. What are lambda expressions in Java?

Answer: 

Introduced in Java 8, lambda expressions provide a clear and concise way to represent anonymous functions, enabling functional programming styles. Syntax:

(parameters) -> expression

74. What are functional interfaces?

Answer: 

A functional interface is an interface with exactly one abstract method, making it eligible for lambda expressions and method references. Examples include Runnable, Callable, Predicate<T>, Function<T, R>.

75. What is the Stream API?

Answer: 

Introduced in Java 8, the Stream API provides a functional approach to processing sequences of elements, supporting operations like filter, map, reduce, and collect, enabling efficient data manipulation.

76. What is the difference between map and flatMap in streams?

Answer:

map: Applies a function to each element, transforming them individually.

flatMap: Applies a function that returns a stream for each element and then flattens these into a single stream.

77. What is method reference in Java?

Answer: 

Method references provide a shorthand syntax for lambda expressions that invoke existing methods. Syntax includes Class::staticMethod, object::instanceMethod, Class::instanceMethod, Class::new.

78. What are default methods in interfaces?

Answer: 

Introduced in Java 8, default methods allow interfaces to have method implementations, enabling new methods to be added to interfaces without breaking existing implementations.

79. What is the Optional class?

Answer: 

Introduced in Java 8, Optional is a container object used to represent the presence or absence of a value, helping to avoid NullPointerException.

80. What is the difference between Stream and Collection?

Answer:

Collection: Represents a data structure that holds elements.

Stream: Represents a sequence of elements supporting sequential and parallel aggregate operations, without storing data.

81. What is the Collectors class?

Answer: 

The Collectors class provides various reduction operations, such as accumulating elements into collections, summarizing data, grouping, and partitioning.

82. What is the parallelStream() method?

Answer: 

It creates a parallel stream that can leverage multiple cores for concurrent processing, potentially improving performance for large data sets.

83. What is the reduce operation in streams?

Answer: 

The reduce operation combines elements of a stream into a single result by repeatedly applying a binary operator.

84. What is the difference between forEach and map in streams?

Answer:

forEach: Performs an action for each element, primarily used for side-effects.

map: Transforms each element into another form, producing a new stream.

85. What is the collect operation in streams?

Answer: 

The collect operation transforms the elements of a stream into a different form, such as a collection, using a Collector.

86. What is the distinct method in streams?

Answer: 

The distinct method returns a stream with duplicate elements removed, based on equals().

87. What is the peek method in streams?

Answer: 

The peek method allows performing an action on each element as it passes through the stream, primarily used for debugging.

88. What is short-circuiting in streams?

Answer: 

Short-circuiting operations can terminate the processing of a stream before all elements are processed, such as limit, findFirst, anyMatch.

89. What is the Comparator interface?

Answer: 

Comparator is a functional interface used to define custom ordering for objects, typically used in sorting.

90. What is the difference between Comparable and Comparator?

Answer:

Comparable: Defines natural ordering by implementing the compareTo method within the class.

Comparator: Defines custom ordering by implementing the compare method externally.

91. What is a try-with-resources statement?

Answer: 

Introduced in Java 7, it ensures that resources are automatically closed at the end of the statement, simplifying resource management.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {

    // Use br

} catch (IOException e) {

    // Handle exception

}

92. What is the java.nio package?

Answer: 

java.nio (New I/O) provides non-blocking I/O operations, buffers, channels, and selectors for scalable I/O operations, introduced in Java 1.4 and enhanced in later versions.

93. What is the difference between File and Path in Java?

Answer:

File: Represents file and directory pathnames; part of java.io package.

Path: Part of java.nio.file package; provides more comprehensive functionality and better performance.

94. What is the java.time package?

Answer:

Introduced in Java 8, java.time provides a comprehensive API for date and time manipulation, addressing many shortcomings of the old java.util.Date and java.util.Calendar classes.

95. What is the difference between LocalDate, LocalTime, and LocalDateTime?

Answer:

LocalDate: Represents a date without time.

LocalTime: Represents a time without date.

LocalDateTime: Represents both date and time without time zone.

96. What is the DateTimeFormatter class?

Answer: 

It is used to format and parse date-time objects in the java.time package, allowing for custom date and time patterns.

97. What is the Instant class?

Answer: 

Instant represents a point in time (timestamp) in UTC, suitable for machine-based timestamps.

98. What is the ZoneId class?

Answer: 

ZoneId represents a time zone identifier, such as Europe/Paris, used to handle date-time objects in different time zones.

99. What is the Duration class?

Answer: 

Duration measures time-based amounts, such as seconds or nanoseconds, between two Instant objects.

100. What is the Period class?

Answer: 

Period measures date-based amounts, such as years, months, and days, between two dates.

101. What is the Spliterator interface?

Answer:

Introduced in Java 8, Spliterator is used for traversing and partitioning elements of a source, supporting parallel processing.

102. What is the Collectors.toMap() method?

Answer: 

It collects elements of a stream into a Map using provided key and value mapping functions.

103. What is the Supplier interface?

Answer: 

A functional interface that supplies a result without taking any input, defined as Supplier<T> with the method T get().

104. What is the Consumer interface?

Answer: 

A functional interface that accepts a single input and performs an operation without returning a result, defined as Consumer<T> with the method void accept(T t).

105. What is the Predicate interface?

Answer: 

A functional interface that represents a boolean-valued function of one argument, defined as Predicate<T> with the method boolean test(T t).

106. What is the Function interface?

Answer: 

A functional interface that represents a function accepting one argument and producing a result, defined as Function<T, R> with the method R apply(T t).

107. What is the BiFunction interface?

Answer: 

A functional interface that represents a function accepting two arguments and producing a result, defined as BiFunction<T, U, R> with the method R apply(T t, U u).

108. What is the Stream.iterate() method?

Answer: 

It generates an infinite sequential ordered stream by iteratively applying a function to a seed element.

109. What is the Stream.generate() method?

Answer: 

It generates an infinite sequential unordered stream where each element is generated by a provided Supplier.

110. What is the difference between findFirst and findAny in streams?

Answer:

findFirst: Returns the first element in the stream.

findAny: Returns any element, which can be useful in parallel streams for better performance.

111. What is the peek method used for in streams?

Answer: 

peek is mainly used for debugging purposes, allowing you to perform actions on each element as it passes through the stream without modifying the elements.

112. What is the flatMapToInt method?

Answer: 

It transforms each element of a stream into an IntStream, then flattens all the IntStream instances into a single IntStream.

113. What is the difference between map and mapToInt?

Answer:

map: Transforms each element to another object.

mapToInt: Transforms each element to an int, producing an IntStream for primitive operations.

114. What is the collect method used for?

Answer: 

It performs a mutable reduction operation on the elements of a stream, accumulating them into a summary result like a collection, string, or other data structures.

115. What is a terminal operation in streams?

Answer: 

A terminal operation triggers the processing of the stream and produces a non-stream result, such as collect, forEach, reduce, count.

116. What is an intermediate operation in streams?

Answer: 

Intermediate operations transform a stream into another stream and are lazy, meaning they are not executed until a terminal operation is invoked. Examples include filter, map, sorted.

117. What is the Comparator.comparing method?

Answer: 

It creates a Comparator based on a key extractor function, useful for sorting objects based on a specific attribute.

Comparator<Person> byName = Comparator.comparing(Person::getName);

118. What is the Comparator.thenComparing method?

Answer: 

It combines two comparators, allowing for secondary sorting criteria when the primary comparator results in equality.

Comparator<Person> byNameThenAge = Comparator.comparing(Person::getName)

                                             .thenComparing(Person::getAge);

119. What is the Stream.Builder?

Answer: 

It is a mutable builder for constructing a stream, allowing you to add elements one by one before building the stream.

120. What is the difference between anyMatch, allMatch, and noneMatch?

Answer:

anyMatch: Returns true if any elements match the predicate.

allMatch: Returns true if all elements match the predicate.

noneMatch: Returns true if no elements match the predicate.

121. What is the Stream.peek() method used for?

Answer: 

As mentioned earlier, peek is used for performing intermediate actions on each element of the stream, typically for debugging.

122. What is the Collectors.joining() method?

Answer: 

It concatenates the input elements into a single String, optionally with a delimiter, prefix, and suffix.

String result = stream.collect(Collectors.joining(", ", "[", "]"));

123. What is the Collectors.groupingBy() method?

Answer: 

It groups the stream elements based on a classification function, resulting in a Map where keys are the classification and values are lists of elements.

Map<String, List<Person>> grouped = stream.collect(Collectors.groupingBy(Person::getCity));

124. What is the Collectors.partitioningBy() method?

Answer: 

It partitions the stream elements into two groups based on a predicate, resulting in a Map<Boolean, List<T>>.

Map<Boolean, List<Person>> partitioned = stream.collect(Collectors.partitioningBy(p -> p.getAge() > 18));

125. What is the Collectors.toSet() method?

Answer: 

It collects the stream elements into a Set, eliminating duplicates.

Set<String> set = stream.collect(Collectors.toSet());

126. What is the Collectors.toList() method?

Answer: 

It collects the stream elements into a List.

List<String> list = stream.collect(Collectors.toList());

127. What is the Collectors.summingInt() method?

Answer: 

It sums the int values extracted from the stream elements.

int total = stream.collect(Collectors.summingInt(Person::getAge));

128. What is the Collectors.averagingInt() method?

Answer: 

It calculates the average of int values extracted from the stream elements.

double average = stream.collect(Collectors.averagingInt(Person::getAge));

129. What is the Collectors.maxBy() method?

Answer: 

It finds the maximum element based on a provided Comparator.

Optional<Person> oldest = stream.collect(Collectors.maxBy(Comparator.comparing(Person::getAge)));

130. What is the Collectors.minBy() method?

Answer: 

It finds the minimum element based on a provided Comparator.

Optional<Person> youngest = stream.collect(Collectors.minBy(Comparator.comparing(Person::getAge)));

131. What is the Collectors.mapping() method?

Answer: 

It applies a mapping function to the stream elements before collecting them.

Map<String, List<String>> namesByCity = stream.collect(

    Collectors.groupingBy(Person::getCity, Collectors.mapping(Person::getName, Collectors.toList()))

);

132. What is the Collectors.flatMapping() method?

Answer: 

It applies a mapping function that returns a stream for each element and then flattens these streams into a single stream before collecting.

Map<String, Set<String>> hobbiesByCity = stream.collect(

    Collectors.groupingBy(Person::getCity, Collectors.flatMapping(p -> p.getHobbies().stream(), Collectors.toSet()))

);

133. What is the Collectors.reducing() method?

Answer: 

It performs a reduction on the elements using an associative accumulation function and an optional identity value.

int totalAge = stream.collect(Collectors.reducing(0, Person::getAge, Integer::sum));

134. What is the Collectors.collectingAndThen() method?

Answer: 

It performs a final transformation on the result of a collector.

List<String> result = stream.collect(

    Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)

);

135. What is the Collectors.toMap() method?

Answer: 

It collects stream elements into a Map using key and value mapping functions.

Map<String, Integer> nameAgeMap = stream.collect(Collectors.toMap(Person::getName, Person::getAge));

136. What is the CompletableFuture class?

Answer: 

CompletableFuture is a class in java.util.concurrent that represents a future result of an asynchronous computation, supporting callbacks and chaining.

137. What is the difference between Future and CompletableFuture?

Answer:

Future: Represents the result of an asynchronous computation but has limited functionality.

CompletableFuture: Extends Future with the ability to chain, compose, and handle asynchronous operations more flexibly.

138. What is the ExecutorCompletionService?

Answer: 

It is a class that combines an Executor with a BlockingQueue to manage asynchronous task execution and retrieve their results as they complete.

139. What is the CountDownLatch class?

Answer: 

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

140. What is the CyclicBarrier class?

Answer: 

A synchronization aid that allows a set of threads to wait for each other to reach a common barrier point, reusable after releasing waiting threads.

141. What is the Semaphore class?

Answer: 

A thread synchronization construct that controls access to a shared resource through permits, limiting the number of concurrent accesses.

142. What is the ReentrantLock class?

Answer: 

A flexible locking mechanism that allows explicit lock operations, supporting features like fairness, multiple condition variables, and the ability to interrupt thread waiting for a lock.

143. What is the ReadWriteLock interface?

Answer: 

It defines a lock mechanism that allows multiple readers to access a resource concurrently while allowing only one writer exclusive access.

144. What is the Phaser class?

Answer: 

A flexible synchronization barrier that can be dynamically adjusted, supporting phases of thread synchronization similar to CyclicBarrier and CountDownLatch.

145. What is the StampedLock class?

Answer: 

A lock mechanism that supports read and write locks with optimistic reads, allowing higher concurrency by reducing contention.

146. What is the LockSupport class?

Answer: 

Provides lower-level thread blocking and unblocking operations, serving as a foundation for higher-level synchronization utilities.

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

Answer:

notify(): Wakes up a single thread waiting on the object's monitor.

notifyAll(): Wakes up all threads waiting on the object's monitor.

148. What is the ThreadLocal class?

Answer: 

ThreadLocal provides thread-local variables, allowing each thread to have its own independent instance of a variable.

149. What is the WeakReference class?

Answer: 

A type of reference that does not prevent its referent from being garbage collected, useful for implementing caches and other memory-sensitive structures.

150. What is the SoftReference class?

Answer: 

A reference type that allows the referent to be garbage collected when the JVM needs memory, useful for caches that should be cleared under memory pressure.

151. What is the PhantomReference class?

Answer: 

A reference type used to determine exactly when an object has been removed from memory, primarily for scheduling post-finalization actions.

152. What is the java.util.concurrent.atomic package?

Answer: 

It provides classes that support lock-free, thread-safe programming on single variables, such as AtomicInteger, AtomicLong, AtomicReference.

153. What is the AtomicInteger class?

Answer: 

A class that provides atomic operations on int values, allowing thread-safe increment, decrement, and other operations without using synchronized blocks.

154. What is the ForkJoinPool class?

Answer: 

A specialized implementation of ExecutorService designed to efficiently execute ForkJoinTasks using a work-stealing algorithm, ideal for parallelizable tasks.

155. What is the WorkStealingPool?

Answer: 

A type of ForkJoinPool that automatically manages a pool of worker threads, stealing tasks from other threads to balance the workload.

156. What is the BlockingQueue interface?

Answer: 

A BlockingQueue is a queue that supports operations that wait for the queue to become non-empty when retrieving and wait for space to become available when storing.

157. What is the difference between BlockingQueue and Queue?

Answer:

BlockingQueue: Supports blocking operations, useful in producer-consumer scenarios.

Queue: General-purpose interface without blocking capabilities.

158. What is the ArrayBlockingQueue class?

Answer: 

A bounded, blocking queue backed by an array, enforcing a fixed capacity and FIFO ordering.

159. What is the LinkedBlockingQueue class?

Answer: 

An optionally bounded, blocking queue backed by linked nodes, supporting higher throughput and concurrency.

160. What is the PriorityBlockingQueue class?

Answer: 

An unbounded, blocking queue that orders elements based on their natural ordering or a provided comparator.

161. What is the SynchronousQueue class?

Answer: 

A blocking queue that does not have any internal capacity, where each insert operation must wait for a corresponding remove operation.

162. What is the DelayQueue class?

Answer: 

A blocking queue where elements can only be taken when their delay has expired, useful for scheduling tasks.

163. What is the Exchanger class?

Answer: 

A synchronization point where two threads can exchange objects, useful for data transfer between threads.

164. What is the Semaphore class used for?

Answer: 

To control access to a shared resource by multiple threads by maintaining a set of permits. Threads acquire permits before accessing the resource and release them after.

165. What is the CountDownLatch class used for?

Answer: 

To make one or more threads wait until a set of operations being performed in other threads completes, using a countdown mechanism.

166. What is the CyclicBarrier class used for?

Answer:

To allow a set of threads to wait for each other to reach a common barrier point, and then proceed together. It can be reused after the barrier is tripped.

167. What is the ReentrantReadWriteLock class?

Answer: 

An implementation of ReadWriteLock that allows multiple threads to read simultaneously while only one thread can write at a time, enhancing concurrency.

168. What is the StampedLock class used for?

Answer: 

It provides a capability-based lock with three modes for controlling read/write access, including an optimistic read mode for higher concurrency.

169. What is the ConcurrentHashMap class?

Answer: 

A thread-safe implementation of HashMap that allows concurrent read and write operations without locking the entire map, providing high throughput.

170. What is the CopyOnWriteArrayList class?

Answer: 

A thread-safe variant of ArrayList where all mutative operations (add, set, etc.) are implemented by making a fresh copy of the underlying array.

171. What is the CopyOnWriteArraySet class?

Answer: 

A thread-safe variant of Set that uses a CopyOnWriteArrayList internally, ensuring thread safety with copy-on-write semantics.

172. What is the BlockingDeque interface?

Answer: 

An extension of BlockingQueue that supports insertion and removal of elements from both ends, allowing double-ended queue operations.

173. What is the LinkedBlockingDeque class?

Answer:

 A blocking deque backed by linked nodes, supporting an optionally bounded capacity and allowing high concurrency.

174. What is the LinkedTransferQueue class?

Answer: 

A concurrent, unbounded TransferQueue that allows producers to wait for consumers to receive elements, supporting high-throughput message passing.

175. What is the DelayQueue class used for?

Answer: 

To hold elements that implement the Delayed interface, allowing elements to be taken from the queue only when their delay has expired, useful for scheduling tasks.

176. What is the ArrayBlockingQueue class used for?

Answer:

 To implement a bounded blocking queue backed by an array, enforcing a fixed capacity and FIFO ordering, suitable for producer-consumer scenarios.

177. What is the Phaser class used for?

Answer: 

To manage dynamic synchronization phases where threads can register and deregister dynamically, providing more flexibility than CyclicBarrier.

178. What is the CompletionService interface?

Answer: 

It combines the functionality of Executor and BlockingQueue to manage asynchronous task execution and retrieve their results as they complete.

179. What is the ThreadPoolExecutor class?

Answer: 

A flexible and customizable thread pool implementation that manages a pool of worker threads, handling task execution with configurable parameters like core pool size, maximum pool size, and keep-alive time.

180. What is the ScheduledThreadPoolExecutor class?

Answer: 

An executor service that can schedule commands to run after a given delay or to execute periodically, useful for scheduled tasks.

181. What is the ExecutorCompletionService class?

Answer: 

It combines an Executor with a BlockingQueue to manage asynchronous task execution and retrieve their results as they complete, maintaining the order of completion.

182. What is the Exchanger class used for?

Answer: 

To allow two threads to exchange objects at a synchronization point, facilitating data transfer between threads.

183. What is the ReentrantLock class used for?

Answer: 

To provide a flexible locking mechanism with features like fairness, multiple condition variables, and the ability to interrupt threads waiting for a lock.

184. What is the Semaphore class used for?

Answer: 

To control access to a shared resource by multiple threads by maintaining a set of permits, where threads acquire permits before accessing the resource and release them after.

185. What is the BlockingQueue interface used for?

Answer: 

To provide thread-safe queues that support blocking operations, useful in producer-consumer scenarios where producers wait if the queue is full and consumers wait if the queue is empty.

186. What is the CompletableFuture class used for?

Answer: 

To represent the result of an asynchronous computation, supporting callbacks, chaining, and composition of multiple asynchronous tasks.

187. What is the FutureTask class?

Answer: 

A concrete implementation of Future that can wrap a Callable or Runnable, allowing it to be executed by an Executor and providing methods to check status and retrieve results.

188. What is the ForkJoinTask class?

Answer: 

An abstract class that represents a task that can be executed by a ForkJoinPool, supporting recursive splitting (forking) and joining of subtasks for parallel execution.

189. What is the ForkJoinPool class used for?

Answer: 

To manage a pool of worker threads designed to efficiently execute ForkJoinTasks using a work-stealing algorithm, ideal for divide-and-conquer parallelism.

190. What is the WorkStealingPool class used for?

Answer: 

A type of ForkJoinPool that creates a pool of worker threads, automatically managing task stealing to balance the workload among threads for improved performance.

191. What is the PriorityBlockingQueue class used for?

Answer: 

To implement a thread-safe priority queue where elements are ordered based on their natural ordering or a provided comparator, supporting concurrent access.

192. What is the BlockingDeque interface used for?

Answer: 

To provide a double-ended blocking queue that allows insertion and removal of elements from both ends, supporting both FIFO and LIFO operations.

193. What is the Delayed interface?

Answer: 

An interface that represents an object whose execution is delayed, used in conjunction with DelayQueue to schedule tasks with a delay.

194. What is the CountedCompleter class?

Answer: 

A subclass of ForkJoinTask that allows defining tasks with a completion action, suitable for tasks that can be split into subtasks and need to perform actions upon completion.

195. What is the Parallel Streams concept?

Answer: 

Parallel streams allow stream operations to be executed concurrently on multiple threads, leveraging multicore processors for improved performance on large data sets.

196. What is the Stream.collect() method used for?

Answer: 

To perform a mutable reduction operation on the elements of a stream, accumulating them into a collection, summary, or other data structures.

197. What is the Stream.mapToDouble() method?

Answer: 

It transforms each element of a stream into a double value, producing a DoubleStream for primitive operations.

198. What is the Stream.flatMapToInt() method?

Answer: 

It transforms each element of a stream into an IntStream, then flattens these into a single IntStream, useful for processing nested collections.

199. What is the Stream.sorted() method used for?

Answer: 

To return a stream with elements sorted according to their natural order or a provided comparator.

200. What is the Stream.limit() method used for?

Answer: 

To truncate a stream to contain no more than a specified number of elements.

201. What is the Stream.skip() method used for?

Answer: 

To skip the first n elements of a stream and return the remaining elements.

202. What is the Stream.reduce() method used for?

Answer: 

To combine the elements of a stream into a single result by repeatedly applying a binary operator, such as summing numbers.

203. What is the Stream.forEachOrdered() method?

Answer: 

Similar to forEach, but guarantees that elements are processed in encounter order, maintaining the order of the stream.

204. What is the Stream.peek() method used for?

Answer: 

To perform an action on each element as it passes through the stream, typically for debugging purposes, without modifying the elements.

205. What is the Stream.anyMatch() method used for?

Answer: 

To check if any elements in the stream match a given predicate, returning true if at least one match is found.

206. What is the Stream.allMatch() method used for?

Answer: 

To check if all elements in the stream match a given predicate, returning true only if every element matches.

207. What is the Stream.noneMatch() method used for?

Answer: 

To check if no elements in the stream match a given predicate, returning true if there are no matches.

208. What is the Stream.findFirst() method used for?

Answer: 

To return an Optional describing the first element of the stream, or an empty Optional if the stream is empty.

209. What is the Stream.findAny() method used for?

Answer: 

To return an Optional describing any element of the stream, which may be useful in parallel streams for better performance.

210. What is the Optional.ifPresent() method?

Answer: 

It performs a given action if a value is present in the Optional, allowing for safe handling of potentially absent values.

211. What is the Optional.orElse() method?

Answer: 

It returns the value if present, otherwise returns a default value provided.

212. What is the Optional.orElseGet() method?

Answer: 

It returns the value if present, otherwise invokes a supplier function to provide a default value.

213. What is the Optional.orElseThrow() method?

Answer: 

It returns the value if present, otherwise throws an exception provided by a supplier function.

214. What is the Optional.map() method?

Answer: 

It applies a function to the value if present and returns a new Optional with the result.

215. What is the Optional.flatMap() method?

Answer: 

It applies a function that returns an Optional to the value if present and returns that Optional, avoiding nested Optional instances.

216. What is the Collectors.toUnmodifiableList() method?

Answer: 

Introduced in Java 10, it collects the stream elements into an unmodifiable List, preventing further modifications.

217. What is the Collectors.toUnmodifiableSet() method?

Answer: 

Introduced in Java 10, it collects the stream elements into an unmodifiable Set, preventing further modifications.

218. What is the Collectors.toUnmodifiableMap() method?

Answer: 

Introduced in Java 10, it collects the stream elements into an unmodifiable Map, preventing further modifications.

219. What is the var keyword in Java?

Answer: 

Introduced in Java 10, var allows for local variable type inference, letting the compiler determine the variable's type based on the initializer.

var list = new ArrayList<String>();

220. What is the var keyword's limitation?

Answer: 

var can only be used for local variables with an initializer, not for class fields, method parameters, or return types.

221. What is the record keyword in Java?

Answer: 

Introduced in Java 14 as a preview and standardized in Java 16, record is a special type of class that provides a concise syntax for immutable data carriers.

public record Person(String name, int age) {}

222. What are sealed classes in Java?

Answer: 

Introduced in Java 15 as a preview and standardized in Java 17, sealed classes restrict which other classes or interfaces can extend or implement them, enhancing control over inheritance.

public sealed class Shape permits Circle, Square {}

223. What is the instanceof pattern matching introduced in Java 16?

Answer: 

It allows more concise type checking and casting by combining the instanceof check with a variable declaration.

if (obj instanceof String s) {

    // Use s directly

}

224. What is the text block feature in Java?

Answer: 

Introduced in Java 15, text blocks provide a multi-line string literal syntax, improving readability and reducing the need for escape sequences.

String json = """

              {

                  "name": "John",

                  "age": 30

              }

              """;

225. What is the switch expression enhancement in Java 14?

Answer: 

It allows switch to be used as an expression that returns a value and supports enhanced case labels with the -> arrow syntax.

String result = switch (day) {

    case MONDAY, FRIDAY, SUNDAY -> "Sixth";

    default -> "Unknown";

};

226. What is the sealed interface in Java?

Answer: 

Similar to sealed classes, a sealed interface restricts which classes can implement it, providing tighter control over the inheritance hierarchy.

public sealed interface Vehicle permits Car, Truck {}

227. What are pattern matching for switch introduced in Java 17?

Answer: 

It allows switch statements to match patterns rather than just constant values, enabling more expressive and concise code.

switch (obj) {

    case String s -> System.out.println(s.toUpperCase());

    case Integer i -> System.out.println(i * 2);

    default -> System.out.println("Unknown type");

}

228. What is the @FunctionalInterface annotation?

Answer: 

It is used to indicate that an interface is intended to be a functional interface, containing exactly one abstract method, enabling the use of lambda expressions.

229. What is the @Override annotation used for?

Answer: 

It indicates that a method is intended to override a method in a superclass, helping to catch errors if the method does not actually override any method.

230. What is the @Deprecated annotation?

Answer: 

It marks a method, class, or field as deprecated, indicating that it should no longer be used and may be removed in future versions.

231. What is the @SuppressWarnings annotation?

Answer: 

It instructs the compiler to suppress specific warnings for the annotated element, such as unchecked operations or deprecation.

232. What is the @SafeVarargs annotation?

Answer: 

It suppresses warnings about potentially unsafe operations on varargs parameters, ensuring that the method does not perform unsafe operations on its varargs parameters.

233. What is the @Retention annotation?

Answer: 

It specifies how long annotations with the annotated type are to be retained, such as SOURCE, CLASS, or RUNTIME.

234. What is the @Target annotation?

Answer: 

It specifies the kinds of program elements to which an annotation type is applicable, such as METHOD, FIELD, TYPE, etc.

235. What is the @Documented annotation?

Answer:

It indicates that annotations with the annotated type should be documented by JavaDoc and similar tools.

236. What is reflection in Java?

Answer: 

Reflection is the ability of a program to inspect and modify its own structure and behavior at runtime, including classes, methods, fields, and annotations.

237. What is the Class class used for?

Answer: 

The Class class represents classes and interfaces in a running Java application, allowing for reflection operations like inspecting fields and methods.

238. What is the Method class used for?

Answer: 

The Method class represents a single method of a class or interface, enabling invocation of methods via reflection.

239. What is the Field class used for?

Answer: 

The Field class represents a single field of a class or interface, allowing for inspection and modification of field values via reflection.

240. What is the Constructor class used for?

Answer: 

The Constructor class represents a constructor of a class, allowing for dynamic instantiation of objects via reflection.

241. What is the Proxy class used for?

Answer: 

The Proxy class enables the creation of dynamic proxy instances that implement specified interfaces, allowing for method interception and delegation.

242. What is the java.lang.reflect package?

Answer: 

It provides classes and interfaces for obtaining reflective information about classes and objects, enabling runtime inspection and manipulation.

243. What is the AccessibleObject class?

Answer: 

It is the superclass of Field, Method, and Constructor objects, providing the ability to suppress Java language access checks via the setAccessible method.

244. What is the Annotation interface?

Answer: 

It is the common interface extended by all annotation types, providing access to annotation metadata via reflection.

245. What is the AnnotatedElement interface?

Answer: 

It represents program elements that can have annotations, such as classes, methods, fields, and constructors, providing methods to access their annotations.

246. What is the java.lang.annotation package?

Answer: 

It provides classes and interfaces for defining and handling annotations, including meta-annotations like @Retention, @Target, @Documented, and @Inherited.

247. What is the AnnotationProcessor?

Answer: 

It is a tool that processes annotations at compile time, allowing for code generation and validation based on annotation metadata.

248. What is the RetentionPolicy enum?

Answer: 

It defines how long annotations with a particular type are retained, with options SOURCE, CLASS, and RUNTIME.

249. What is the @Inherited annotation?

Answer: 

It indicates that an annotation type can be inherited from superclasses, allowing subclasses to inherit annotations from their parent classes.

250. What is the @Repeatable annotation?

Answer: 

It allows multiple instances of the same annotation to be applied to a single program element, enabling repeated annotations.

251. What is the javac command?

Answer: 

It is the Java compiler command-line tool used to compile .java source files into .class bytecode files.

252. What is the java command?

Answer: 

It is the Java application launcher command-line tool used to run Java applications by invoking the JVM with specified class files or JARs.

253. What is the jar command?

Answer: 

It is a command-line tool used to create, view, and manipulate JAR (Java Archive) files, which package multiple class files and resources into a single archive.

254. What is the javap tool?

Answer: 

It is a disassembler tool that displays the bytecode of compiled .class files, useful for debugging and understanding compiled code.

255. What is the javadoc tool?

Answer: 

It generates HTML documentation from Java source code comments, particularly those in the Javadoc format.

256. What is the jdb tool?

Answer: 

It is the Java debugger tool used for debugging Java applications, allowing setting breakpoints, inspecting variables, and stepping through code.

257. What is the javah tool?

Answer: 

Deprecated in Java 10, it was used to generate C header files for native methods in Java classes.

258. What is the ClassLoader class?

Answer: 

It is responsible for dynamically loading classes into the JVM at runtime, following a delegation model.

259. What is the parent delegation model in ClassLoader?

Answer: 

It is a hierarchical approach where a class loader delegates the class loading request to its parent before attempting to load the class itself, ensuring consistency and preventing duplicate classes.

260. What are the types of class loaders in Java?

Answer:

Bootstrap ClassLoader: Loads core Java classes from rt.jar.

Extension ClassLoader: Loads classes from the Java extensions directory.

System (Application) ClassLoader: Loads classes from the application's classpath.

Custom ClassLoaders: User-defined class loaders for specific loading mechanisms.

261. What is the URLClassLoader class?

Answer: 

A class loader that loads classes and resources from a search path of URLs, useful for loading classes from remote locations or JAR files.

262. What is the difference between StringBuilder and StringBuffer?

Answer:

StringBuilder: Not synchronized, faster, suitable for single-threaded scenarios.

StringBuffer: Synchronized, thread-safe, suitable for multi-threaded scenarios.

263. What is the java.util.Timer class?

Answer: 

It is a utility class for scheduling tasks for future execution in a background thread, supporting both one-time and recurring tasks.

264. What is the java.util.TimerTask class?

Answer: 

It is an abstract class representing a task to be scheduled by a Timer.

265. What is the difference between Timer and ScheduledExecutorService?

Answer:

Timer: Single-threaded, less flexible, can be prone to issues if tasks take too long.

ScheduledExecutorService: More flexible, supports multiple threads, better error handling, and more robust scheduling features.

266. What is the ScheduledExecutorService interface?

Answer: 

It extends ExecutorService to support scheduling tasks to run after a delay or periodically, providing a more versatile alternative to Timer.

267. What is the Callable interface?

Answer: 

It represents a task that returns a result and can throw checked exceptions, defined by the call() method.

268. What is the Runnable interface?

Answer: 

It represents a task that does not return a result and cannot throw checked exceptions, defined by the run() method.

269. What is the Future interface used for?

Answer: 

To represent the result of an asynchronous computation, providing methods to check if the computation is complete, to wait for its completion, and to retrieve the result.

270. What is the Future.get() method?

Answer: 

It retrieves the result of the computation, blocking if necessary until the result is available.

271. What is the Future.cancel() method?

Answer: 

It attempts to cancel the execution of the task, interrupting if possible.

272. What is the Future.isDone() method?

Answer: 

It checks if the computation is complete, whether normally or via an exception.

273. What is the Future.isCancelled() method?

Answer:

It checks if the task was cancelled before it completed normally.

274. What is the Thread.UncaughtExceptionHandler interface?

Answer: 

It provides a method to handle uncaught exceptions thrown by a thread, allowing custom error handling mechanisms.

275. What is the ThreadGroup class?

Answer: 

It represents a group of threads, allowing bulk operations on multiple threads, such as setting priorities or interrupting all threads in the group.

276. What is the Thread.State enum?

Answer: 

It defines the various states a thread can be in, such as NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.

277. What is the Thread.sleep() method used for?

Answer: 

To pause the execution of the current thread for a specified duration, allowing other threads to execute.

278. What is the Thread.yield() method used for?

Answer: 

To hint to the thread scheduler that the current thread is willing to yield its current use of a processor, allowing other threads to execute.

279. What is the Thread.join() method used for?

Answer: 

To wait for a thread to die, ensuring that the current thread pauses execution until the specified thread completes.

280. What is the Thread.interrupt() method used for?

Answer: 

To interrupt a thread, setting its interrupt status, which can be checked or used to interrupt blocking operations like sleep or wait.

281. What is the difference between Thread.interrupted() and Thread.isInterrupted()?

Answer:

Thread.interrupted(): Checks and clears the interrupted status of the current thread.

Thread.isInterrupted(): Checks the interrupted status without clearing it.

282. What is the RunnableFuture interface?

Answer: 

It is an interface that extends both Runnable and Future, representing a task that can be executed and can return a result.

283. What is the Phaser class used for?

Answer: 

To manage a dynamic number of threads participating in phases of execution, allowing threads to register and deregister dynamically.

logoblog

Thanks for reading 280 Core Java interview questions and answers for freshers and experienced

Previous
« Prev Post

No comments:

Post a Comment