0% found this document useful (0 votes)
3 views40 pages

Java Interview Handbook Styled

Uploaded by

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

Java Interview Handbook Styled

Uploaded by

fantacy.market
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA INTERVIEW REVISION HANDBOOK

Structured from Basic → Advanced Topics

JAVA BASICS
Answer:
In Java:
Answer:
== checks if two references point to the same object in memory.
Answer:
.equals() checks if two objects are considered equal by their value/content (as defined by the
class’s equals method).
Answer:
Example with Integer:
Answer:
Java
Integer a = 127;
Integer b = 127;
[Link](a == b); // true
[Link]([Link](b)); // true
Integer a = 128;
Integer b = 128;
[Link](a == b); // false
[Link]([Link](b)); // true

Answer:
This happens because Java caches Integer objects for values from -128 to 127. Integer variables within
this range refer to the same object when created using valueOf() (default for autoboxing),
hence == returns true. Outside this range, new Integer objects are created, so == returns false.

OOP CONCEPTS
Q. What is the difference between abstraction and encapsulation in Java? Explain
with examples.
Answer:
Abstraction:
Answer:
Definition: Abstraction is the concept of showing only essential details to the user and hiding the
implementation details.
Answer:
Example: Abstract classes and interfaces let you declare methods that must be implemented by
subclasses, while the specific implementation is hidden.
Answer:
Usage: Use abstract classes or interfaces when you want to define a contract or functionality without
specifying the details.
Answer:
Java
abstract class Animal {
abstract void eat(); // abstraction: we don’t say HOW animals eat
}
class Dog extends Animal {
void eat() { [Link]("Dog eats bones"); } // concrete implementation
}

Answer:
Encapsulation:
Answer:
Definition: Encapsulation means wrapping data (fields) and code (methods) together in a class, and
controlling access to them.
Example: Using private fields and public getter/setter methods so the internal
state can’t be accessed directly.

Answer:
Usage: Protects the internal state and only allows it to be changed in a controlled manner (through
methods).
Answer:
Java
class Person {
private String name;
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
}

Answer:
Access modifiers:
Answer:
private: visible only within the class
Answer:
default (no modifier): visible only within package
Answer:
protected: visible within package and subclasses (even outside package)
Answer:
public: visible everywhere

Q. Why answer like this?


Answer:
Interviewers want to see that:
Answer:
You understand abstraction hides implementation, lets you specify what (not how)
Answer:
You understand encapsulation means bundling data and restricting access—using access modifiers

Q. What is Polymorphism in Java? Can you give two types and a real-life code
example?
Answer:
Polymorphism:
Answer:
Definition: Polymorphism allows objects to be treated as instances of their parent class, enabling a
single interface with multiple implementations.
Answer:
Types:
Answer:
Compile-time polymorphism (Method Overloading):
Answer:
Multiple methods with the same name but different parameter lists (number, type, or both).
Answer:
Decided at compile time.
Answer:
Example:
Answer:
Java
class MathUtil {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}

Answer:
Run-time polymorphism (Method Overriding):
A subclass overrides a method of the parent class.

Answer:
Decided at runtime, allows dynamic method dispatch.
Answer:
Example:
Answer:
Java
class Animal {
void speak() { [Link]("Animal speaks"); }
}
class Dog extends Animal {
void speak() { [Link]("Dog barks"); }
}
Animal a = new Dog();
[Link](); // prints "Dog barks"

Q. What is the difference between composition and inheritance in Java? In which


scenarios would you prefer one over the other, and why? Give examples.
Answer:
Inheritance:
Answer:
(“extends”) Expresses an IS-A relationship.
Use when one class is a specialized version of another.

Answer:
Example:
Answer:
Java
class Animal { void speak() {} }
class Dog extends Animal { void speak() { [Link]("Bark"); } }

Answer:
Here, Dog IS-A Animal.
Answer:
Composition:
Answer:
Expresses a HAS-A relationship.
A class is composed of one or more objects from other classes; delegates
behavior.

Answer:
Example:
Answer:
Java
class Engine { void start() {} }
class Car {
private Engine engine = new Engine(); // composition
void startCar() { [Link](); }
}

Answer:
Here, Car HAS-A Engine.

Q. Why prefer composition?


Answer:
More flexible—behavior can be changed at runtime or by swapping components.
Answer:
Leads to looser coupling and easier maintenance.

Q. When to use inheritance?


Answer:
When subclassing gives clear code re-use, follows Liskov Substitution, and matches real domain (“Dog
IS-A Animal”).

Q. When to use composition?


Answer:
By default—especially for sharing code/behavior, or when combining functionality from different
classes.
Inheritance: Acquires features from parent class;

Answer:
Java
class Animal {}
class Dog extends Animal {}
Polymorphism: One interface, many implementations;

Answer:
Java
Animal a = new Dog(); [Link](); // Calls Dog's version
Encapsulation: Data hidden with accessors;

Answer:
Java
private int age; public int getAge() { return age; }
Abstraction: Hides complexity with interfaces/abstract classes;

Answer:
Java
abstract class Shape { abstract void draw();

COLLECTIONS FRAMEWORK
Q. What is the difference between ArrayList and LinkedList in Java? When would
you use one over the other? Provide reasoning and basic example code.

ArrayList:
Answer:
Indexed list backed by a dynamic array (contiguous memory).
Answer:
Fast access by index (O(1)).
Answer:
Insertion/removal at end is fast (O(1)), middle is slow (O(n)) due to shifting elements.
Answer:
Good for scenarios where you need to access elements frequently by index.
Answer:
LinkedList:
Answer:
Doubly-linked structure, elements are not stored in contiguous memory.
Answer:
Access by index is slow (O(n)), as traversal is needed.
Answer:
Insertion/removal at head/tail is fast (O(1)), middle insertion is O(n) if position must be found by
index.
Answer:
Good for scenarios with frequent insertions/removals from ends.
Answer:
Example:
List<String> arrList = new ArrayList<>();
[Link]("A"); // O(1)
[Link](0); // O(1)
List<String> linkList = new LinkedList<>();
[Link]("A"); // O(1)
[Link]("B"); // O(1)
[Link](); // prints "Dog barks"

Answer:
When to use:
ArrayList: Frequent indexed access, infrequent inserts/removals except at end.

Answer:
LinkedList: Frequent insertions/removals at ends, less need for indexed access.
List<Integer> list = new ArrayList<>(); // only Integers allowed
[Link](42);
// [Link]("hello"); // compile-time error
for (Integer i : list) {
[Link](i); // no cast needed
}

Answer:
Without generics:
List list = new ArrayList();
[Link](42); // OK
[Link]("hello"); // OK

Answer:
// Run-time error when retrieving and casting
Usage: Canonicalized mappings, like keys in WeakHashMap, to avoid memory leaks.

Answer:
Phantom Reference:
PhantomReference<Object> ref = new PhantomReference<>(obj, queue);

Answer:
Used to know exactly when an object is removed from memory (object is already finalized, used for
resource cleanup, and always enqueued post-GC).
Answer:
Usage: Plug-ins for post-mortem cleanup, advanced resource management.
Answer:
Example:
Answer:
Example:
Answer:
Java
Object obj = new Object();
SoftReference<Object> softRef = new SoftReference<>(obj);
WeakReference<Object> weakRef = new WeakReference<>(obj);
ReferenceQueue<Object> queue = new ReferenceQueue<>();
PhantomReference<Object> phantomRef = new PhantomReference<>(obj, queue);
static List<User> userList = new ArrayList<>();

Answer:
If you add user objects and never remove them, even if they’re obsolete, the list keeps growing—
objects are never eligible for GC.
Answer:
Listener leaks: Registering event listeners but never deregistering them (e.g., GUI listeners).
Caches with strong references: E.g., HashMap caching objects but never removing
them.
Answer:
Detection:
Answer:
Using tools like VisualVM, Eclipse MAT (Memory Analyzer Tool), YourKit, or JProfiler.
Answer:
Look for steady memory increase, many unreachable objects referenced from roots (like static
variables).
Answer:
Prevention:
Answer:
Remove references when objects are no longer needed.
Use weak references in caches or listeners (WeakHashMap).

Answer:
Be careful with static fields and inner classes.
Answer:
Regularly profile memory in large applications.
11. HashMap vs Hashtable
HashMap: Fast, not thread-safe, allows nulls.
Use HashMap unless legacy or strict thread-safety is required.
12. ConcurrentHashMap

Answer:
Allows safe concurrent access with minimal locking by segmenting the map.
13. ArrayList vs LinkedList
ArrayList: Fast random access, slow insert/delete (especially in the middle).

Answer:
LinkedList: Fast insert/delete, slow random access.
Use ArrayList for most cases, LinkedList for frequent inserts/deletes.

Answer:
14. Comparator vs Comparable
Answer:
Comparable: Natural ordering (defines compareTo in the class).
Answer:
16. fail-fast vs fail-safe Iterators
fail-fast: Throws exception if collection is modified while iterating
(e.g. ArrayList).
fail-safe: Works on a copy; no exception (e.g. CopyOnWriteArrayList).

Answer:
22. HashSet vs TreeSet
Answer:
HashSet: Fast, unordered, uses hashCode.
Answer:
TreeSet: Sorted, slower, uses compareTo or Comparator.
Answer:
23. Shallow Copy vs Deep Copy
Answer:
Shallow: Copies references.
Answer:
Deep: Copies entire object graph (new objects).
Answer:
24. Immutability (why is String immutable?)
Answer:
Prevents accidental/unwanted changes.
Queue: First-in-first-out; use Queue or LinkedList.

Q. What is ArrayList internally?


ArrayList internally uses a dynamic array.

Answer:
Meaning:
Answer:
Starts small
Answer:
Expands automatically
Answer:
Stores elements continuously in memory
Answer:
Default capacity after creation
Answer:
When you create:
List<Integer> list = new ArrayList<>();

Answer:
Size = 0, Capacity = 0 (YES — this is true in JDK 8+)
ArrayList does not allocate memory until you add the first element.

Q. What happens on first add()?


Answer:
Creates internal array of size 10 (Default capacity = 10)
Answer:
So after first add:
Answer:
Size = 1
Answer:
Capacity = 10

Q. 4. What happens when array becomes full?


Answer:
Let’s say capacity = 10 and you add the 11th element.
ArrayList grows automatically using this formula:

Answer:
✔ New Capacity = Old Capacity + (Old Capacity / 2)
Answer:
Which means 1.5 times expansion.
When ArrayList fills up:

Answer:
A new bigger array is created
Old elements are copied to new array
Reference is shifted to new array
Old array is eligible for GC
Answer:
👉 Resizing is expensive (O(n))
Answer:
That’s why:
Answer:
Adding at end = usually O(1)
Answer:
But sometimes “amortized O(n)” when resize happens

Q. How does ArrayList grow internally?


ArrayList grows by 1.5x its old capacity. It allocates a new array using
newCapacity = oldCapacity + oldCapacity / 2,
then copies old elements to the new array, and the old array is garbage
collected.
This resizing is costly, so adding is amortized O(1).

Q. What is LinkedList?
Answer:
LinkedList is a doubly linked list implementation of:
Answer:
List interface
Answer:
Deque interface
Answer:
So it supports:
Answer:
FIFO (Queue)

Q. When to use LinkedList?


Answer:
Use LinkedList when:
Answer:
Frequent insertions/removals are required
Answer:
You work with Queue/Deque operations
Answer:
Accessing elements by index is NOT a priority
Answer:
Do NOT use LinkedList when:
Answer:
You need fast access (get(i) / set(i))

Q. Why LinkedList is slow for get(index)?


Answer:
Because it must traverse from head or tail until it reaches the index.
No direct memory access.

Q. Is LinkedList thread safe?


No (like ArrayList)

Q. Why LinkedList consumes more memory?


Answer:
Because each node stores:
Answer:
value
Answer:
next pointer
Answer:
previous pointer
We have “make & edit” dialog in our sismage app
and in this dilapge we have 2 panel
“Compute mismatches”in which we select the wellbore and have this “Compute
Mismatch” button on click of which we are able to see mismatchOutput value
table and the of it
once we clicked on this “Compute Mismatch” button we are able to see some value
in “with influence radius of” field and this field is in
“Adjust” panel and one of the dialoge box also popup
of name "Created Mismatches for " + [Link](),
public MismatchesDisplayDialog(SismageJFrame parent, MismatchesProcessOutput
output) {
super(parent, "Created Mismatches for " + [Link](), false,
SismageModule.SURFACE_POLYGON_GRAPH_TST_MAP);
[Link] = [Link]();
[Link] = [Link]();
mismatches = output;
initGUI();
}
any way we need to work on “Adjust” creation
so in this “Adjust” panel we have this “Shift and flex”
and “Create new version” radio button once we select both of them and click on
“Adjust” button which is bellow
the new horizon is created

but we have noticed the new horizon which is created is below the old horizon
or reference one and distance between them is same as mismatchOutput value the
distande between them is correct but we want this new _ adjusted horizon which
got created will created above not below the existing one
I just feel like we need to subtract this adjusted mismatchOutput value not
added while creation or vice vesra

analyze the code and class and see what are the factor and thing responsible
for this behavioure and see if it posibe to create this new adjusted horizon
above in please of down
give me code changes which are required to perform this task
How does the internal structure of HashMap change after Java 8, and why was
this change made? What problem does it solve?
Before Java 8, each HashMap bucket was a linked list of entries with the same
hash code. If many keys collided (bad hash distribution), these lists could
become very long, making get/put operations O(n) for a bucket.
From Java 8 onward, HashMap changes:

Answer:
When a bucket becomes too large (default threshold: 8), it turns from a linked list into a balanced
binary tree (specifically, a red-black tree).
Answer:
In a tree, lookups and inserts are O(log n) instead of O(n).

Q. Why was this change made?


Answer:
To fix performance issues caused by hash collisions and poor hashCode implementations.
Answer:
Tree structure ensures consistent performance even with many collisions, preventing denial-of-service
attacks and speeding up operations on large bucket chains.
Summary:
Java 8 improved HashMap's worst-case performance by switching from linked lists
to balanced trees within buckets when collisions are high.

Q. What is CopyOnWriteArrayList? How does it achieve thread safety, and when


would you use it over other collection types?
CopyOnWriteArrayList is a thread-safe variant of ArrayList
from [Link].
It achieves thread safety by copying the entire array whenever it's modified
(add, set, remove), so readers always see a consistent snapshot. Its iterators
are fail-safe—they iterate over the snapshot, so they never
throw ConcurrentModificationException.

Answer:
When to use:
Answer:
Ideal for situations where reads greatly outnumber writes (e.g., event listeners, configuration objects).
Answer:
Not efficient for frequent modifications, since every write copies the array.
Summary:
CopyOnWriteArrayList is best for read-heavy concurrency scenarios; it trades
update performance for safe, fast reads and fail-safe iteration.

Q. Explain the difference between fail-fast and fail-safe iterators in Java. Give
practical examples of each.
Answer:
Fail-fast iterators detect structural modifications to the collection during iteration and immediately
throw a ConcurrentModificationException.
Example:
Answer:
Java
List<String> list = new ArrayList<>();
for (String s : list) {

Answer:
To update safely during iteration, always use the iterator’s remove() method:
Answer:
Java
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]();

Answer:
Fail-safe iterators allow concurrent modifications without exception because they iterate over a
snapshot or copy of the collection.
Examples include:
CopyOnWriteArrayList (iterator over a snapshot)
ConcurrentHashMap (iterator is weakly consistent)

Answer:
Modifications during iteration are visible only to future iterators—current iterator never fails.
Summary:
Fail-fast: throws error if modified during iteration (e.g., ArrayList,
HashMap).
Fail-safe: allows safe iteration and concurrent updates (e.g.,
CopyOnWriteArrayList, ConcurrentHashMap).

Q. What is the purpose of IdentityHashMap? How does it differ from HashMap in


terms of key equality, and when is it useful?
IdentityHashMap is a special Map implementation in Java where keys are compared
using reference equality (==) rather than object equality as in HashMap (which
uses .equals() for comparison).
HashMap: Two keys are considered equal if their .equals() method returns true.
IdentityHashMap: Keys are only considered equal if they are the exact same
object in memory (same reference).
When is it useful?
IdentityHashMap is useful for scenarios where you need to distinguish keys
based on their identity, not their contents—such as object caches, tracking
proxy objects, serialization frameworks, or mapping metadata to specific object
instances.

Answer:
Example:
Answer:
Java
Map<String, String> hashMap = new HashMap<>();
[Link](new String("a"), "1");
[Link](new String("a"), "2"); // overrides previous entry
Map<String, String> identityMap = new IdentityHashMap<>();
[Link](new String("a"), "1");
[Link](new String("a"), "2"); // both entries remain, since keys are
different objects

EXCEPTION HANDLING
Answer:
Next Question (Advanced: Exceptions): What is the difference between checked and unchecked
exceptions in Java? Give examples of each, and explain why we use checked exceptions.
Answer:
Checked Exceptions:
Answer:
Must be handled (caught or declared) in code.
Answer:
Checked by the compiler at compile time.
Answer:
Examples:
Answer:
IOException
Answer:
SQLException
Answer:
FileNotFoundException
Answer:
Purpose: Enforce error handling for operations that may fail in normal circumstances (file IO, database
access).
Answer:
Java
try {
FileReader f = new FileReader("[Link]"); // may throw FileNotFoundException
} catch (FileNotFoundException e) {

Answer:
Unchecked Exceptions:
Answer:
Not checked at compile time.
Answer:
Usually indicate programming errors (logic mistakes).
Answer:
Examples:
Answer:
ArithmeticException (divide by zero)
Answer:
NullPointerException
Answer:
ArrayIndexOutOfBoundsException
Answer:
No compile-time requirement to handle them.
int a = 10 / 0; // throws ArithmeticException at runtime

Q. Why use checked exceptions?


Answer:
Enforces handling errors that are likely during normal program operations.
Answer:
Provides more robust/error-resilient programs.
Answer:
What are generics in Java? Why are they used, and how do they improve type safety? Provide a short
code example.
Answer:
Generics:
Answer:
Definition: Generics allow classes, interfaces, and methods to operate on a specified type
(parameterized types) without sacrificing type safety.
Answer:
Why use:
Answer:
Type safety: Ensures only objects of the specified type can be added.
Answer:
No need for casting: Reduces runtime errors, makes code easier to read.
Answer:
Code Example:
Answer:
Java
FileReader f = new FileReader("[Link]"); // may throw FileNotFoundException
} catch (FileNotFoundException e) {

Answer:
Does not return a value or throw checked exceptions.
Answer:
Represents a task and returns a result (or throws exception).
Answer:
Method:
Answer:
Java
V call() throws Exception;

Answer:
Used with classes like ExecutorService, Future.
Answer:
Example
Answer:
Java
Answer:
4. Checked vs Unchecked Exceptions
Answer:
Checked: Must be handled/declared. Example: IOException, SQLException
Unchecked: Runtime errors; not declared.
Example: NullPointerException, RuntimeException

Answer:
5. String Pool
Answer:
The Java String Pool is a special memory area for Strings.
Answer:
It reduces memory usage by reusing identical String literals.
Answer:
6. Reverse a String Without Built-in Methods
Answer:
Java
String str = "hello";
char[] arr = [Link]();
for(int i = 0, j = [Link]-1; i < j; i++, j--) {
char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
}
String reversed = new String(arr);

Answer:
7. String vs StringBuilder vs StringBuffer
Answer:
String: Immutable, slow for heavy edits.
Answer:
20. final vs finally vs finalize
Answer:
final: Prevents modification (variables, methods, classes).
Answer:
finally: Code block executed after try/catch.
Answer:
finalize: Method called before GC (deprecated/not recommended).
Answer:
Runnable: No return value, cannot throw checked exceptions.
Answer:
Callable: Returns value, can throw checked.
Answer:
Exceptions Quest

Q. What is an Exception? (Absolute Basics)


Answer:
An Exception is an unexpected event that stops the normal flow of a program.
Answer:
Examples:
Answer:
Divide by zero
Answer:
File not found
Answer:
Database connection failed
Answer:
Null reference
Answer:
Wrong input
Answer:
Checked vs Unchecked Exceptions
Answer:
Checked Exceptions (Compile-Time Exceptions)
Answer:
These are the exceptions that the compiler checks at compile-time.
If you don’t handle them, your code won’t compile.
Answer:
Because these are exceptions that can be predicted and should be handled.
Answer:
📌 Examples
Answer:
IOException
Answer:
SQLException
Answer:
ClassNotFoundException
Answer:
FileNotFoundException
Answer:
Unchecked Exceptions (Runtime Exceptions)
Answer:
📌 Definition
Answer:
Exceptions that occur during runtime, and the compiler does NOT force you to handle them.
Answer:
📌 Examples
Answer:
ArithmeticException
Answer:
NullPointerException
Answer:
ArrayIndexOutOfBoundsException
Answer:
NumberFormatExceptioncompiles fine but fails while running.
Answer:
throw vs throws
Answer:
throw
Answer:
Used to manually throw exception.
Answer:
throws
Answer:
Used in method signature to declare exceptions.
Answer:
Common Exceptions (Must Know)
Answer:
Unchecked
Answer:
NullPointerException
Answer:
ArithmeticException
Answer:
ArrayIndexOutOfBoundsException
Answer:
IllegalArgumentException
Answer:
Checked
Answer:
IOException
Answer:
FileNotFoundException
Answer:
SQLException
Answer:
finally Block
Answer:
📌 Purpose
Answer:
A block that always executes,
even if:
Answer:
exception occurs
Answer:
no exception occurs
Answer:
return statement inside try/catch
Answer:
throw Keyword
Answer:
📌 Purpose
Answer:
Used to manually throw an exception from your code.

Q. 📌 When used?
Answer:
When you want to create your own custom validation
Answer:
When you want to throw an exception deliberately
Answer:
Program stops after throw
We create the exception object manually
Answer:
throws Keyword
Answer:
📌 Purpose
Answer:
Used in method signature to declare that method may throw exceptions.
Answer:
📌 Means:
Answer:
“I am not handling the exception here, someone else should handle it.”

Q. Why Do We Need Custom Exceptions?


Answer:
Custom exceptions are used when:
Answer:
You want to throw meaningful, business-related errors.
Answer:
Built-in exceptions don’t represent your scenario.
Answer:
You want clean, readable error handling.
Answer:
✔ Example in real life
Answer:
"InvalidAgeException"
Answer:
"InsufficientBalanceException"
Answer:
"InvalidEmailFormatException"
Answer:
These tell exactly what the problem is — unlike generic exceptions.

Q. What is try-with-resources?
Answer:
It is a special form of try block that automatically closes resources after use.
Answer:
✔ A resource means:
Answer:
Any object that must be closed after using it, like:
Answer:
FileReader
Answer:
BufferedReader
Answer:
try-with-resources Syntax
Answer:
Java
try (Resource res = new Resource()) {

Answer:
// use resource
}

Answer:
// resource auto-closed
Answer:
✔ No need for finally
Answer:
✔ No manual close()
Answer:
✔ No resource leak
Q. What is Exception Propagation?
Answer:
Exception Propagation means:
Answer:
If a method does not handle an exception, it is passed to the caller.
And if the caller also doesn’t handle → passed further → up the call stack.

Q. Exception Chaining?
Answer:
Exception Chaining means one exception causes another exception, and Java allows you to link them.
Answer:
It helps you see the root cause of a failure.

Q. 📌 Why needed?
Answer:
When a low-level method throws an exception, a higher-level method might want to throw a different,
more meaningful exception — without losing the original cause.
Answer:
Consider:
Answer:
Database connection fails → SQLException
Answer:
Service layer catches it and throws new exception like:
"Unable to fetch user"
Answer:
But we still want to keep original cause (SQLException).
Answer:
This is done by chaining:
Answer:
Java
throw new ServiceException("Unable to fetch user", causeException);

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


Answer:
Answer:
Answer:
Checked exceptions → Checked at compile-time (e.g., IOException).
Answer:
Unchecked exceptions → Occur at runtime (e.g., NullPointerException).
Compiler does not force handling unchecked exceptions.

Q. ✅ Q2. Can finally block be skipped?


Answer:
Answer:
Yes, in rare cases:
Answer:
[Link]()
Answer:
Otherwise, finally always executes.

Q. ✅ Q3. What is exception propagation?


Answer:
Answer:
If a method does not handle an exception, it is thrown to its caller.
Unchecked exceptions propagate automatically.
Checked exceptions must be declared using throws.

Q. ✅ Q4. What is the difference between throw and throws?


Answer:
throw → Used to manually throw exception inside method.
throws → Used in method signature to declare exceptions.

Q. ✅ Q5. Can we use multiple catch blocks?


Answer:
Answer:
Yes.
From Java 7 onward, you can also use multi-catch:
Answer:
Java
Answer:
catch(IOException | SQLException e)
Answer:
Show more lines

Q. ✅ Q6. What happens when both try and finally have return statements?
Answer:
Answer:
Return in finally overrides return in try.

Q. ✅ Q7. What is exception chaining?


Answer:
Answer:
Linking one exception as the cause of another:
Answer:
Java
throw new RuntimeException("Error", cause);

Answer:
Show more lines
Answer:
Used to keep the root cause.

Q. ✅ Q8. What are suppressed exceptions?


Answer:
Answer:
In try-with-resources, if both try block and close() throw exceptions,
Exception from close() becomes suppressed, not lost.

Q. ✅ Q9. Difference between masked & suppressed exceptions?


Masked → Happens in try-finally; original exception is lost.
Suppressed → Happens in try-with-resources; original exception is kept, cleanup
exception stored as suppressed.

Q. ✅ Q10. Can a constructor throw exceptions?


Answer:
Answer:
Yes.
Constructors can throw checked or unchecked exceptions.

Q. ✅ Q11. Can overriding method throw new exceptions?


Answer:
Rules:
✔ Can throw narrower checked exceptions
✔ Can throw any unchecked exception
❌ Cannot throw broader or new checked exceptions

Q. ✅ Q12. What happens if an exception occurs in a static block?


Answer:
Unchecked exception → allowed, program fails at class loading.
Checked exception → NOT allowed (compile-time error).

Q. ✅ Q13. Why should we avoid catching Exception or Throwable?


Answer:
Because:
Answer:
It hides specific errors
Answer:
It may catch Error (OutOfMemoryError)
Answer:
Makes debugging harder
Answer:
Always catch specific exceptions.

Q. ✅ Q14. Why should we avoid empty catch blocks?


Answer:
Because:
Answer:
The exception is swallowed
Answer:
No message
Answer:
No debugging information
Answer:
Application silently fails

Q. ✅ Q15. What is best practice for closing resources?


Answer:
Use try-with-resources:
Answer:
Java
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
}

Answer:
Show more lines
Answer:
Automatic cleanup → no leaks → clean code.
Answer:
Real Interview Questions Covered

Q. Difference between checked & unchecked exception


Answer:
throw vs throws
Answer:
Exception Propagation
Answer:
try-with-resources & suppressed exceptions
Answer:
Custom exceptions
Answer:
finally behavior
Answer:
Masked vs suppressed

Q. Why avoid catching Exception/Throwable?


Answer:
Multiple catch / multi-catch
Answer:
Exception chaining

Q. Why not use exceptions for flow?


Answer:
Overriding & exception rules

Q. What happens in static block?

Q. What if exception in constructor?

Q. What if exception before try block?


Answer:
Collection Quest
[Link]("new"); // Throws ConcurrentModificationException
}
[Link](); // No exception
}

MULTITHREADING & CONCURRENCY


Q. Explain the difference between synchronized methods and synchronized blocks
in Java. Why would you use one over the other? Provide an example.
Answer:
Synchronized Method:
Answer:
When you declare a method as synchronized, only one thread can execute it at a time for a given object
(locks the object’s monitor).
Answer:
All code inside the method is synchronized.
Answer:
Java
public synchronized void increment() {
counter++;
}
Answer:
Equivalent to locking on this for instance methods.
Answer:
Synchronized Block:
Answer:
You can synchronize only a portion of code, and explicitly specify the object to lock.
Answer:
Java
public void increment() {
synchronized(this) {
counter++;
}
}

Answer:
or:
Answer:
Java
synchronized(someOtherObject) {

Answer:
// code
}
More flexible; can reduce time spent holding the lock, improving concurrency.

Q. Why choose one over the other?


Synchronized block: When you don’t need to lock the whole method, just some
code; or to lock on a different object.

Answer:
Synchronized method: Simpler, but less control.
Answer:
Heap is larger and shared across all threads.

Q. What is the Singleton pattern in Java? Why is it used, and how would you
implement a thread-safe Singleton? Give example code and reasoning.
Answer:
Thread-Safe Implementation:
Answer:
Example (using synchronized for thread safety):
Answer:
Java
public static synchronized Singleton getInstance() {
if (instance == null) {
private static volatile Singleton instance;
synchronized([Link]) {
if (instance == null) {

Answer:
Runnable (single method: run())
Answer:
Comparator<T> (single method: compare(T t1, T t2))
Answer:
Runnable:
Answer:
Represents a task to be run in a thread.
Answer:
Method:
Answer:
Java
void run();

Answer:
Callable:
Callable<Integer> task = () -> {
return 42;
};
ExecutorService service = [Link]();
Future<Integer> future = [Link](task);
Integer result = [Link](); // result = 42

Answer:
Deadlock
Answer:
In Java multithreading, a deadlock is a situation where two or more threads are permanently
blocked because each thread is waiting for a resource (lock) that another thread holds, and none of
them can proceed.
Answer:
How Deadlock Happens
Answer:
Deadlock typically occurs when:
Answer:
Multiple threads need multiple shared resources.
Answer:
Each thread acquires a lock on one resource and waits for another resource that is already locked by
another thread.
Answer:
This creates a circular wait where no thread can continue.
Answer:
StringBuilder: Mutable, fast, not thread-safe.
Answer:
StringBuffer: Mutable, thread-safe (synchronized), used when safety is needed.
Answer:
8. Multithreading: Thread vs Runnable
By extending Thread, you override the run() method; use if you need a new
thread type.

Answer:
By implementing Runnable, you share resources more easily and use thread pooling.
Answer:
Prefer Runnable for greater flexibility and design elegance.
Answer:
9. synchronized Keyword
Answer:
Ensures only one thread executes a method/block at a time, preventing race conditions and data
inconsistency.
Answer:
10. volatile Keyword
Answer:
Guarantees visibility of changes to a variable across threads, but doesn’t guarantee atomicity.
Useful for simple flags; not as robust as synchronized for complex atomicity.

Answer:
Hashtable: Thread-safe, legacy, does not allow nulls.
Answer:
Multiple threads can read/write efficiently without blocking each other.
Answer:
19. Singleton (Thread-safe) Example
Answer:
Java
private static volatile Singleton instance;
synchronized([Link]) {

Answer:
21. Deadlocks
Answer:
Deadlock: Two/more threads wait forever for each other’s locks.
Avoid deadlocks: Lock resources in consistent order, use timeouts, or avoid
shared locks.
Answer:
Makes Strings thread-safe and useful as map keys.
Answer:
Implemented by marking class/final fields and no setters.
Answer:
25. Callable vs Runnable with Future
Answer:
Use Future to get result from Callable via ExecutorService.
Answer:
26. Producer-Consumer with wait()/notify()
Use synchronized blocks; producer calls notify(), consumer calls wait().

Answer:
Both operate on shared object/queue.
Answer:
27. Static vs Dynamic Binding
Answer:
Static (compile-time): Overloading (method resolution via parameter types).
Answer:
Dynamic (run-time): Overriding (method resolution via object type).
Answer:
Thread death
Answer:
Use when you want thread-safe, lock-free reads with <i>rare</i> mutations.

JAVA 8 FEATURES
Answer:
What are Java Streams? How do you use them for processing collections? Provide a short example
(with a lambda).
Answer:
Java Streams, introduced in Java 8, provide a functional programming approach to process collections
of data. Streams support intermediate and terminal operations, enabling efficient and declarative data
processing.
Answer:
Streams in Java:
Answer:
Streams provide a declarative, pipeline way to process collections (like filtering, mapping, reducing),
often using lambda expressions.
Answer:
Once a stream is consumed (terminal operation like forEach, collect), it cannot be reused.
Answer:
Common stream operations: filter, map, reduce, collect.
Answer:
Example:
Answer:
Java
List<Integer> numbers = [Link](1, 2, 3, 4, 5);

Answer:
// Get squares of even numbers
List<Integer> squares = [Link]()

Answer:
.filter(n -> n % 2 == 0) // filter even numbers
Answer:
.map(n -> n * n) // map to squares
.collect([Link]()); // collect as List

Answer:
Why answer like this? Interviewers want evidence you know how Java Streams work, their advantages,
and basic code usage.

Q. Explain the concept of Functional Interfaces in Java. How do they relate to


lambdas? Give an example of defining and using a custom functional interface.
Answer:
Functional Interface:
Answer:
An interface with exactly one abstract method (can have default/static methods).
Answer:
Allows lambda expressions to implement that method concisely.
Answer:
Marked with @FunctionalInterface (optional but recommended for clarity).
Answer:
Example—Defining and Using Custom Functional Interface:
Java
Answer:
@FunctionalInterface
interface MyFunc {
int operate(int a, int b);
}

Answer:
// Using lambda expression:
MyFunc sum = (a, b) -> a + b;
[Link]([Link](5, 3)); // output: 8
Answer:
Relation to Lambdas:
Answer:
You can use a lambda expression anywhere a functional interface is expected, since Java knows which
single method to implement.
Answer:
Common Examples:
Answer:
Definition: Serialization is the process of converting an object into a byte stream so it can be saved to a
file, sent over a network, etc.
Answer:
Deserialization: The reverse process — converting a byte stream back into an object.
Requirement: The class must implement [Link].

Answer:
transient Keyword in Java
Answer:
Method References ( : : )
Answer:
Method references in Java provide a way to refer to methods or constructors directly by their names,
making the code more concise and readable. They are particularly useful for replacing simple lambda
expressions that call existing methods.
Answer:
30 BASIC Rerepeated Quest
Comparator: Custom ordering (defines compare in a separate class or via
lambda).

Answer:
17. Java Stream API: Intermediate vs Terminal Operations
Answer:
Intermediate: Transform stream (e.g. filter, map), lazy, don’t trigger processing.
Answer:
Terminal: Ends pipeline, triggers processing (e.g. collect, forEach).
Answer:
18. Abstract Classes vs Interfaces
Answer:
Abstract Class: Can have implemented methods and fields.
Interface: Only defines contracts; Java 8+ allows default/static methods.
Use abstract class for shared code; interface for common contract.

Answer:
FileInputStream
Answer:
Socket
Answer:
Connection
Answer:
PreparedStatement
Answer:
All these implement AutoCloseable.

JVM / MEMORY / GC
[Link]();
}

Q. Explain the difference between heap and stack memory in Java. What is stored
where, and how does garbage collection relate to this?
Answer:
Stack Memory:
Answer:
Used for method call frames, local variables, and primitive data.
Answer:
Every time a method is called, a stack frame is created with its local variables and arguments.
Answer:
Primitive data (like int, char) is stored directly in stack frames.
Answer:
Reference variables are stored in stack, actual objects on the heap.
Stack memory is smaller and managed by the JVM; grows/shrinks with method
calls/returns.

Answer:
Heap Memory:
Answer:
Used for storing all objects (created via new) and arrays.
Answer:
Variables in stack that reference objects actually point to their location in the heap.
Answer:
Garbage Collection:
Answer:
Automatic process in JVM that frees up heap memory by removing objects no longer referenced
("eligible for GC").
Stack memory is managed automatically with method calls/returns; heap is
managed with GC.

Answer:
Example:
Answer:
Java
try {
[Link]();
}
Ensures only one instance of a class exists in the JVM, and provides a global
point of access to that instance.

Q. Why Use It?


Answer:
Useful for resource management (e.g., database connection pools, logging), where only one instance
should manage the resource.

Q. Explain what happens during Java class loading. What are the different class
loaders, and why might you use a custom class loader?
Answer:
Java Class Loading Process:
Loading: The class file is located and brought into memory by a class loader.

Answer:
Linking: Verifies bytecode, prepares static fields/methods, resolves references.
Answer:
Initialization: Static initializers and static variables are executed.
Answer:
Types of ClassLoaders:
Answer:
Bootstrap ClassLoader: Loads core Java classes ([Link]). Part of the JVM.
Answer:
Extension (Platform) ClassLoader: Loads JDK extensions present in the ext directory.
Answer:
System/Application ClassLoader: Loads application classes in the classpath.
Answer:
Custom ClassLoader: User-defined for specialized loading (e.g., loading encrypted classes, plugins, or
classes from networks/databases).

Q. Why Use a Custom ClassLoader?


Load classes in a special way (e.g., from encrypted files, over a network, or
for class reloading in frameworks).

Answer:
Sandbox untrusted code.
Answer:
Example:
Answer:
Java
ClassLoader cl = [Link]();
Class<?> clazz = [Link]("[Link]");

Q. What are strong, weak, soft, and phantom references in Java? When would you
use each?
Answer:
Types of References ([Link]):
Answer:
Strong Reference:
The ordinary reference (e.g., Object obj = new Object();).

Answer:
GC does not reclaim unless reference is nullified.
Answer:
Usage: Normal objects in application code.
Answer:
Soft Reference:
SoftReference<Object> ref = new SoftReference<>(obj);

Answer:
Cleared only when JVM is low on memory.
Answer:
Usage: Caches that can be purged in memory shortage (e.g. image caches).
Answer:
Weak Reference:
WeakReference<Object> ref = new WeakReference<>(obj);

Answer:
Cleared as soon as the only references are weak (even if not low on memory).

Q. What is a memory leak in Java if there is garbage collection? Can you describe a
scenario that causes a leak, and how would you detect and prevent it?
Answer:
A memory leak in Java occurs when objects that are no longer needed by the application remain in
memory because the garbage collector cannot remove them.
Answer:
Memory Leak in Java:
Answer:
Occurs when unused objects are still referenced, so they can't be garbage collected, causing memory
usage to grow.
Answer:
Example Scenario:
Answer:
Static collections:
Answer:
Java
Answer:
1. JVM, JRE, and JDK
JVM (Java Virtual Machine): Runs compiled Java bytecode; platform-independent;
manages memory and execution.

Answer:
JRE (Java Runtime Environment): JVM plus core libraries—enough to run Java applications.
Answer:
JDK (Java Development Kit): JRE plus compilers, tools (javac etc)—used to develop Java programs.
Answer:
2. OOP Principles in Java
Answer:
3. Garbage Collection in Java
Answer:
Works: JVM automatically frees unused objects.
Answer:
Minor GC: Collects young generation (short-lived).
Answer:
Major (Old/Full) GC: Collects old generation (long-lived).
Answer:
Full GC: Collects both young and old generations.
Answer:
15. Memory Leaks & Detection
Answer:
Leaks can occur if references are accidentally kept to unused objects.
Answer:
Use tools like VisualVM, Eclipse MAT, or profilers to find leaks.
Answer:
29. Stack vs Queue
Stack: Last-in-first-out; use Stack or Deque.

Answer:
Eventually, if no one handles it, Java Runtime (JVM) handles it → program stops.
Answer:
JVM crash
Answer:
LIFO (Stack)
Answer:
List operations
Answer:
Each element is stored in a Node object:
class Node<E> {
E item;
Node<E> next;
Node<E> prev;
}

Answer:
So each node has:
Answer:
item → value
Answer:
next → pointer to next node
Answer:
prev → pointer to previous node
Answer:
This is how nodes look:
Answer:
null ← [A] ↔ [B] ↔ [C] → null

ADVANCED JAVA
Q. What is Singleton Pattern?
public class Singleton {
private static Singleton instance;
private Singleton() { } // private constructor
instance = new Singleton();
}
return instance;
}
}
}
}

Answer:
Better Approach (using Double-Checked Locking):
Answer:
Java
public class Singleton {
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

Answer:
Or (Eager Initialization):
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() { return instance; }
}

Q. What is Java Reflection? What are some use cases and limitations? Provide a code
snippet that gets all methods of a class at runtime.

Q. What is Java Reflection? What are some use cases and limitations? Provide a code
snippet that gets all methods of a class at runtime.
Answer:
Java Reflection:
Answer:
Allows programs to examine or modify the runtime properties (methods, fields, constructors, etc.) of
classes.
Answer:
Enables dynamic code, such as creating objects, invoking methods, or modifying fields, without
knowing their names at compile time.
Answer:
Common Use Cases:
Answer:
Frameworks (Spring, Hibernate) for dependency injection and serialization
Answer:
Testing tools for mocking/stubbing
Answer:
Building generic libraries (e.g., JSON serialization)
Accessing private fields/methods in special cases
Answer:
Limitations:
Answer:
Performance overhead (reflection is slower than direct calls)
Answer:
Security risks (can bypass access controls)
Answer:
Loss of compile-time type checks
Answer:
Example—listing all methods of a class:
Answer:
Example—listing all methods of a class:
Answer:
Java
Class<?> clazz = [Link];
Method[] methods = [Link]();
for (Method m : methods) {
[Link]([Link]());
}

Answer:
Serialization in Java
Answer:
Definition: The transient keyword is used to exclude a field from serialization.
Answer:
Use Case: Prevents sensitive or unnecessary data from being stored (e.g., passwords, temporary
values).
class Singleton {
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
if(instance == null) instance = new Singleton();
}
}
return instance;
}
}
28. Serialization; serialVersionUID

Answer:
Makes object persistable/transmittable.
Answer:
serialVersionUID ensures version compatibility.
Define in class implementing Serializable.

Answer:
30. Reflection
Answer:
Allows runtime inspection/modification of classes and members.
Answer:
Used in frameworks, DI, serialization.
Answer:
Limitations: Slower, can break security, harder to debug.

You might also like