Java Interview Handbook Styled
Java Interview Handbook Styled
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. 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"
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.
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.
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.
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. 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)
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).
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).
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
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. 📌 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. 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. ✅ Q6. What happens when both try and finally have return statements?
Answer:
Answer:
Return in finally overrides return in try.
Answer:
Show more lines
Answer:
Used to keep the root cause.
Answer:
Show more lines
Answer:
Automatic cleanup → no leaks → clean code.
Answer:
Real Interview Questions Covered
Answer:
or:
Answer:
Java
synchronized(someOtherObject) {
Answer:
// code
}
More flexible; can reduce time spent holding the lock, improving concurrency.
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.
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. 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).
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.