1. Why is Java not 100% object-oriented?
Java is not considered 100% object-oriented because it uses primitive data types like:
int, char, float, boolean, double
These are not objects. In pure object-oriented languages, everything should be an object.
Java introduced wrapper classes like below to provide object representation for primitives.
Integer, Character, Float -> to provide object representation for primitives.
Example: int a = 10; Here a is not an object.
2. Why are pointers not used in Java?
Java does not support pointers directly because of:
1. Security: Pointers can access any memory location and may cause:
memory corruption, data leakage, hacking issues
2. Simplicity: Pointers make programming complex.
3. Automatic Memory Management: Java uses JVM and Garbage Collector. So
programmers do not need manual memory handling.
3. What is JIT Compiler in Java?
JIT stands for Just-In-Time [Link] is a part of JVM.
Working:
1. Java source code → compiled into bytecode
2. JVM interprets bytecode
3. Frequently used code is converted into machine code by JIT
4. Execution becomes faster
Benefit: Improves performance and Reduces interpretation time
4. Why is String immutable in Java?
Immutable means: once created, value cannot be changed.
Example: Original string remains same.
String s = "Hello";
[Link]("World");
Reasons:
1. Security
Strings are used in: database URLs, usernames/passwords, network connections
Immutability prevents modification.
2. String Pool Optimization
Java reuses string objects to save memory.
3. Thread Safety
Immutable objects are automatically thread-safe.
4. Hashcode Caching
Useful in collections like: HashMap and HashSet
5. What is a Marker Interface?
A marker interface is an interface with no methods and no [Link] is used to provide special
information to JVM or compiler. Example: Serializable, Cloneable, Remote
interface Test { } Purpose: It “marks” a class with special behavior.
6. Can you override a private or static method in Java?
Private Method → NO
Private methods are accessible only inside the same class. They are not inherited, so
overriding is impossible.
Static Method → NO
Static methods belong to class, not object. They can be method hidden, not overridden.
class A { static void show() {
[Link]("A"); } }
class B extends A { static void show() {
[Link]("B"); } } This is method hiding.
7. Does finally always execute in Java?
YES, finally block executes whether: exception occurs or not and exception handled or not
try {
int a = 10/0;
}
finally {
[Link]("Finally executed");
}
Cases where finally may NOT execute:
1. [Link](): [Link](0); JVM stops immediately.
2. JVM crash
3. Power failure
8. What methods does Object class have?
Method Purpose
toString() Converts object to string
equals() Compares objects
hashCode() Returns hash value
clone() Creates object copy
getClass() Returns class information
finalize() Called before garbage collection
wait() Thread waiting
notify() Wakes one thread
Wakes all threads
notifyAll()
9. How can you make a class immutable?
1. Declare class as final
final class Employee, Prevents inheritance.
2. Make fields private and final
private final int id;
3. No setter methods
Only getters allowed.
4. Initialize values using constructor
5. Return copies for mutable objects
Date, Array, List
final class Employee {
private final int id;
public Employee(int id) {
[Link] = id;
}
public int getId() {
return id; } }
10. What is Singleton class in Java and how can we make a class singleton?
Singleton means: only one object of the class can be created.
Used in: Database connections, Logger, Configuration, Caching
Make constructor private->Create static object->Provide public static method
class Singleton {
private static Singleton obj = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return obj;
}}
Singleton s1 = [Link]();
Singleton s2 = [Link]();
Both refer to same object.
Advantages of Singleton
Saves memory
Controlled access
Global access point
Java Collection Framework (No Repetition Version)
Why Collections?
Arrays have limitations:
Fixed size
Difficult insertion/deletion
Fewer utility methods
Collections provide:
Dynamic size
Built-in methods
Better data manipulation
Collection Hierarchy
Iterable
|
Collection
|
--------------------------------
| | | |
List Set Queue Deque
Separate hierarchy:
Map
|
--------------------------------
| | |
HashMap LinkedHashMap TreeMap
|
Hashtable
Important: Map is part of the Collection Framework but does NOT extend Collection.
Iterable Interface- Top-most interface.
Method: iterator()
Used in: for(Integer i : list)
Collection Interface- Root interface of collection hierarchy.
Common methods:
add()
remove()
size()
clear()
contains()
isEmpty()
List Interface
Features
Ordered
Allows duplicates
Maintains insertion order
Index-based access
Example: [10,20,10,30]
ArrayList- Uses dynamic array.
Features
Fast access
Slow insertion/deletion in middle
Allows duplicates
Maintains order
ArrayList<String> list = new ArrayList<>();
Complexity
Operation Time
Access O(1)
Insert End O(1)
Insert Middle O(n)
Delete Middle O(n)
Use when:
More searching
Less modification
LinkedList- Uses doubly linked list.
Features
Fast insertion/deletion
Slow access
Maintains order
Allows duplicates
LinkedList<Integer> list = new LinkedList<>();
Complexity
Operation Time
Access O(n)
Insert/Delete O(1)
Use when: Frequent insertion/deletion
ArrayList vs LinkedList
Feature ArrayList LinkedList
Structure Dynamic Array Doubly Linked List
Access Fast Slow
Insert/Delete Slow Fast
Memory Less More
Vector
Synchronized
Thread-safe
Slower than ArrayList
Vector<Integer> v = new Vector<>();
Stack- LIFO (Last In First Out)
Methods:
push()
pop()
peek()
Stack<Integer> s = new Stack<>();
Set Interface
Features
No duplicates
Not index-based
Example:[10,20,30]
Uses:
hashCode()
equals()
for duplicate checking.
HashSet
No duplicates
Unordered
Fastest Set
HashSet<Integer> set = new HashSet<>();
Complexity:
Operation Time
Add O(1)
Remove O(1)
Search O(1)
LinkedHashSet
No duplicates
Maintains insertion order
LinkedHashSet<Integer> set = new LinkedHashSet<>();
Uses:
Hash Table
Linked List
TreeSet
Sorted order
No duplicates
TreeSet<Integer> set = new TreeSet<>();
Uses: Red-Black Tree
Complexity:
Operation Time
Add O(log n)
Operation Time
Remove O(log n)
Search O(log n)
HashSet vs LinkedHashSet vs TreeSet
Feature HashSet LinkedHashSet TreeSet
Order No Insertion Order Sorted
Duplicate No No No
Performance Fastest Medium Slower
Queue Interface
FIFO (First In First Out)
Used in:
Scheduling
Messaging
Printer Queue
Methods:
offer()
poll()
peek()
PriorityQueue
Priority based
Default Min Heap
Insertion order not maintained
PriorityQueue<Integer> pq = new PriorityQueue<>();
Deque Interface
Double-ended queue.
Insert/Delete from:
Front
Rear
ArrayDeque<Integer> dq = new ArrayDeque<>();
ArrayDeque
Can act as:
Queue
Stack
Preferred over Stack.
Map Interface
Stores:
key -> value
Example:
101 -> "John"
Features
Keys unique
Values can duplicate
HashMap
Features
Fastest Map
No order
One null key allowed
HashMap<Integer,String> map = new HashMap<>();
Complexity
Operation Time
Put O(1)
Get O(1)
Remove O(1)
Internal Working
Key
↓
hashCode()
↓
Bucket Index
↓
Store Value
Important
Default Capacity = 16
Load Factor = 0.75
Collision handled using Linked List
Java 8 converts long chains to Red-Black Tree
LinkedHashMap
Maintains insertion order
Uses:
Hash Table
Linked List
TreeMap
Sorted keys
Red-Black Tree
Complexity:
O(log n)
Hashtable
Thread-safe
No null key/value
HashMap vs Hashtable
Feature HashMap Hashtable
Thread Safe No Yes
Null Key Allowed Not Allowed
Performance Faster Slower
Comparable vs Comparator
Comparable
Default sorting.
Method:
compareTo()
Comparator
Custom sorting.
Method:
compare()
Iterator vs ListIterator
Feature Iterator ListIterator
Direction Forward Both
Used For All Collections List Only
Modify Elements Limited Yes
Fail-Fast vs Fail-Safe
Fail-Fast
Throws:
ConcurrentModificationException
Examples:
ArrayList
HashMap
HashSet
Works on original collection.
Fail-Safe
Works on copy/clone.
Examples:
ConcurrentHashMap
CopyOnWriteArrayList
No exception during modification.
BlockingQueue
Package:
[Link]
Thread-safe queue.
Methods:
put()
take()
offer()
poll()
Implementations:
ArrayBlockingQueue
LinkedBlockingQueue
PriorityBlockingQueue
Used in Producer-Consumer problems.
Synchronized Collection vs Concurrent Collection
Feature Synchronized Concurrent
Locking Entire Collection Fine-grained
Performance Slower Faster
Example Vector ConcurrentHashMap
Most Asked Interview Questions
Why Map doesn't extend Collection?
Collection stores single objects.
add(E e)
Map stores key-value pairs.
put(K,V)
Hence Map cannot extend Collection.
Which collection allows duplicates?
List
Which collection stores unique values?
Set
Which collection maintains insertion order?
ArrayList
LinkedHashSet
LinkedHashMap
Which collection automatically sorts data?
TreeSet
TreeMap
Best Collection Selection
Requirement Collection
Fast Access ArrayList
Frequent Insert/Delete LinkedList
Unique Elements HashSet
Sorted Elements TreeSet
Key-Value Storage HashMap
Thread-Safe List Vector
LIFO Stack
FIFO Queue