0% found this document useful (0 votes)
21 views25 pages

Untitled 1

Uploaded by

bokaso2569
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views25 pages

Untitled 1

Uploaded by

bokaso2569
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 25

Of course.

I will provide the content in a plain text format, organized with clear headings and a
consistent structure. This will allow you to copy the entire response and paste it directly into a
document editor (like Microsoft Word, Google Docs, or a simple text editor), where you can then
adjust the formatting (bold, italics, etc.) and save it as a PDF.

I will use simple, clean formatting that will translate well to any document.

---

# Core Java Interview Questions: A Comprehensive Guide

This guide provides a detailed list of core Java interview questions, organized by topic and
difficulty level. Each question includes a concise, clear answer.

---

## 1. Java Fundamentals

### Easy (20 Questions)

1. **What is a class and what is an object?**


* A **class** is a blueprint or a template for creating objects.
* An **object** is an instance of a class, a real-world entity with a state and behavior.

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


* **JDK (Java Development Kit)**: A software development environment for creating Java
applications.
* **JRE (Java Runtime Environment)**: The runtime environment for executing Java
applications.
* **JVM (Java Virtual Machine)**: The abstract machine that executes Java bytecode, enabling
platform independence.

3. **What is the `main` method in Java?**


* It is the entry point for any Java program. The JVM starts executing code from this specific
method.

4. **What are the primitive data types in Java?**


* They include `byte`, `short`, `int`, `long`, `float`, `double`, `char`, and `boolean`.

5. **What is the difference between `==` and the `equals()` method?**


* The `==` operator compares memory addresses (object references).
* The `equals()` method compares the actual content of the objects.

6. **What is a variable?**
* A variable is a name given to a memory location used to store a value.

7. **What is a constructor?**
* A special method used to initialize an object. Its name is the same as the class, and it has no
return type.

8. **What is a package?**
* A way of organizing related classes and interfaces, helping to prevent naming conflicts.
9. **List the access modifiers in Java.**
* They are `public`, `private`, `protected`, and `default`.

10. **What is the `static` keyword?**


* It indicates that a member (variable, method, or block) belongs to the class itself, not to an
instance of the class.

11. **What is `type casting`?**


* The process of converting a variable from one data type to another.

12. **What is the purpose of the `return` statement?**


* It is used to exit a method and, optionally, return a value.

13. **What are control flow statements?**


* Statements that control the order of execution in a program, such as `if-else`, `switch`, and
loops.

14. **What is the difference between `break` and `continue`?**


* `break` terminates a loop or `switch` statement, while `continue` skips the current iteration and
proceeds to the next.

15. **What is an array?**


* A fixed-size data structure that holds a collection of elements of the same type.

16. **What are constants in Java?**


* Variables declared using the `final` keyword, whose values cannot be changed after
initialization.

17. **Can the `main` method be overloaded?**


* Yes, but the JVM will only execute the specific `public static void main(String[] args)`
signature.

18. **What is a literal?**


* A fixed value that is directly represented in the code (e.g., `100`, `"Java"`).

19. **What is the default value of local variables?**


* Local variables do not have a default value and must be explicitly initialized before use.

20. **What is an expression?**


* A combination of variables, operators, and method calls that evaluates to a single value.

---

### Medium (20 Questions)

1. **What is the difference between `String`, `StringBuilder`, and `StringBuffer`?**


* `String`: Immutable.
* `StringBuilder`: Mutable and not thread-safe.
* `StringBuffer`: Mutable and thread-safe.

2. **Explain the `final`, `finally`, and `finalize` keywords.**


* `final`: A keyword for making a variable, method, or class unchangeable.
* `finally`: A block of code in a `try-catch` statement that always executes.
* `finalize`: A method called by the Garbage Collector before an object is destroyed.

3. **What is polymorphism?**
* The ability of an object to take on many forms. It is achieved through method overloading and
overriding.

4. **What is a `marker interface`?**


* An interface with no methods, used to "mark" a class with a specific capability for the JVM
(e.g., `Serializable`).

5. **What is the difference between `this` and `super` keywords?**


* `this` refers to the current object.
* `super` refers to the immediate parent class object.

6. **What is an abstract class?**


* A class that cannot be instantiated. It can contain both abstract and concrete methods.

7. **Can we have a `try` block without a `catch` block?**


* Yes, if it is followed by a `finally` block or is a `try-with-resources` statement.

8. **What is the `transient` keyword?**


* Used to indicate that a field should not be serialized when an object is persisted.

9. **What is the difference between an `ArrayList` and a `LinkedList`?**


* `ArrayList` is better for random access, while `LinkedList` is better for insertions and deletions.

10. **Explain `method overriding`.**


* When a subclass provides a specific implementation for a method already defined in its parent
class.

11. **How does `HashMap` work in Java?**


* It stores data in key-value pairs using a hash table, where `hashCode()` determines the bucket
and `equals()` handles collisions.

12. **What is an interface?**


* A blueprint of a class that defines a contract for behavior. It can contain abstract, `default`, and
`static` methods.

13. **What is the difference between `Comparable` and `Comparator`?**


* `Comparable` is for natural ordering (within the class itself).
* `Comparator` is for custom sorting (external to the class).

14. **What is a `daemon thread`?**


* A low-priority thread that runs in the background. The JVM will exit if only daemon threads are
running.

15. **What is a `race condition`?**


* A situation where multiple threads try to access and modify shared data, leading to an
unpredictable result.
16. **What is `Deadlock`?**
* A state where two or more threads are blocked forever, waiting for each other to release a
resource.

17. **Explain the `synchronized` keyword.**


* It provides a lock on a shared resource, allowing only one thread to access it at a time.

18. **What is the difference between a process and a thread?**


* A process is a heavyweight program with its own memory space. A thread is a lightweight sub-
process that shares the memory space of its parent process.

19. **What is multithreading?**


* The concurrent execution of multiple threads to improve CPU utilization.

20. **What is the Garbage Collector in Java?**


* An automatic memory management process that reclaims memory occupied by objects that are
no longer in use.

---

### Hard (20 Questions)

1. **Explain the `try-with-resources` statement.**


* A Java 7 feature that automatically closes resources (like files) after the `try` block, preventing
resource leaks.

2. **What is JIT (Just-In-Time) compilation?**


* A JVM component that compiles Java bytecode into native machine code at runtime,
optimizing performance.

3. **Explain the `volatile` keyword.**


* It ensures a variable's value is always read from the main memory, guaranteeing visibility
across threads, but not atomicity.

4. **What is the difference between `wait()` and `sleep()`?**


* `wait()` releases the lock on an object; `sleep()` does not. `wait()` must be called inside a
synchronized block.

5. **How do `HashMap` and `HashSet` handle duplicates?**


* `HashSet` uses `HashMap` internally, leveraging key uniqueness to prevent duplicates.

6. **How does `HashMap` handle collisions?**


* By using an array of linked lists, and since Java 8, a Red-Black Tree for buckets with many
entries.

7. **What is a `fail-fast` iterator?**


* An iterator that throws a `ConcurrentModificationException` if the underlying collection is
modified during iteration.

8. **Explain `covariant return type`.**


* Allows an overriding method to return a more specific subclass of the type returned by the
overridden method.
9. **What is the Liskov Substitution Principle?**
* States that a subclass should be able to replace its superclass without affecting the program's
correctness.

10. **Explain the Open/Closed Principle.**


* States that software entities should be open for extension but closed for modification.

11. **Explain the `ExecutorService` framework.**


* A high-level API for managing a pool of threads and handling asynchronous task execution.

12. **What is the difference between `Callable` and `Runnable`?**


* `Callable` can return a value and throw a checked exception; `Runnable` cannot.

13. **What is a `ReentrantLock`?**


* An explicit lock class that provides more flexible control over thread synchronization than the
`synchronized` keyword.

14. **What is a `race condition` and how can it be prevented?**


* It's a concurrency bug. It can be prevented using synchronization mechanisms like
`synchronized` blocks or `ReentrantLock`.

15. **Explain `Lambda Expressions`.**


* A concise way to represent anonymous functions. A key feature of functional programming in
Java 8.

16. **What is the `Stream` API?**


* A powerful tool for processing collections of objects in a functional style, supporting both
sequential and parallel operations.

17. **What is `Optional`?**


* A container object that may or may not contain a non-null value, used to help prevent
`NullPointerException`.

18. **What is `Type Erasure` in Generics?**


* A compiler process where generic type information is erased after compile-time type checks,
leaving only the raw types.

19. **What is a `Method Reference`?**


* A shorthand syntax for a lambda expression that calls an existing method.

20. **What is the `CompletableFuture` class?**


* A class used for asynchronous programming, providing methods to handle tasks that may not be
completed immediately.

---

## 2. Object-Oriented Programming (OOP) in Java

### Easy (20 Questions)

1. **What are the four main pillars of OOP?**


* Encapsulation, Inheritance, Polymorphism, Abstraction.

2. **What is Encapsulation?**
* Bundling data and methods that operate on the data into a single unit. It also refers to data
hiding.

3. **What is Inheritance?**
* A mechanism where a class acquires the properties and behaviors of another class.

4. **What is Polymorphism?**
* The ability of a single interface to represent multiple different underlying forms.

5. **What is Abstraction?**
* Hiding complex implementation details and showing only essential functionality.

6. **What is the difference between a superclass and a subclass?**


* A superclass (parent) is the class being inherited from, and a subclass (child) is the class that
inherits from it.

7. **What is the `this` keyword used for?**


* It refers to the current object instance.

8. **What is the `super` keyword used for?**


* It refers to the immediate parent class object.

9. **What is Method Overloading?**


* Having multiple methods in the same class with the same name but different parameters.

10. **What is Method Overriding?**


* When a subclass provides its own implementation of a method defined in its parent class.

11. **Can a constructor be inherited?**


* No, constructors are not inherited by the subclass.

12. **Can a constructor be overloaded?**


* Yes.

13. **Can a constructor be overridden?**


* No.

14. **What is the purpose of an abstract method?**


* To declare a method that has no implementation and must be implemented by concrete
subclasses.

15. **What is a Concrete Class?**


* A class that is not abstract and can be instantiated.

16. **Can a class implement multiple interfaces?**


* Yes.

17. **Why doesn't Java support multiple inheritance of classes?**


* To avoid the "Diamond Problem" and to maintain simplicity.
18. **What are Accessors and Mutators?**
* Accessors are getter methods, and mutators are setter methods, used to control access to private
variables.

19. **What is a `default` constructor?**


* A constructor with no parameters that is automatically provided by the compiler if no other
constructor is defined.

20. **What is the `instanceof` operator?**


* Used to check if an object is an instance of a particular class or interface.

---

### Medium (20 Questions)

1. **What is the difference between an abstract class and an interface?**


* An abstract class can have instance variables and constructors. An interface can have only
abstract methods (before Java 8).

2. **What is a `marker interface`? Give an example.**


* An interface with no methods, used to "mark" a class with a capability. Example: `Serializable`.

3. **Explain the principle of encapsulation using getters and setters.**


* It involves making class members `private` and exposing controlled access through public
`getter` and `setter` methods.

4. **Explain Runtime Polymorphism.**


* The JVM determines which overridden method to call at runtime, based on the actual object
type.

5. **What is Compile-time Polymorphism?**


* The compiler determines which overloaded method to call based on the method signature at
compile time.

6. **What is `covariant return type`?**


* It allows an overriding method to return a more specific subclass of the type returned by the
overridden method.

7. **What is a final method?**


* A method that cannot be overridden by a subclass.

8. **What is a final class?**


* A class that cannot be inherited.

9. **What is the order of constructor calls in inheritance?**


* The parent class's constructor is always executed before the child class's constructor.

10. **What are the rules for Method Overriding?**


* The method signature must be the same, the return type must be the same or a covariant type,
and the access level cannot be more restrictive.
11. **When should you use an abstract class vs. an interface?**
* Use an abstract class when you need to define common behavior and state. Use an interface
when you need to define a contract for capabilities.

12. **What is loose coupling and tight coupling?**


* Loose coupling (preferred) means classes are independent. Tight coupling means classes are
highly dependent on each other.

13. **What is Method Hiding?**


* When a subclass defines a `static` method with the same signature as a `static` method in the
superclass.

14. **Can you override a `static` method?**


* No, `static` methods belong to the class, not an object.

15. **What is constructor chaining?**


* The process of a constructor calling another constructor in the same class (`this()`) or a
superclass (`super()`).

16. **Can a class be `abstract` without an `abstract` method?**


* Yes, to prevent it from being instantiated.

17. **Can an interface be `final`?**


* No.

18. **Explain the "Programming to an Interface" principle.**


* Declaring variables with an interface type (`List list = new ArrayList();`) to promote flexibility
and loose coupling.

19. **Explain Association, Aggregation, and Composition.**


* Association is a general relationship. Aggregation is a weak "has-a" relationship (e.g., Car and
Wheel). Composition is a strong "has-a" relationship (e.g., Human and Heart).

20. **What is the `protected` access modifier?**


* Accessible within the same package and by all subclasses.

---

### Hard (20 Questions)

1. **Explain the Liskov Substitution Principle (LSP).**


* Subtypes must be substitutable for their base types without altering program correctness.

2. **Explain the Open/Closed Principle (OCP).**


* Software entities should be open for extension but closed for modification.

3. **Explain the Single Responsibility Principle (SRP).**


* A class should have only one reason to change, meaning it should have only one job.

4. **Explain the Dependency Inversion Principle (DIP).**


* High-level modules should not depend on low-level modules; both should depend on
abstractions.
5. **Explain the Interface Segregation Principle (ISP).**
* Clients should not be forced to depend on methods they do not use. Prefer many small
interfaces over a single large one.

6. **What is the Diamond Problem and how do Java interfaces solve it?**
* Ambiguity in multiple inheritance. Java 8 handles it by requiring an explicit override if two
interfaces have the same default method.

7. **Why are design patterns important?**


* They are reusable solutions to common software design problems, helping create robust and
scalable code.

8. **Explain the Strategy Design Pattern.**


* Defines a family of algorithms, encapsulates each one, and makes them interchangeable.

9. **What is the difference between a static nested class and an inner class?**
* A static nested class does not need an instance of the outer class and cannot access its non-static
members. An inner class requires an outer instance.

10. **What are anonymous inner classes?**


* Classes without a name, used for on-the-fly implementation of a single-method interface.

11. **What is the Factory Method Pattern?**


* Defines an interface for creating an object, but lets subclasses decide which class to instantiate.

12. **Explain the Delegation Pattern.**


* An object forwards a request to another object (the delegate).

13. **What is reflection in Java?**


* An API that allows a program to inspect and modify its own structure and behavior at runtime.

14. **What are the drawbacks of using Reflection?**


* Performance overhead, breaking encapsulation, and security risks.

15. **What is a final variable initialized in a constructor?**


* A non-static final variable that is initialized in the constructor, which is the only place it can be
if not initialized inline.

16. **How can a class be made immutable?**


* By making the class `final`, its fields `private` and `final`, and not providing setter methods.

17. **Can you call a non-static method from a static method?**


* Only by first creating an instance of the class.

18. **Explain `Dynamic Proxy` in Java.**


* A class that can dynamically implement an interface at runtime, often used in AOP (Aspect-
Oriented Programming).

19. **What is a nested interface?**


* An interface declared inside a class or another interface.
20. **What is the difference between Deep Copy and Shallow Copy?**
* Shallow copy duplicates object references, while deep copy creates a completely new,
independent copy of all objects.

---

### 3. Collections Framework & Generics

### Easy (20 Questions)

1. **What is the Java Collections Framework (JCF)?**


* A set of classes and interfaces to represent and manipulate collections of objects.

2. **What is the difference between `Collection` and `Collections`?**


* `Collection` is the root interface; `Collections` is a utility class with static methods.

3. **What are the three main interfaces in the Collections hierarchy?**


* `List`, `Set`, and `Map` (Note: `Map` does not extend `Collection`).

4. **What is the difference between `List` and `Set`?**


* `List` is ordered and allows duplicates. `Set` is unordered and prevents duplicates.

5. **What is the primary difference between `HashSet` and `TreeSet`?**


* `HashSet` is unordered but fast. `TreeSet` is sorted but slower.

6. **How does a `Set` ensure uniqueness?**


* It uses the `hashCode()` and `equals()` methods of the stored objects.

7. **What is the difference between `ArrayList` and `LinkedList`?**


* `ArrayList` is backed by a dynamic array. `LinkedList` is backed by a doubly linked list.

8. **What is a `Queue`?**
* A collection that follows the FIFO (First-In, First-Out) principle.

9. **What is the difference between `HashMap` and `Hashtable`?**


* `HashMap` is not synchronized and allows a `null` key. `Hashtable` is synchronized and does
not allow `null` keys or values.

10. **What is Generics?**


* A feature that provides compile-time type safety for collections.

11. **What is the benefit of using Generics?**


* It prevents `ClassCastException` and eliminates the need for manual type casting.

12. **What is an `Iterator`?**


* An interface used to traverse the elements of a collection.

13. **What is the use of the `Map` interface?**


* To store data in key-value pairs.

14. **Can you store a primitive type in an `ArrayList`?**


* No, only objects. Autoboxing automatically converts primitives to their wrapper classes.
15. **What is a `Vector`?**
* A synchronized, legacy class similar to `ArrayList`.

16. **How do you get a synchronized version of an `ArrayList`?**


* Using `Collections.synchronizedList()`.

17. **What is a `ListIterator`?**


* An iterator that can traverse a `List` in both forward and backward directions.

18. **What is a `PriorityQueue`?**


* A queue where elements are ordered according to their natural order or a custom `Comparator`.

19. **What is the default initial capacity of a `HashMap`?**


* 16.

20. **What is `Load Factor` in a `HashMap`?**


* A threshold that determines when a `HashMap` should be resized.

---

### Medium (20 Questions)

1. **Explain `fail-fast` and `fail-safe` iterators.**


* A fail-fast iterator throws a `ConcurrentModificationException` if the collection is modified. A
fail-safe iterator does not.

2. **What is the difference between `HashMap` and `ConcurrentHashMap`?**


* `ConcurrentHashMap` is thread-safe and more performant for concurrent access than
`HashMap`.

3. **Explain the difference between `Comparable` and `Comparator`.**


* `Comparable` is for a single natural ordering. `Comparator` is for multiple custom orderings.

4. **How does a `HashSet` prevent duplicates?**


* It uses the key uniqueness property of the `HashMap` that it internally uses.

5. **How does `HashMap` handle collisions?**


* It uses chaining (a linked list or a tree) to store multiple key-value pairs in the same bucket.

6. **Why should you override `hashCode()` when overriding `equals()`?**


* The `equals()` and `hashCode()` contract requires that if two objects are equal, their hash codes
must be equal.

7. **What is `Type Erasure` in Generics?**


* The process where generic type information is removed by the compiler after type checks.

8. **What are Bounded Type Parameters?**


* Using `extends` or `super` with a generic type to restrict the types that can be used.

9. **What is the `Map` hierarchy?**


* The main interfaces are `Map`, `SortedMap`, and `NavigableMap`.
10. **What is a `LinkedHashMap`?**
* A `Map` that maintains the insertion order of its key-value pairs.

11. **When should you use a `TreeMap`?**


* When you need a `Map` where the keys are sorted.

12. **What is the difference between `Iterator` and `ListIterator`?**


* `ListIterator` can traverse backwards and supports element modification.

13. **Can a `Map` have duplicate keys?**


* No.

14. **Why is `Vector` considered obsolete?**


* Its synchronization mechanism is inefficient.

15. **What is the `diamond operator` (`<>`)?**


* A Java 7 feature that allows the compiler to infer generic types.

16. **What is `System.identityHashCode()`?**


* Returns the default hash code based on an object's memory address.

17. **What is `CopyOnWriteArrayList`?**


* A thread-safe `List` where all modification operations create a new copy of the underlying
array.

18. **Explain the `@SuppressWarnings("unchecked")` annotation.**


* It suppresses compiler warnings related to unchecked operations in generics.

19. **What is a `Dequeue`?**


* A double-ended queue that allows elements to be inserted or removed from both ends.

20. **What is the `Enumeration` interface?**


* A legacy interface for iterating over collections, superseded by `Iterator`.

---

### Hard (20 Questions)

1. **How are Collisions handled in `HashMap` since Java 8?**


* If a bucket's linked list gets too long (size > 8), it is converted to a Red-Black Tree for better
performance.

2. **Explain the use of Wildcards in Generics: `? extends T` and `? super T`.**


* **P.E.C.S. (Producer Extends, Consumer Super)**: `extends` is for reading (producing),
`super` is for writing (consuming).

3. **Can you use a `TreeMap` without implementing `Comparable` or passing a `Comparator`?**


* No, it requires an ordering to sort its keys.

4. **How does `TreeSet` ensure uniqueness?**


* It uses the `compareTo()` or `compare()` methods. If they return 0, the elements are considered
duplicates.

5. **Explain the Iterator vs. For-Each loop difference.**


* The Iterator allows safe element removal during iteration, while the For-Each loop does not.

6. **What is the `final` keyword's role in immutability in relation to collection fields?**


* It only makes the reference to the collection immutable, not the collection's contents.

7. **Explain `NavigableMap` and `NavigableSet`.**


* They are extensions of `SortedMap`/`SortedSet` that provide navigation methods.

8. **What is the benefit of `ArrayDeque` over `LinkedList` as a `Queue` implementation?**


* `ArrayDeque` is more efficient as it doesn't have the overhead of linked nodes.

9. **Why does the `compareTo()` method return an `int`?**


* A negative value means "less than," zero means "equal," and a positive value means "greater
than."

10. **What is the Time Complexity for basic operations on `ArrayList`, `LinkedList`, and
`HashSet`?**
* `ArrayList`: Get is O(1), Insert/Delete is O(n).
* `LinkedList`: Get is O(n), Insert/Delete is O(1).
* `HashSet`: Average O(1), Worst O(n).

11. **What are Heterogeneous collections?**


* Collections that store objects of different data types (not common in modern Java with
generics).

12. **Explain the Internal Resizing of an `ArrayList`.**


* When capacity is reached, it creates a new, larger array and copies all elements to it.

13. **What is `Collections.unmodifiableList()`?**


* A utility method that returns a read-only wrapper around a list.

14. **What are Identity Maps?**


* Specialized `Maps` that compare keys using reference equality (`==`) instead of object equality
(`equals()`).

15. **What are Weak References?**


* References that do not prevent an object from being garbage collected. Used in
`WeakHashMap`.

16. **Explain the `@Override` annotation with Collections.**


* It should be used when overriding `equals()` and `hashCode()` to ensure the correct signature.

17. **What is the difference between a `Stack` and a `Queue`?**


* `Stack` is LIFO (Last-In, First-Out). `Queue` is FIFO (First-In, First-Out).

18. **How can you optimize performance for a large number of `ArrayList` additions?**
* By initializing the `ArrayList` with an appropriate initial capacity.
19. **Why use interface types when declaring collections?**
* To promote loose coupling and make the code more flexible.

20. **What is the significance of the `E` in `ArrayList<E>`?**


* It's a common convention for a generic "element" placeholder.

---

### 4. Exception Handling

### Easy (20 Questions)

1. **What is an Exception?**
* An event that disrupts the normal flow of a program.

2. **What is Exception Handling?**


* The process of responding to an exception to prevent a program from crashing.

3. **What is the difference between `throw` and `throws`?**


* `throw` is used to explicitly throw an exception. `throws` is used in a method signature to
declare an exception.

4. **What is the hierarchy of Java exceptions?**


* `Throwable` is the root class, with `Error` and `Exception` as subclasses.

5. **What is a `try-catch` block used for?**


* The `try` block contains risky code, and the `catch` block handles exceptions that occur.

6. **What is the `finally` block used for?**


* It contains code that is guaranteed to execute, regardless of whether an exception was thrown.

7. **Can you have multiple `catch` blocks for a single `try`?**


* Yes.

8. **What is the difference between `Error` and `Exception`?**


* `Error` is for serious, often unrecoverable problems. `Exception` is for problems that can be
handled.

9. **What is a Checked Exception?**


* An exception that must be handled or declared at compile time.

10. **What is an Unchecked Exception?**


* An exception that occurs at runtime and does not need to be explicitly handled.

11. **Where is a `Stack Trace` printed?**


* To the standard error stream.

12. **What happens if a `try` block doesn't throw an exception?**


* The `catch` block is skipped.

13. **Can an exception be re-thrown?**


* Yes.
14. **What is the purpose of the `printStackTrace()` method?**
* It prints the full stack trace of the exception.

15. **Can a `catch` block be empty?**


* Yes, but it is a bad practice.

16. **What is a `RuntimeException`?**


* The base class for all unchecked exceptions.

17. **Name two common `RuntimeException` examples.**


* `NullPointerException`, `ArrayIndexOutOfBoundsException`.

18. **Name two common checked exception examples.**


* `IOException`, `SQLException`.

19. **What is the order of execution: `try`, `catch`, `finally`?**


* `try` -> `catch` (if needed) -> `finally`.

20. **Does the `finally` block always execute?**


* Almost always, unless the JVM crashes or `System.exit()` is called.

---

### Medium (20 Questions)

1. **Explain the `try-with-resources` statement.**


* It automatically closes resources, eliminating the need for a `finally` block for cleanup.

2. **What happens if an exception is thrown in the `finally` block?**


* It will override any pending exception from the `try` or `catch` block.

3. **Can you throw an `Error`?**


* Yes, but it is highly discouraged.

4. **How do you create a custom checked exception?**


* By extending `java.lang.Exception`.

5. **How do you create a custom unchecked exception?**


* By extending `java.lang.RuntimeException`.

6. **What is `exception propagation`?**


* An exception being passed up the method call stack until it is caught.

7. **What is a `catch-all` block? Why is it a bad idea?**


* `catch(Exception e)`. It masks serious problems and makes debugging difficult.

8. **Explain the `multi-catch` block (since Java 7).**


* A single `catch` block that can handle multiple exception types.

9. **What is the difference between `System.exit(0)` and `System.exit(1)`?**


* `exit(0)` indicates success; `exit(1)` indicates an error.
10. **What is `exception chaining`?**
* Linking one exception to another using the `initCause()` method.

11. **Why use `System.err.println()` for logging exceptions?**


* It writes to the standard error stream, ensuring the message is displayed even if standard output
is redirected.

12. **What is the purpose of the `getLocalizedMessage()` method?**


* Returns a localized description of the exception.

13. **Can a `catch` block throw an exception?**


* Yes.

14. **Why is it discouraged to rely on the `finalize()` method for cleanup?**


* Its execution is not guaranteed or predictable.

15. **In a `try-catch-finally` block, if `try` has a `return`, will `finally` execute?**
* Yes, `finally` executes before the method returns.

16. **What is `Suppressed Exception`?**


* Exceptions that are suppressed when another exception is thrown from a `try-with-resources`
block's `close()` method.

17. **What does the keyword `assert` do?**


* It checks a boolean condition and throws an `AssertionError` if it's false.

18. **How is `NullPointerException` different from `IOException` in terms of handling?**


* `NPE` is unchecked and doesn't need to be handled. `IOException` is checked and must be
handled.

19. **Explain the principle of least privilege in exception handling.**


* Catch only the most specific exception you can handle.

20. **What is the general rule regarding the placement of `catch` blocks?**
* More specific exceptions must be caught before more general ones.

---

### Hard (20 Questions)

1. **How can you prevent a `NullPointerException`?**


* By using conditional checks, the `Optional` class (Java 8+), or defensive programming.

2. **Explain the difference between `OutOfMemoryError` and `StackOverflowError`.**


* `OOME` occurs when the heap is full. `SOE` occurs when the call stack overflows, usually due
to infinite recursion.

3. **Why does `finally` always execute before a `return` in `try`?**


* The JVM ensures that the cleanup code in `finally` runs before the method exits.

4. **Can you rethrow a checked exception without declaring it in the method signature?**
* Yes, in Java 7+ if it's caught in a multi-catch block and the compiler can prove it's an
unchecked exception.

5. **Explain the internal working of `try-with-resources`.**


* The compiler generates bytecode that implicitly includes a `finally` block to close the
resources.

6. **What is the `getSuppressed()` method?**


* A `Throwable` method that returns an array of exceptions that were suppressed by the primary
exception.

7. **Write a scenario where the `finally` block would not execute.**


* If the JVM crashes or `System.exit()` is called.

8. **What is `serialVersionUID`?**
* A unique ID for a `Serializable` class that ensures version compatibility during serialization and
deserialization.

9. **What is the purpose of the `assert` keyword?**


* It is used for internal sanity checks.

10. **What happens if the `catch` block also contains a `return` statement?**
* The `finally` block executes, and then the method returns from the `catch` block.

11. **Explain "swallowing" of exceptions. Why is it bad?**


* Catching an exception without handling or logging it. It hides bugs.

12. **If both `try` and `finally` throw an exception, which one is thrown to the caller?**
* The exception from the `finally` block is thrown.

13. **How is `ClassNotFoundException` different from `NoClassDefFoundError`?**


* `CNFE` is a checked exception. `NCDE` is an error thrown when a class was found at compile
time but not at runtime.

14. **Can you override a method that throws a checked exception with one that throws an
unchecked exception?**
* Yes.

15. **Can you rethrow an exception without assigning it to a new variable?**


* Yes, `throw e;`.

16. **Why is it discouraged to catch `Throwable`?**


* It catches `Error` as well, which can hide fatal JVM problems.

17. **When should you use a custom exception?**


* When built-in exceptions don't clearly describe a business-specific error.

18. **Explain Checked Exception handling in an Interface context.**


* Implementing classes must handle or declare the checked exceptions declared in the interface
method.

19. **What are the possible causes of an `IllegalStateException`?**


* A method being called at an inappropriate time for an object's current state.

20. **Does the order of resources matter in a `try-with-resources` statement?**


* Yes, they are closed in the reverse order of their declaration.

---

### 5. Multithreading & Concurrency

### Easy (20 Questions)

1. **What is a Thread?**
* The smallest unit of execution in a program.

2. **What are the two ways to create a thread?**


* Extend the `Thread` class or implement the `Runnable` interface.

3. **What is the difference between `start()` and `run()`?**


* `start()` creates a new thread and calls `run()` on it. `run()` just executes on the current thread.

4. **What is Multithreading?**
* The concurrent execution of multiple threads.

5. **What is Thread Synchronization?**


* Controlling access to shared resources to prevent concurrency issues.

6. **What is `Deadlock`?**
* A state where two or more threads are blocked forever, waiting for each other.

7. **What is a `race condition`?**


* When multiple threads access and modify shared data, leading to an unpredictable result.

8. **What is the `synchronized` keyword used for?**


* To acquire a lock on an object or method.

9. **What is a `daemon thread`?**


* A low-priority background thread.

10. **What is the `sleep()` method?**


* Pauses the current thread without releasing any locks.

11. **What is the purpose of the `join()` method?**


* Waits for a thread to complete its execution.

12. **What is the default priority of a thread?**


* `NORM_PRIORITY` (5).

13. **Can you start a thread twice?**


* No, it throws an `IllegalThreadStateException`.

14. **What is a Thread Pool?**


* A collection of threads that can be reused to execute tasks.
15. **What is Concurrency?**
* The ability to handle multiple tasks at the same time.

16. **What is Parallelism?**


* The simultaneous execution of multiple tasks on multiple processors.

17. **Can the `run()` method throw an exception?**


* Only unchecked exceptions (`RuntimeException`).

18. **What is a `ThreadLocal` variable?**


* A variable that provides each thread with its own independent copy.

19. **What does the `yield()` method do?**


* Causes the current thread to pause and allows other threads of the same priority to run.

20. **What is the best way to create a thread?**


* By implementing `Runnable`, as it allows for multiple inheritance of interfaces.

---

### Medium (20 Questions)

1. **Explain the Thread Life Cycle states.**


* New, Runnable, Running, Blocked, Waiting, Timed Waiting, Terminated.

2. **What is the difference between `wait()` and `sleep()`?**


* `wait()` releases a lock and must be in a synchronized block. `sleep()` does not release a lock.

3. **What is Inter-thread Communication?**


* Threads exchanging data, achieved using `wait()`, `notify()`, and `notifyAll()`.

4. **What is the `volatile` keyword?**


* It ensures visibility (changes are written to main memory) but not atomicity.

5. **Explain the `ExecutorService` framework.**


* A high-level API for managing a thread pool, separating task submission from thread execution.

6. **What is the difference between `Callable` and `Runnable`?**


* `Callable` can return a value and throw a checked exception. `Runnable` cannot.

7. **How do you gracefully stop a thread?**


* By using a `volatile` flag that the thread periodically checks.

8. **What is the `ReentrantLock`?**


* A more flexible alternative to the `synchronized` keyword for locking.

9. **What is a `CyclicBarrier`?**
* A synchronization aid that allows a set of threads to wait for each other to reach a common
point.

10. **What is a `CountDownLatch`?**


* A synchronization aid that allows one or more threads to wait until a set of operations are
completed.

11. **What is the use of the `Thread.interrupt()` method?**


* Sends an interrupt request to a thread.

12. **What is Starvation?**


* When a thread is perpetually denied access to a shared resource.

13. **What is Livelock?**


* Threads are active but unable to make progress because they are constantly reacting to each
other.

14. **How do you create a thread-safe singleton?**


* Using a synchronized method, synchronized block, or `volatile` with double-checked locking.

15. **What is the `tryLock()` method?**


* Attempts to acquire a lock and returns `true` if successful, or `false` otherwise.

16. **What are immutable objects and how do they help concurrency?**
* Objects that cannot be changed after creation. They are inherently thread-safe.

17. **What are Atomic variables?**


* Classes like `AtomicInteger` that provide thread-safe operations on single variables without
explicit locks.

18. **How is a `wait()` call typically structured?**


* Inside a `synchronized` block and within a `while` loop to handle spurious wake-ups.

19. **What is Spurious Wakeup?**


* When a waiting thread wakes up without being notified.

20. **What is the `Executors` utility class?**


* Provides factory methods for creating common `ExecutorService` instances.

---

### Hard (20 Questions)

1. **Explain AQS (AbstractQueuedSynchronizer).**


* A framework used by concurrency classes to build locks and synchronizers by managing a
FIFO queue of waiting threads.

2. **Explain Double-Checked Locking (DCL). Why is `volatile` essential?**


* A pattern for lazy initialization of a thread-safe singleton. `volatile` prevents instruction
reordering.

3. **What is the difference between internal and external locking?**


* Internal locking uses `synchronized` on an object. External locking uses explicit `Lock` objects.

4. **How does `ConcurrentHashMap` achieve high concurrency?**


* By using an array of synchronized segments, allowing multiple threads to write to different
parts of the map concurrently.

5. **Explain the Compare-And-Swap (CAS) operation.**


* An atomic CPU instruction that updates a value only if it matches an expected value.

6. **What is the ABA problem in CAS?**


* A value changes from A to B and back to A, fooling a CAS operation.

7. **Explain Thread Interruption in detail.**


* Interruption is cooperative. A thread's interrupt status flag is set, and the thread must check and
handle it.

8. **What is a `ForkJoinPool`?**
* An `ExecutorService` designed for parallel execution of tasks that can be broken down and
merged.

9. **What is the `Phaser`?**


* A reusable synchronization barrier that allows threads to wait for each other across multiple
phases of a task.

10. **Explain the Happens-Before relationship in the Java Memory Model.**


* A set of rules that guarantee visibility of memory writes across threads.

11. **What are `SynchronousQueue` and `DelayQueue`?**


* `SynchronousQueue` is a zero-capacity queue. `DelayQueue` holds elements that can only be
retrieved after a specific delay.

12. **When should you use a `ReentrantReadWriteLock`?**


* When a resource is read much more often than it is written.

13. **What is Thread Starvation? How can it be mitigated?**


* A thread is perpetually denied CPU time. Mitigated by using fair locks.

14. **What are thread-safe collections? Give examples.**


* Collections that can be accessed by multiple threads without explicit synchronization. E.g.,
`ConcurrentHashMap`.

15. **What is the purpose of `shutdown()` and `shutdownNow()` on `ExecutorService`?**


* `shutdown()` waits for tasks to finish. `shutdownNow()` tries to stop all running tasks
immediately.

16. **Why is it dangerous to synchronize on a `String` literal?**


* String literals are interned, which could cause unintended locks in unrelated parts of the code.

17. **What is a `Future` object?**


* A handle to the result of an asynchronous computation.

18. **Explain Thread Scheduling (Time Slicing vs. Preemptive).**


* Preemptive: The OS decides when to switch threads. Time Slicing: Each thread gets a fixed
time slot.
19. **What is the `ForkJoinTask` class?**
* The base class for tasks running in a `ForkJoinPool`.

20. **Explain Optimistic vs. Pessimistic Locking.**


* Pessimistic locking assumes conflicts and locks resources. Optimistic locking assumes no
conflicts and uses CAS to verify.

---

### 6. Java 8+ Features (Lambda, Streams, Optional, etc.)

### Easy (20 Questions)

1. **What is a Lambda Expression?**


* A concise way to represent a method interface using an anonymous function.

2. **What is a Functional Interface?**


* An interface with exactly one abstract method.

3. **What is the `@FunctionalInterface` annotation?**


* An optional annotation that ensures an interface is a functional interface.

4. **What is the Stream API?**


* A sequence of elements supporting sequential and parallel aggregate operations.

5. **What is the purpose of the `Optional` class?**


* To represent a value that may or may not be present, helping to avoid `NullPointerException`.

6. **What are `default` methods in an interface?**


* Methods with an implementation in the interface itself, allowing for backward compatibility.

7. **What are `static` methods in an interface?**


* Utility methods that are part of the interface and can be called directly.

8. **What is the `forEach` method?**


* A method used to iterate over elements of a collection or stream.

9. **What is the `::` (double colon) operator?**


* The Method Reference operator, a shorthand for a lambda expression.

10. **Name two common `Stream` operations.**


* `filter()`, `map()`, `collect()`, `forEach()`.

11. **What is the difference between a `Stream` and a `Collection`?**


* A `Collection` stores data; a `Stream` is a pipeline for computations.

12. **What does the `filter()` method do?**


* It creates a new stream containing only elements that satisfy a condition.

13. **What does the `map()` method do?**


* It transforms each element in a stream.
14. **What is the `Optional.isPresent()` method?**
* Returns `true` if the `Optional` object contains a value.

15. **What is the `Optional.get()` method?**


* Returns the value, or throws `NoSuchElementException` if the `Optional` is empty.

16. **How do you convert a `List` to a `Stream`?**


* Using the `list.stream()` method.

17. **What is the `@Override` rule for `default` methods?**


* Subclasses can override a `default` method.

18. **What is the `Stream.of()` method used for?**


* To create a stream from a set of arguments.

19. **What is the purpose of `Collectors.toList()`?**


* A terminal operation that gathers all stream elements into a `List`.

20. **What is the `or` method in `Optional` (Java 9+)?**


* Returns the value if present, otherwise returns a value from a supplier.

---

### Medium (20 Questions)

1. **What is the difference between `intermediate` and `terminal` stream operations?**


* Intermediate operations are lazy and return a stream. Terminal operations are eager and produce
a result.

2. **Explain `lazy evaluation` in streams.**


* The stream pipeline is executed only when a terminal operation is called.

3. **Explain the difference between `map()` and `flatMap()`.**


* `map()` transforms one element into another. `flatMap()` transforms one element into a stream
and then flattens all streams into one.

4. **How do you use streams to achieve parallelism?**


* By calling `parallelStream()` or `parallel()`.

5. **Explain `Optional.orElse()` and `Optional.orElseGet()`.**


* `orElse()` evaluates its default value eagerly. `orElseGet()` evaluates it lazily.

6. **What is a `BiFunction`?**
* A functional interface that accepts two arguments and produces a result.

7. **How do you implement a `reduce` operation on a stream?**


* Using the `reduce()` method, which combines elements into a single result.

8. **Explain Method References (`::`). List the four types.**


* A shorthand for lambdas. Types: static, instance of a specific object, instance of an arbitrary
object, and constructor.
9. **What is `Type Inference` with Lambdas?**
* The compiler automatically determines the parameter types of a lambda expression.

10. **What is the purpose of `Collectors.groupingBy()`?**


* To group elements of a stream into a `Map` based on a classifier function.

11. **What is `Optional.ofNullable()`?**


* Creates an `Optional` with a value if non-null, or an empty `Optional` if null.

12. **Why is using `Optional` in method parameters discouraged?**


* `Optional` is intended as a return type to handle the absence of a value.

13. **What is the purpose of the `peek()` method in streams?**


* An intermediate operation used for debugging.

14. **What are `stateful` vs. `stateless` intermediate operations?**


* Stateless (`filter`) don't rely on past elements. Stateful (`sorted`) need to process all elements.

15. **What are `VarHandle` and `MethodHandle`?**


* Low-level APIs for manipulating fields and methods, used for advanced concurrency.

16. **What is the purpose of the `tryLock()` method on `Optional` (Java 9+)?**
* This is a trick question. `tryLock()` is on `Lock` interfaces, not `Optional`.

17. **What is the `CompletableFuture` class?**


* A class for asynchronous programming, allowing you to chain dependent tasks.

18. **How is `Collectors.partitioningBy()` different from `groupingBy()`?**


* `partitioningBy()` groups elements into only two groups (`true`/`false`).

19. **What is the `Stream.Builder` class?**


* Used to build a stream programmatically.

20. **What is the difference between a `Stream` and an `Iterable`?**


* An `Iterable` is for simple traversal. A `Stream` is for functional-style operations.

---

### Hard (20 Questions)

1. **Explain Thread Confinement in parallel streams.**


* Ensuring that mutable state is accessed by only one thread.

2. **What is the `UnmodifiableList` view returned by `Collectors.toUnmodifiableList()`?**


* It creates a truly immutable list that cannot be modified.

3. **How do you combine two streams efficiently?**


* Using `Stream.concat()`, which is a lazy operation.

4. **Why is `sorted()` expensive in a parallel stream?**


* It is a stateful operation that requires all data to be collected and sorted before it can proceed.
5. **What are the performance considerations when using `parallelStream()`?**
* It's good for large, CPU-intensive tasks but can be slow for I/O-bound tasks.

6. **Explain the JVM's handling of `default` methods in interfaces.**


* The JVM adds a default method to a class at runtime unless the class has its own
implementation.

7. **How does the `reduce()` operation guarantee correctness in parallel streams?**


* By requiring the reduction function to be associative, allowing for partial, parallel reductions.

8. **What is a `Collector`? What are the four parts?**


* An interface that implements a reduction. Parts: Supplier, Accumulator, Combiner, Finisher.

9. **What is `Optional.flatMap()` used for?**


* To prevent nested `Optional` objects when a function returns an `Optional`.

10. **Explain the use of the `var` keyword (Java 10+).**


* It allows local variable type inference, making code cleaner while retaining type safety.

11. **What are Sealed Classes (Java 17)?**


* Classes that restrict which other classes can extend or implement them.

12. **Explain the `record` keyword (Java 16).**


* A concise syntax for creating immutable data classes.

13. **What is Pattern Matching for `instanceof` (Java 16)?**


* A new feature that combines an `instanceof` check with a local variable declaration.

14. **How do you create an infinite stream?**


* Using `Stream.iterate()` or `Stream.generate()`.

15. **What is the `Stream.collect(supplier, accumulator, combiner)` overload?**


* The general-purpose method for mutable reduction.

16. **How do you correctly implement `equals()` and `hashCode()` for a class used in a stream
operation?**
* The class should be immutable, and the methods should be based on all fields that contribute to
uniqueness.

17. **What is the purpose of `Optional.ifPresentOrElse()` (Java 9)?**


* It executes one action if a value is present, and another action otherwise.

18. **Explain `Switch Expressions` (Java 14).**


* An extension to the `switch` statement that can be used as an expression.

19. **What are Text Blocks (Java 15)?**


* A multi-line string literal format that reduces the need for escape characters.

20. **How do `limit()` and `skip()` work in a lazy stream?**


* They are intermediate operations that stop processing once their condition is met, improving
efficiency.

You might also like