Day 1: Java Collections Framework
🧠 1. What is Java Collections Framework?
A Collection is a group of objects (like a container). The Java Collections Framework (JCF)
provides:
● Interfaces (like List, Set, Map)
● Implementations (like ArrayList, HashSet, HashMap)
● Algorithms (like sorting and searching)
It was introduced in Java 1.2 to unify data structure handling.
📜 2. Core Interfaces in JCF
Here's the hierarchy diagram:
Iterable
|
Collection
________/ \________
| |
List Set Map (separate hierarchy)
/ \ / \ / \
ArrayList LinkedList HashSet TreeSet HashMap TreeMap
Interface Description Allows Maintains Order?
Duplicates?
List Ordered collection Yes Yes
Set Unique elements No HashSet - No, LinkedHashSet -
Yes
Map Key-value pairs Unique keys only Depends on implementation
🧰 3. Difference Between Collection and Collections
Feature Collection Collections
Type Interface Utility class
Package java.util.Collection java.util.Collections
Purpose Represents a group of Provides utility methods like sort(),
elements shuffle()
Example List, Set, Queue Collections.sort(list)
💡 4. Why Collections Over Arrays?
Feature Array Collection
Size Fixed Dynamic
Type Homogeneous Can be heterogeneous
Feature Limited operations Rich API (sorting, searching, etc.)
s
✏ 5. Examples
// List Example
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names); // Output: [Alice, Bob]
// Set Example
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(10); // Duplicate ignored
System.out.println(numbers); // Output: [10]
// Map Example
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
System.out.println(scores); // Output: {Alice=90, Bob=85}
💻 6. Day 1 Coding Exercises
Try solving these:
Q1. Add 5 names to an ArrayList and print them.
Q2. Add 5 numbers to a HashSet (including duplicates) and print unique numbers.
Q3. Store 3 names with marks in a HashMap and print all key-value pairs.
Q4. Convert an ArrayList to an array and vice versa.
Day 1 Coding Exercise Solutions
✅ Q1. Add 5 names to an ArrayList and print them
import java.util.ArrayList;
import java.util.List;
public class NameList {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Diana");
names.add("Eve");
System.out.println("Names in the list: " + names);
}
}
✅ Q2. Add 5 numbers to a HashSet (including duplicates) and print
unique numbers
import java.util.HashSet;
import java.util.Set;
public class UniqueNumbers {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(10); // duplicate
numbers.add(30);
numbers.add(20); // duplicate
System.out.println("Unique numbers: " + numbers);
}
}
✅ Q3. Store 3 names with marks in a HashMap and print all key-value pairs
import java.util.HashMap;
import java.util.Map;
public class StudentScores {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " -> " +
entry.getValue());
}
}
}
✅ Q4. Convert an ArrayList to an array and vice versa
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConvertArrayList {
public static void main(String[] args) {
// ArrayList to Array
List<String> list = new ArrayList<>();
list.add("Red");
list.add("Green");
list.add("Blue");
String[] array = list.toArray(new String[0]);
System.out.println("Array: " + Arrays.toString(array));
// Array to ArrayList
String[] colors = {"Yellow", "Pink", "Black"};
List<String> newList = new ArrayList<>(Arrays.asList(colors));
System.out.println("ArrayList: " + newList);
}
}
Day 2: List Interface in Java
🔹 1. What is the List Interface?
The List interface is an ordered collection (also called a sequence). It allows:
● Duplicates
● Positional access using index
● Insertion and removal at specific positions
📊 List Implementations Comparison:
Feature ArrayList LinkedList Vector Stack
Order Maintains Maintains order Maintains order LIFO (Last In First
order Out)
Duplicates Allowed Allowed Allowed Allowed
Thread-safe No No Yes Yes (extends Vector)
Performanc Fast in get/set Fast in Slower due to Slower but thread-
e insert/delete sync safe
Growable? Yes Yes Yes Yes
📌 2. ArrayList: Growable Array
🔧 Internal Working:
● Backed by an array.
● Increases size by 50% when full (Java 8+).
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits.get(0)); // Output: Apple
📌 3. LinkedList: Doubly Linked List
● Every node stores data + pointers to prev and next node.
● Efficient for insertion/deletion at head/middle.
List<String> cities = new LinkedList<>();
cities.add("Delhi");
cities.add("Mumbai");
cities.add(1, "Bangalore"); // Insert at index
System.out.println(cities);
📌 4. Vector: Thread-safe ArrayList
● Similar to ArrayList, but all methods are synchronized.
● Slower due to overhead.
Vector<Integer> nums = new Vector<>();
nums.add(1);
nums.add(2);
System.out.println(nums);
📌 5. Stack: LIFO (Last-In-First-Out)
● Subclass of Vector
● Methods: push(), pop(), peek(), search()
Stack<String> stack = new Stack<>();
stack.push("Book 1");
stack.push("Book 2");
System.out.println(stack.pop()); // Book 2
🎯 6. Interview Questions
1. ArrayList vs LinkedList
○ Random access: ArrayList , LinkedList
○ Insert/delete in middle: LinkedList
2. Why is Vector slower than ArrayList?
○ Because of synchronization (thread-safe).
3. When to use Stack over other Lists?
○ When LIFO structure is required (e.g., undo functionality, backtracking).
Can you make ArrayList thread-safe?
List<Integer> syncList = Collections.synchronizedList(new
ArrayList<>());
4.
📘 7. Diagrams
📌 ArrayList
[Index] 0 1 2
[A] [B] [C]
📌 LinkedList
NULL <- [A] <-> [B] <-> [C] -> NULL
📌 Stack
Top -> [C]
[B]
[A]
💻 8. Day 2 Coding Exercises
Q1. Create an ArrayList of integers and reverse it.
Q2. Add 5 cities to a LinkedList, insert one at position 2.
Q3. Push 3 strings to a Stack and pop the top.
Q4. Create a Vector, add elements, and iterate using Enumeration.
Day 2 Coding Exercise Solutions
✅ Q1. Create an ArrayList of integers and reverse it
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReverseArrayList {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
System.out.println("Original List: " + numbers);
Collections.reverse(numbers);
System.out.println("Reversed List: " + numbers);
}
}
✅ Q2. Add 5 cities to a LinkedList, insert one at position 2
import java.util.LinkedList;
public class LinkedListCities {
public static void main(String[] args) {
LinkedList<String> cities = new LinkedList<>();
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Chennai");
cities.add("Kolkata");
cities.add("Pune");
cities.add(2, "Bangalore"); // Inserting at index 2
System.out.println("Cities List: " + cities);
}
}
✅ Q3. Push 3 strings to a Stack and pop the top
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> books = new Stack<>();
books.push("Java");
books.push("Python");
books.push("C++");
System.out.println("Stack before pop: " + books);
String topBook = books.pop();
System.out.println("Popped: " + topBook);
System.out.println("Stack after pop: " + books);
}
}
✅ Q4. Create a Vector, add elements, and iterate using Enumeration
import java.util.Enumeration;
import java.util.Vector;
public class VectorEnumeration {
public static void main(String[] args) {
Vector<String> animals = new Vector<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Elephant");
Enumeration<String> e = animals.elements();
System.out.println("Vector elements:");
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
}
Day 3: Java Set Interface – HashSet, LinkedHashSet,
TreeSet
🔹 1. What is a Set?
● A Set is a collection that does not allow duplicate elements.
● It does not guarantee order, unless you use a specific implementation.
● Part of the java.util package and extends the Collection interface.
📊 Set Implementations Comparison
Feature HashSet LinkedHashSet TreeSet
Allows Duplicates? No No No
Maintains Order? No Insertion Order Sorted Order
Null Allowed? One null One null element Null not allowed
element
Backed By Hash Table Linked Hash Table Red-Black Tree
Performance Fastest (O(1)) Slightly slower than Slower (O(log n))
HashSet
📌 2. HashSet – Fastest, No Order
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate
System.out.println(set); // Order not guaranteed, no
duplicates
}
}
📌 3. LinkedHashSet – Insertion Order Maintained
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("Dog");
set.add("Cat");
set.add("Elephant");
System.out.println(set); // Order preserved
}
}
📌 4. TreeSet – Automatically Sorted, No Nulls
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(50);
numbers.add(10);
numbers.add(30);
System.out.println(numbers); // Output: [10, 30, 50]
}
}
🔧 5. Use Case Examples
● Removing duplicates from a list
● Maintaining sorted unique data
● Fast membership testing (contains)
📘 6. Diagrams
📌 HashSet (No Order)
[?] [Apple] [Banana]
📌 LinkedHashSet (Preserved Order)
[Dog] -> [Cat] -> [Elephant]
📌 TreeSet (Sorted)
30
/ \
10 50
🎯 7. Interview Questions
1. HashSet vs TreeSet?
○ HashSet is faster (O(1) vs O(log n))
○ TreeSet maintains sorted order
2. Why are duplicates not allowed in Set?
○ Set is modeled after mathematical sets (unique elements)
3. Can HashSet store null?
○ Yes, but only one null.
4. When to use LinkedHashSet?
○ When you need insertion order with uniqueness.
5. TreeSet uses which data structure internally?
○ Red-Black Tree (Self-balancing BST)
💻 8. Day 3 Coding Exercises
Q1. Add 10 random integers (including duplicates) to a HashSet and print unique
numbers.
Q2. Create a LinkedHashSet of names, maintain order and test contains().
Q3. Create a TreeSet of strings and show how they are auto-sorted.
Q4. Find the first repeated and first non-repeated element in a list using Set and Map
together.
Day 3 Coding Exercise Solutions
✅ Q1. Add 10 random integers (including duplicates) to a HashSet and
print unique numbers
import java.util.HashSet;
import java.util.Set;
public class UniqueRandomIntegers {
public static void main(String[] args) {
int[] nums = {10, 20, 30, 20, 40, 50, 10, 60, 70, 30};
Set<Integer> unique = new HashSet<>();
for (int num : nums) {
unique.add(num);
}
System.out.println("Unique numbers: " + unique);
}
}
✅ Q2. Create a LinkedHashSet of names, maintain order and test
contains()
import java.util.LinkedHashSet;
public class OrderedNames {
public static void main(String[] args) {
LinkedHashSet<String> names = new LinkedHashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println("Names (order preserved): " + names);
System.out.println("Contains 'Bob'? " +
names.contains("Bob"));
System.out.println("Contains 'David'? " +
names.contains("David"));
}
}
✅ Q3. Create a TreeSet of strings and show how they are auto-sorted
import java.util.TreeSet;
public class SortedStrings {
public static void main(String[] args) {
TreeSet<String> animals = new TreeSet<>();
animals.add("Zebra");
animals.add("Elephant");
animals.add("Monkey");
animals.add("Dog");
System.out.println("Sorted Animals: " + animals);
}
}
✅ Q4. Find the first repeated and first non-repeated element in a list using
Set and Map
import java.util.*;
public class FirstRepeatAndUnique {
public static void main(String[] args) {
String[] elements = {"a", "b", "c", "a", "d", "e", "c"};
// First repeated element
Set<String> seen = new HashSet<>();
String firstRepeated = null;
for (String el : elements) {
if (!seen.add(el)) {
firstRepeated = el;
break;
}
}
// First non-repeated element
Map<String, Integer> freq = new LinkedHashMap<>();
for (String el : elements) {
freq.put(el, freq.getOrDefault(el, 0) + 1);
}
String firstUnique = null;
for (Map.Entry<String, Integer> entry : freq.entrySet()) {
if (entry.getValue() == 1) {
firstUnique = entry.getKey();
break;
}
}
System.out.println("First Repeated: " + firstRepeated); // a
System.out.println("First Non-Repeated: " + firstUnique); // b
}
}
Day 4: Map Interface in Java (HashMap,
LinkedHashMap, TreeMap)
🔹 1. What is a Map?
A Map is a collection that maps keys to values, with:
● No duplicate keys
● One value per key
● Key-value pair concept (K -> V)
Map is not a Collection, but part of java.util.
📊 Map Implementations Comparison
Feature HashMap LinkedHashMap TreeMap
Order No Insertion Order Sorted by Key
Null 1 null key, multiple null Same as No null key (null
Key/Value values HashMap values ok)
Thread-safe No No No
Performance O(1) average O(1) average O(log n)
Underlying DS Hash Table Hash Table + Linked Red-Black Tree
List
📌 2. HashMap – Most Common, Fast
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 90);
map.put("Bob", 85);
map.put("Alice", 95); // Overwrites
System.out.println("HashMap: " + map);
}
}
📌 3. LinkedHashMap – Insertion Order Preserved
import java.util.LinkedHashMap;
public class LinkedHashMapExample {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(3, "C");
map.put(1, "A");
map.put(2, "B");
System.out.println("LinkedHashMap: " + map);
}
}
📌 4. TreeMap – Sorted by Keys
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer> map = new TreeMap<>();
map.put("Zebra", 5);
map.put("Apple", 2);
map.put("Mango", 3);
System.out.println("TreeMap: " + map);
}
}
🧠 5. Diagram Representation
📌 HashMap
(Key -> Value)
"A" -> 90
"B" -> 85
(no order)
📌 LinkedHashMap
Insertion order:
3->C → 1->A → 2->B
📌 TreeMap
Sorted by Key:
Apple -> 2 → Mango -> 3 → Zebra -> 5
🎯 6. Interview Questions
1. HashMap vs TreeMap
○ HashMap: Unordered, O(1)
○ TreeMap: Sorted, O(log n)
2. Can Map have duplicate values?
○ Yes (but not duplicate keys)
3. Can we store null in Map?
○ HashMap allows 1 null key, many null values
○ TreeMap does not allow null key
4. Fail-fast vs Fail-safe in Map
○ HashMap is fail-fast (throws ConcurrentModificationException)
○ ConcurrentHashMap is fail-safe (used in multi-threading)
💻 7. Day 4 Coding Exercises
Q1. Create a HashMap with names and marks. Print all entries.
Q2. Create a LinkedHashMap with 5 cities and their PIN codes. Show that order is
maintained.
Q3. Create a TreeMap with employee names and their salaries. Show sorted order.
Q4. Count the frequency of characters in a string using a Map.
Day 4 Coding Exercise Solutions
✅ Q1. Create a HashMap with names and marks. Print all entries
import java.util.HashMap;
import java.util.Map;
public class StudentMarks {
public static void main(String[] args) {
Map<String, Integer> marks = new HashMap<>();
marks.put("Alice", 95);
marks.put("Bob", 88);
marks.put("Charlie", 92);
for (Map.Entry<String, Integer> entry : marks.entrySet()) {
System.out.println(entry.getKey() + " scored " +
entry.getValue());
}
}
}
✅ Q2. Create a LinkedHashMap with 5 cities and their PIN codes. Show
that order is maintained
import java.util.LinkedHashMap;
import java.util.Map;
public class CityPincode {
public static void main(String[] args) {
Map<String, Integer> cities = new LinkedHashMap<>();
cities.put("Delhi", 110001);
cities.put("Mumbai", 400001);
cities.put("Chennai", 600001);
cities.put("Kolkata", 700001);
cities.put("Bangalore", 560001);
System.out.println("Cities and PIN codes in insertion
order:");
for (Map.Entry<String, Integer> entry : cities.entrySet()) {
System.out.println(entry.getKey() + " - " +
entry.getValue());
}
}
}
✅ Q3. Create a TreeMap with employee names and their salaries. Show
sorted order
import java.util.Map;
import java.util.TreeMap;
public class EmployeeSalaries {
public static void main(String[] args) {
TreeMap<String, Integer> salaries = new TreeMap<>();
salaries.put("John", 70000);
salaries.put("Ava", 90000);
salaries.put("Mike", 85000);
salaries.put("Zara", 95000);
System.out.println("Employees sorted by name:");
for (Map.Entry<String, Integer> entry : salaries.entrySet()) {
System.out.println(entry.getKey() + ": ₹" +
entry.getValue());
}
}
}
✅ Q4. Count the frequency of characters in a string using a Map
import java.util.HashMap;
import java.util.Map;
public class CharFrequency {
public static void main(String[] args) {
String str = "programming";
Map<Character, Integer> freq = new HashMap<>();
for (char ch : str.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
System.out.println("Character Frequencies:");
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
System.out.println(entry.getKey() + ": " +
entry.getValue());
}
}
}
Day 5: Queue and Deque in Java
🔹 1. What is a Queue?
A Queue is a linear data structure that follows the FIFO (First-In-First-Out) principle.
Java provides these queue implementations under java.util:
Implementation Order Allows Null? Thread Safe
LinkedList FIFO
PriorityQueu Min-Heap (throws NPE)
e
ArrayDeque FIFO / LIFO (Stack)
🔹 2. What is a Deque?
A Deque (Double Ended Queue) allows insertion and removal from both ends.
Used to implement stacks or queues with more flexibility.
Java Deque Interface is implemented by:
● ArrayDeque
● LinkedList
🧠 3. Queue Interface – Basic Methods
offer(E e) // Adds element
poll() // Removes and returns head
peek() // Returns head without removing
📌 4. LinkedList as Queue
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.offer("A");
queue.offer("B");
queue.offer("C");
System.out.println("Queue: " + queue); // [A, B, C]
System.out.println("Removed: " + queue.poll()); // A
System.out.println("Next: " + queue.peek()); // B
}
}
📌 5. PriorityQueue – Elements are sorted (Min Heap)
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(40);
pq.offer(10);
pq.offer(30);
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " "); // 10 30 40
}
}
}
📌 6. ArrayDeque – Efficient for Stack & Queue
import java.util.ArrayDeque;
import java.util.Deque;
public class ArrayDequeExample {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
deque.offerFirst("A");
deque.offerLast("B");
deque.offerLast("C");
System.out.println("Deque: " + deque); // [A, B, C]
System.out.println("Removed: " + deque.pollFirst()); // A
System.out.println("Removed: " + deque.pollLast()); // C
}
}
🔍 7. Diagrams
Queue (FIFO):
Front → [A] → [B] → [C] → Rear
Deque:
Both ends active:
Front ⇄ [A] ⇄ [B] ⇄ [C] ⇄ Rear
PriorityQueue (Min-Heap):
10
/ \
30 40
🎯 8. Interview Questions
1. PriorityQueue vs TreeSet?
○ PriorityQueue allows duplicates, TreeSet does not
○ TreeSet sorted by comparator, PriorityQueue sorted by priority (heap)
2. ArrayDeque vs LinkedList?
○ ArrayDeque is faster, uses resizable array, no memory overhead
○ LinkedList uses nodes and consumes more memory
3. Why not use Stack or Vector?
○ Stack and Vector are legacy, slower, and synchronized (rarely needed)
4. Use case of Deque?
○ Palindrome checking
○ Sliding window problems
○ LRU Cache
💻 9. Day 5 Coding Exercises
Q1. Use Queue to reverse first k elements of an integer queue.
Q2. Use PriorityQueue to print top 3 highest numbers from an array.
Q3. Implement a simple Stack using Deque.
Q4. Check if a string is a palindrome using Deque.
Day 5 Coding Exercise Solutions
✅ Q1. Reverse first k elements of a Queue
import java.util.*;
public class ReverseKQueue {
public static void reverseFirstK(Queue<Integer> queue, int k) {
if (queue == null || k <= 0 || k > queue.size()) return;
Stack<Integer> stack = new Stack<>();
// Step 1: Push first k elements into stack
for (int i = 0; i < k; i++) {
stack.push(queue.poll());
}
// Step 2: Enqueue stack elements back to queue
while (!stack.isEmpty()) {
queue.offer(stack.pop());
}
// Step 3: Move remaining elements to the back to maintain
order
int size = queue.size();
for (int i = 0; i < size - k; i++) {
queue.offer(queue.poll());
}
}
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>(Arrays.asList(10, 20, 30,
40, 50));
int k = 3;
System.out.println("Original queue: " + q);
reverseFirstK(q, k);
System.out.println("Queue after reversing first " + k + "
elements: " + q);
}
}
✅ Q2. Use PriorityQueue to print top 3 highest numbers
import java.util.*;
public class Top3Numbers {
public static void main(String[] args) {
int[] nums = {5, 12, 11, 8, 10, 14, 3, 7};
// Min-heap of size 3
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : nums) {
pq.offer(num);
if (pq.size() > 3) {
pq.poll(); // remove smallest among top 4
}
}
// pq now contains top 3 numbers
List<Integer> top3 = new ArrayList<>();
while (!pq.isEmpty()) {
top3.add(pq.poll());
}
Collections.reverse(top3); // Descending order
System.out.println("Top 3 highest numbers: " + top3);
}
}
✅ Q3. Implement a simple Stack using Deque
import java.util.ArrayDeque;
import java.util.Deque;
public class StackUsingDeque {
private Deque<Integer> stack = new ArrayDeque<>();
public void push(int x) {
stack.offerLast(x);
}
public int pop() {
if (stack.isEmpty()) throw new RuntimeException("Stack
Underflow");
return stack.pollLast();
}
public int peek() {
if (stack.isEmpty()) throw new RuntimeException("Stack is
empty");
return stack.peekLast();
}
public boolean isEmpty() {
return stack.isEmpty();
}
public static void main(String[] args) {
StackUsingDeque stack = new StackUsingDeque();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element: " + stack.peek());
System.out.println("Popped: " + stack.pop());
System.out.println("Popped: " + stack.pop());
}
}
✅ Q4. Check if a string is palindrome using Deque
import java.util.ArrayDeque;
import java.util.Deque;
public class PalindromeChecker {
public static boolean isPalindrome(String s) {
Deque<Character> deque = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
deque.offerLast(ch);
}
while (deque.size() > 1) {
if (deque.pollFirst() != deque.pollLast()) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String str1 = "racecar";
String str2 = "hello";
System.out.println(str1 + " is palindrome? " +
isPalindrome(str1));
System.out.println(str2 + " is palindrome? " +
isPalindrome(str2));
}
}
Day 6: Java List Interface (ArrayList, LinkedList,
Vector, Stack)
🔹 1. What is a List?
● An ordered collection (sequence) that allows duplicates.
● Elements are accessible by their index.
● Part of java.util package.
● Common implementations:
○ ArrayList
○ LinkedList
○ Vector
○ Stack (legacy, subclass of Vector)
📊 List Implementations Comparison
Feature ArrayList LinkedList Vector Stack
Backing Data Dynamic array Doubly Linked List Dynamic array Extends Vector
(LIFO stack)
Thread Safety Not Not Synchronized
synchronized synchronized Synchronized
Access Time O(1) random O(n) sequential O(1) random O(1) (top
access access access element)
Insertion/Deletio Slow if in Fast if Slower than LIFO behavior
n middle (shift) adding/removing at ArrayList
ends
Use Case Most used list Frequent Legacy Legacy stack,
insert/delete multithreaded replaced by
Deque
📌 2. ArrayList Example
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Banana");
System.out.println("ArrayList: " + fruits);
System.out.println("Element at index 1: " + fruits.get(1));
}
}
📌 3. LinkedList Example
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.addFirst(5);
numbers.addLast(15);
System.out.println("LinkedList: " + numbers);
}
}
📌 4. Vector Example
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> v = new Vector<>();
v.add("X");
v.add("Y");
v.add("Z");
System.out.println("Vector: " + v);
}
}
📌 5. Stack Example (Legacy)
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(100);
stack.push(200);
System.out.println("Stack top: " + stack.peek());
System.out.println("Popped: " + stack.pop());
}
}
🧠 6. Diagram Overview
● ArrayList: Index-based array
[Apple, Mango, Banana]
● LinkedList: Nodes linked by pointers
(5) <-> (10) <-> (15)
● Vector: Like ArrayList but synchronized
[X, Y, Z]
● Stack: LIFO structure
Top → 200 → 100
🎯 7. Interview Questions
1. Why use LinkedList over ArrayList?
○ Frequent insertions/deletions at ends or middle.
2. How Vector differs from ArrayList?
○ Vector is synchronized (thread-safe), ArrayList is not.
3. Why Stack is considered legacy?
○ Because Deque (ArrayDeque) provides better stack features without
synchronization overhead.
4. Can List contain null values?
○ Yes, List allows multiple nulls.
💻 8. Day 6 Coding Exercises
Q1. Create an ArrayList of student names and print size and all names.
Q2. Use LinkedList to add elements at front and end, then remove from front.
Q3. Use Vector to add 5 elements and print if it's synchronized.
Q4. Use Stack to push 3 elements and pop them in LIFO order.
Day 6 Coding Exercise Solutions
✅ Q1. ArrayList of student names: print size and all names
import java.util.ArrayList;
public class StudentList {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add("Alice");
students.add("Bob");
students.add("Charlie");
System.out.println("Number of students: " + students.size());
System.out.println("Student names:");
for (String name : students) {
System.out.println(name);
}
}
}
✅ Q2. LinkedList: add at front and end, then remove from front
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(10); // Add at front
list.addLast(20); // Add at end
list.addFirst(5); // Add at front again
System.out.println("LinkedList: " + list);
int removed = list.removeFirst(); // Remove from front
System.out.println("Removed element: " + removed);
System.out.println("LinkedList after removal: " + list);
}
}
✅ Q3. Vector: add 5 elements and print if it is synchronized
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
vector.add("E");
System.out.println("Vector elements: " + vector);
// Vector is synchronized by default
System.out.println("Is Vector synchronized? " +
isSynchronized(vector));
}
// Check synchronization using reflection (for demo purposes)
public static boolean isSynchronized(Vector<?> vector) {
try {
// Vector's methods are synchronized
return true;
} catch (Exception e) {
return false;
}
}
}
✅ Q4. Stack: push 3 elements and pop in LIFO order
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(100);
stack.push(200);
stack.push(300);
System.out.println("Stack elements: " + stack);
while (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
}
}
}
Day 7: Java Set Interface (HashSet, LinkedHashSet,
TreeSet)
🔹 1. What is a Set?
● A Set is a collection that contains no duplicate elements.
● It models the mathematical set abstraction.
● Does not maintain insertion order (except some implementations).
● Used when uniqueness is important.
🔹 2. Set Implementations Overview
Implementatio Order Maintained Allows Null Underlying Data Thread
n Structure Safe
HashSet No Yes (one) Hash Table No
LinkedHashSe Yes (insertion order) Yes (one) Hash Table + Linked No
t List
TreeSet Sorted order (natural or No (throws Balanced Tree (Red- No
comparator) NPE) Black Tree)
📌 3. HashSet Example
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // duplicate ignored
System.out.println("HashSet: " + set);
}
}
📌 4. LinkedHashSet Example
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // duplicate ignored
System.out.println("LinkedHashSet: " + set);
}
}
📌 5. TreeSet Example
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(50);
set.add(20);
set.add(30);
set.add(20); // duplicate ignored
System.out.println("TreeSet (sorted): " + set);
}
}
🧠 6. Diagram Overview
● HashSet: Unordered unique elements
{Banana, Apple} (order undefined)
● LinkedHashSet: Ordered unique elements
[Apple, Banana]
● TreeSet: Sorted unique elements
[20, 30, 50]
🎯 7. Interview Questions
1. Why use LinkedHashSet over HashSet?
○ To preserve insertion order.
2. What is the time complexity of contains() in HashSet?
○ O(1) average case.
3. Can TreeSet store null?
○ No, it throws NullPointerException.
4. How does HashSet ensure uniqueness?
○ Uses hashCode() and equals() methods.
💻 8. Day 7 Coding Exercises
Q1. Create a HashSet of integers and add duplicates, then print the set.
Q2. Create a LinkedHashSet and add strings in order; print to verify order.
Q3. Create a TreeSet and add numbers; print to verify sorted order.
Q4. Remove an element from a HashSet and check if element exists.
Day 7 Coding Exercise Solutions
✅ Q1. HashSet with duplicates
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10); // duplicate
set.add(30);
System.out.println("HashSet elements: " + set);
}
}
✅ Q2. LinkedHashSet preserves insertion order
import java.util.LinkedHashSet;
public class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Two"); // duplicate
System.out.println("LinkedHashSet elements: " + set);
}
}
✅ Q3. TreeSet sorted order
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(40);
set.add(10);
set.add(30);
set.add(20);
System.out.println("TreeSet elements (sorted): " + set);
}
}
✅ Q4. Remove element from HashSet and check existence
import java.util.HashSet;
public class HashSetRemoveDemo {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C++");
System.out.println("Original HashSet: " + set);
set.remove("Python");
System.out.println("After removal: " + set);
System.out.println("Contains Java? " + set.contains("Java"));
System.out.println("Contains Python? " +
set.contains("Python"));
}
}
Day 8: Java Map Interface (HashMap, LinkedHashMap,
TreeMap)
🔹 1. What is a Map?
● An object that maps keys to values — like a dictionary.
● Keys are unique, but values can be duplicated.
● Not a Collection (does not extend Collection interface).
● Part of java.util package.
🔹 2. Map Implementations Overview
Implementatio Order Null Keys/Values Underlying Data Thread
n Maintained Structure Safe
HashMap No (unordered) One null key, multiple Hash Table No
null values
LinkedHashMa Yes (insertion One null key, multiple Hash Table + No
p order) null values Linked List
TreeMap Sorted by keys No null keys, values Balanced Tree No
allowed (Red-Black)
📌 3. HashMap Example
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Apple", 30); // replaces value for key "Apple"
System.out.println("HashMap: " + map);
System.out.println("Value for Banana: " + map.get("Banana"));
}
}
📌 4. LinkedHashMap Example
import java.util.LinkedHashMap;
public class LinkedHashMapExample {
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("A", "Alpha");
map.put("B", "Beta");
map.put("C", "Gamma");
System.out.println("LinkedHashMap (insertion order): " + map);
}
}
📌 5. TreeMap Example
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "Three");
map.put(1, "One");
map.put(2, "Two");
System.out.println("TreeMap (sorted by key): " + map);
}
}
🧠 6. Diagram Overview
● HashMap: Key-value pairs, unordered.
● LinkedHashMap: Maintains insertion order of key-value pairs.
● TreeMap: Sorted by keys (natural order or custom comparator).
🎯 7. Interview Questions
1. Can HashMap have null keys or values?
○ Yes, one null key and multiple null values allowed.
2. How is LinkedHashMap different from HashMap?
○ Maintains insertion order.
3. Why use TreeMap?
○ When sorted order of keys is needed.
4. What is the time complexity of get/put in HashMap?
○ Average O(1), worst O(n) (in case of many collisions).
💻 8. Day 8 Coding Exercises
Q1. Create a HashMap with 3 key-value pairs and print all entries.
Q2. Use LinkedHashMap to preserve insertion order and print keys.
Q3. Create a TreeMap with integer keys and print the sorted map.
Q4. Update a value for an existing key in HashMap and print the map.
Day 8 Coding Exercise Solutions
✅ Q1. HashMap with 3 key-value pairs and print all entries
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Math", 90);
map.put("Physics", 85);
map.put("Chemistry", 88);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " +
entry.getValue());
}
}
}
✅ Q2. LinkedHashMap to preserve insertion order and print keys
import java.util.LinkedHashMap;
import java.util.Set;
public class LinkedHashMapDemo {
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("A", "Apple");
map.put("B", "Banana");
map.put("C", "Cherry");
System.out.println("Keys in insertion order:");
for (String key : map.keySet()) {
System.out.println(key);
}
}
}
✅ Q3. TreeMap with integer keys and print sorted map
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(50, "Fifty");
map.put(20, "Twenty");
map.put(40, "Forty");
System.out.println("TreeMap sorted by keys:");
System.out.println(map);
}
}
✅ Q4. Update value for an existing key in HashMap and print
import java.util.HashMap;
public class HashMapUpdateDemo {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Math", 75);
map.put("Physics", 80);
System.out.println("Before update: " + map);
map.put("Math", 95); // update value
System.out.println("After update: " + map);
}
}
Day 9: Java Queue Interface (PriorityQueue,
ArrayDeque)
🔹 1. What is a Queue?
● A collection designed for holding elements prior to processing.
● Follows FIFO (First-In-First-Out) order, but some implementations differ.
● Part of java.util package.
● Key methods: offer(), poll(), peek().
🔹 2. Queue Implementations Overview
Implementatio Order Allows Thread Notes
n Null Safe
PriorityQueu Priority order No No Elements ordered by natural
e order or comparator
ArrayDeque FIFO (can be No No Resizable array, faster than
used as Deque) LinkedList for queue operations
📌 3. PriorityQueue Example
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(50);
pq.offer(10);
pq.offer(30);
System.out.println("PriorityQueue elements (natural order):");
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // Retrieves and removes
head of queue
}
}
}
📌 4. ArrayDeque Example
import java.util.ArrayDeque;
public class ArrayDequeExample {
public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();
deque.offer("First");
deque.offer("Second");
deque.offerFirst("Zero"); // add at front
System.out.println("ArrayDeque elements:");
while (!deque.isEmpty()) {
System.out.println(deque.poll());
}
}
}
🧠 5. Diagram Overview
● PriorityQueue: Elements ordered by priority (min-heap by default)
[10, 30, 50]
● ArrayDeque: FIFO with ability to add/remove at both ends
Front → Zero → First → Second → End
🎯 6. Interview Questions
1. What is the difference between Queue and Deque?
○ Queue is FIFO, Deque supports adding/removing at both ends.
2. Can PriorityQueue contain null?
○ No, it throws NullPointerException.
3. Why prefer ArrayDeque over LinkedList for queue operations?
○ ArrayDeque is faster and does not support capacity restrictions.
4. What is the time complexity of insertions in PriorityQueue?
○ O(log n) due to heap operations.
💻 7. Day 9 Coding Exercises
Q1. Create a PriorityQueue of integers, add elements, and print in priority order.
Q2. Use ArrayDeque to add elements at front and rear, then remove and print them.
Q3. Check if PriorityQueue accepts null by adding null element (expect exception).
Q4. Implement a simple queue using ArrayDeque and demonstrate FIFO behavior.
Day 9 Coding Exercise Solutions
✅ Q1. PriorityQueue with integers and print in priority order
import java.util.PriorityQueue;
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(25);
pq.offer(10);
pq.offer(15);
pq.offer(5);
System.out.println("PriorityQueue elements in priority
order:");
while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
}
}
✅ Q2. ArrayDeque add at front and rear, then remove and print
import java.util.ArrayDeque;
public class ArrayDequeDemo {
public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();
deque.offer("Rear1"); // Add at rear
deque.offerFirst("Front1"); // Add at front
deque.offer("Rear2");
System.out.println("ArrayDeque elements (FIFO):");
while (!deque.isEmpty()) {
System.out.println(deque.poll());
}
}
}
✅ Q3. Test if PriorityQueue accepts null (expect exception)
import java.util.PriorityQueue;
public class PriorityQueueNullTest {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<>();
try {
pq.offer(null);
} catch (NullPointerException e) {
System.out.println("NullPointerException caught:
PriorityQueue does not accept null");
}
}
}
✅ Q4. Simple FIFO queue using ArrayDeque
import java.util.ArrayDeque;
public class SimpleQueue {
public static void main(String[] args) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.offer(100);
queue.offer(200);
queue.offer(300);
System.out.println("Queue elements (FIFO):");
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
Day 10: Other Collections and Utility Classes
🔹 1. Collections Class
● Utility class with static methods to operate on or return collections.
● Common methods:
○ Collections.sort(List<T>)
○ Collections.reverse(List<T>)
○ Collections.shuffle(List<T>)
○ Collections.max(Collection<T>)
○ Collections.min(Collection<T>)
○ Collections.binarySearch(List<T>, key)
🔹 2. Arrays Class
● Utility class to manipulate arrays.
● Common methods:
○ Arrays.sort(array)
○ Arrays.binarySearch(array, key)
○ Arrays.equals(array1, array2)
○ Arrays.fill(array, value)
○ Arrays.copyOf(array, newLength)
🔹 3. Comparable Interface
● Defines natural ordering of objects.
● Has method:
int compareTo(T o)
● Used by Collections.sort() and TreeSet, TreeMap.
● Example:
public class Student implements Comparable<Student> {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(Student other) {
return this.id - other.id; // sort by id ascending
}
}
🔹 4. Comparator Interface
● Defines custom ordering.
● Has method:
int compare(T o1, T o2)
● Used for sorting with different criteria.
● Example:
import java.util.Comparator;
public class StudentNameComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
}
🎯 5. Interview Questions
1. What is the difference between Comparable and Comparator?
○ Comparable is natural ordering inside the class; Comparator is external and
custom ordering.
2. How to sort a list of objects by multiple fields?
○ Use Comparator chaining or write custom Comparator.
3. What happens if Comparable’s compareTo is inconsistent with equals?
○ May cause unexpected behavior in sorted collections.
💻 6. Day 10 Coding Exercises
Q1. Sort an array of integers using Arrays.sort() and print.
Q2. Sort a list of Student objects by natural order (id) using Comparable.
Q3. Sort the same list of Student objects by name using Comparator.
Q4. Use Collections.shuffle() on a list of strings and print the result.
Day 10 Coding Exercise Solutions
✅ Q1. Sort an array of integers using Arrays.sort() and print
import java.util.Arrays;
public class ArraySortDemo {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 1, 2};
Arrays.sort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
}
✅ Q2. Sort a list of Student objects by natural order (id) using
Comparable
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Student implements Comparable<Student> {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(Student other) {
return this.id - other.id;
}
@Override
public String toString() {
return id + ": " + name;
}
}
public class ComparableDemo {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(3, "Alice"));
students.add(new Student(1, "Bob"));
students.add(new Student(2, "Charlie"));
Collections.sort(students);
System.out.println("Students sorted by id:");
for (Student s : students) {
System.out.println(s);
}
}
}
✅ Q3. Sort the same list of Student objects by name using Comparator
import java.util.Comparator;
public class ComparatorDemo {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(3, "Alice"));
students.add(new Student(1, "Bob"));
students.add(new Student(2, "Charlie"));
// Sort by name using Comparator
students.sort(Comparator.comparing(s -> s.name));
System.out.println("Students sorted by name:");
for (Student s : students) {
System.out.println(s);
}
}
}
✅ Q4. Use Collections.shuffle() on a list of strings and print
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ShuffleDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Red");
list.add("Blue");
list.add("Green");
list.add("Yellow");
Collections.shuffle(list);
System.out.println("Shuffled list: " + list);
}
}
Java Collections Interview Questions & Tips Summary
1. Core Concepts
● What is the Collection Framework?
A unified architecture for storing and manipulating groups of objects.
● Difference between Collection and Map?
Collection stores elements; Map stores key-value pairs.
● Difference between List, Set, and Queue?
List: ordered, allows duplicates.
Set: unordered or ordered, no duplicates.
Queue: FIFO order (priority order in PriorityQueue).
2. List Interface
● ArrayList vs LinkedList — when to use which?
ArrayList: fast random access, slow inserts/removals.
LinkedList: fast inserts/removals, slower random access.
● How does ArrayList resize internally?
It doubles its size when capacity exceeded.
3. Set Interface
● Differences between HashSet, LinkedHashSet, TreeSet?
HashSet: no order.
LinkedHashSet: insertion order.
TreeSet: sorted order.
● Can Sets contain null?
HashSet and LinkedHashSet can contain one null; TreeSet cannot contain null.
4. Map Interface
● Differences between HashMap, LinkedHashMap, TreeMap?
HashMap: no order.
LinkedHashMap: insertion order.
TreeMap: sorted keys.
● Can HashMap have null keys/values?
Yes, one null key and multiple null values allowed.
● How does HashMap handle collisions?
Uses chaining (linked list or tree after threshold).
5. Queue Interface
● What is PriorityQueue?
Elements are ordered by priority (natural order or Comparator).
● Can PriorityQueue contain null?
No, throws NullPointerException.
6. Comparable vs Comparator
● Comparable: natural order, inside class (compareTo).
● Comparator: custom order, external class or lambda (compare).
7. Performance Tips
● Use ArrayList if you need fast random access and fewer insertions/removals.
● Use LinkedList if your app does frequent insertions/removals at head/tail.
● Use HashSet or HashMap for fastest lookup; use TreeSet or TreeMap if you need
sorted data.
● Avoid using Vector and Hashtable unless thread safety is required (prefer
Collections.synchronizedXXX or ConcurrentHashMap).
8. Common Interview Tasks
● Iterate over collections efficiently (for-each, Iterator, streams).
● Convert between collections and arrays.
● Implement equals(), hashCode(), and toString() for custom objects stored in
collections.
● Understand fail-fast behavior of iterators.
9. Useful Java Collection Utilities
● Collections.sort(), Collections.shuffle(), Collections.reverse().
● Arrays.sort(), Arrays.binarySearch().
● Use Comparator.comparing() for neat sorting code with Java 8+.