Java Notes
Essential Java formulas, time complexity reference, bit manipulation tricks, and mathematical concepts used in programming and DSA.
Time Complexity (Big-O Notation)
What is Big-O?
Big-O notation describes the upper bound of an algorithm's growth rate. It tells us how the runtime or space grows as input size (n) increases.
| Notation | Name | Example | n=1000 Operations |
|---|---|---|---|
| O(1) | Constant | Array access by index | 1 |
| O(log n) | Logarithmic | Binary Search | ~10 |
| O(n) | Linear | Linear Search | 1,000 |
| O(n log n) | Linearithmic | Merge Sort | ~10,000 |
| O(n²) | Quadratic | Bubble Sort | 1,000,000 |
| O(n³) | Cubic | Matrix Multiplication | 1,000,000,000 |
| O(2ⁿ) | Exponential | Recursive Fibonacci | 1.07 × 10³⁰⁰ |
| O(n!) | Factorial | Traveling Salesman (brute) | 4.02 × 10²⁵⁶⁷ |
Growth Rate Comparison
Practical Limits (for 1 second execution)
| Complexity | Max n (approx) |
|---|---|
| O(n!) | n ≤ 12 |
| O(2ⁿ) | n ≤ 25 |
| O(n³) | n ≤ 500 |
| O(n²) | n ≤ 10,000 |
| O(n log n) | n ≤ 10,000,000 |
| O(n) | n ≤ 100,000,000 |
| O(log n) | n ≤ 10¹⁸ |
Sorting Algorithms Complexity
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting Sort | O(n + k) | O(n + k) | O(n + k) | O(k) | Yes |
| Radix Sort | O(d × (n + k)) | O(d × (n + k)) | O(d × (n + k)) | O(n + k) | Yes |
| Tim Sort | O(n) | O(n log n) | O(n log n) | O(n) | Yes |
| Bucket Sort | O(n + k) | O(n + k) | O(n²) | O(n) | Yes |
Tim Sort is used byArrays.sort()for objects andCollections.sort()in Java. Dual-Pivot Quick Sort is used byArrays.sort()for primitives.
k = range of input values, d = number of digits
Searching Algorithms Complexity
| Algorithm | Best | Average | Worst | Space | Requirements |
|---|---|---|---|---|---|
| Linear Search | O(1) | O(n) | O(n) | O(1) | None |
| Binary Search | O(1) | O(log n) | O(log n) | O(1) | Sorted array |
| Binary Search (recursive) | O(1) | O(log n) | O(log n) | O(log n) | Sorted array |
| Jump Search | O(1) | O(√n) | O(√n) | O(1) | Sorted array |
| Interpolation Search | O(1) | O(log log n) | O(n) | O(1) | Uniform distribution |
| Exponential Search | O(1) | O(log n) | O(log n) | O(1) | Sorted, unbounded |
| Ternary Search | O(1) | O(log₃ n) | O(log₃ n) | O(1) | Sorted array |
Graph Algorithm Complexity
| Algorithm | Time | Space | Use Case |
|---|---|---|---|
| BFS | O(V + E) | O(V) | Shortest path (unweighted) |
| DFS | O(V + E) | O(V) | Cycle detection, topological sort |
| Dijkstra (min-heap) | O((V + E) log V) | O(V) | Shortest path (positive weights) |
| Bellman-Ford | O(V × E) | O(V) | Shortest path (negative weights) |
| Floyd-Warshall | O(V³) | O(V²) | All-pairs shortest path |
| Kruskal's MST | O(E log E) | O(V) | Minimum spanning tree |
| Prim's MST (min-heap) | O((V + E) log V) | O(V) | Minimum spanning tree |
| Topological Sort | O(V + E) | O(V) | Task scheduling (DAG) |
| Tarjan's SCC | O(V + E) | O(V) | Strongly connected components |
| A* Search | O(E) | O(V) | Heuristic-guided pathfinding |
V = vertices (nodes), E = edges
Tree Algorithm Complexity
| Operation | BST (avg) | BST (worst) | AVL Tree | Red-Black Tree |
|---|---|---|---|---|
| Search | O(log n) | O(n) | O(log n) | O(log n) |
| Insert | O(log n) | O(n) | O(log n) | O(log n) |
| Delete | O(log n) | O(n) | O(log n) | O(log n) |
| Traversal | O(n) | O(n) | O(n) | O(n) |
| Height | O(log n) avg | O(n) | O(log n) | O(log n) |
Tree Height Formula:
| Minimum height of BST with n nodes | ⌊log₂(n)⌋ |
| Maximum height of BST with n nodes | n - 1 (degenerate/skewed) |
| Height of complete binary tree | ⌊log₂(n)⌋ |
| Number of nodes in complete binary tree of height h | 2^(h+1) - 1 |
| Number of leaf nodes in complete binary tree | ⌈n/2⌉ |
Dynamic Programming Patterns
| Problem | Time | Space | Approach |
|---|---|---|---|
| Fibonacci | O(n) | O(1) with optimization | Bottom-up tabulation |
| Longest Common Subsequence | O(m × n) | O(m × n) or O(min(m,n)) | 2D table |
| Longest Increasing Subsequence | O(n log n) | O(n) | Binary search + patience sort |
| 0/1 Knapsack | O(n × W) | O(n × W) or O(W) | 2D or 1D DP |
| Coin Change (min coins) | O(n × amount) | O(amount) | 1D DP |
| Edit Distance | O(m × n) | O(m × n) | 2D table |
| Matrix Chain Multiplication | O(n³) | O(n²) | Interval DP |
| Subset Sum | O(n × sum) | O(sum) | Boolean DP |
Java String Pool & Memory Formulas
String Pool Behavior
// String Literal → Pool
String s1 = "Hello"; // Goes to String Pool
String s2 = "Hello"; // Reuses from Pool
System.out.println(s1 == s2); // true (same reference)
// new String() → Heap
String s3 = new String("Hello"); // New object in Heap
System.out.println(s1 == s3); // false (different reference)
System.out.println(s1.equals(s3)); // true (same content)
// intern() → Returns Pool reference
String s4 = s3.intern();
System.out.println(s1 == s4); // true (pool reference)Memory created for String s = new String("Hello"):
- If "Hello" is NOT in pool: 2 objects created (1 in pool + 1 in heap)
- If "Hello" IS already in pool: 1 object created (only in heap)
String Memory Calculation
Note: Java 9+ uses compact strings (Latin-1 = 1 byte per char, UTF-16 = 2 bytes)
StringBuilder vs String Concatenation
String concatenation in loop (n iterations)
Memory: O(n²) — creates n intermediate String objects
Time: O(n²) — copies characters repeatedly
StringBuilder in loop (n iterations)
Memory: O(n) — single resizable buffer
Time: O(n) — amortized O(1) per append
StringBuilder initial capacity = 16 characters
Growth formula: newCapacity = (oldCapacity * 2) + 2
JVM Memory Formulas
Object Memory Layout (64-bit JVM with CompressedOops)
Object Header = 12 bytes (8 mark word + 4 compressed class pointer)
Array Header = 16 bytes (12 + 4 bytes for length)
Object size is padded to multiple of 8 bytes.
Example: class with 1 int and 1 reference
= 12 (header) + 4 (int) + 4 (reference) + 4 (padding) = 24 bytesHeap Memory Calculation
GC Tuning Formulas
| -Xms = Initial heap size (recommended | same as -Xmx for production) |
| -Xmx = Maximum heap size (recommended | 50-70% of available RAM) |
| -Xss = Thread stack size (default | 512KB - 1MB per thread) |
| Example | 200 threads × 1MB = 200MB just for thread stacks |
| -XX | MaxMetaspaceSize = default unlimited (uses native memory) |
Collections Size & Capacity Formulas
ArrayList Capacity
// Default initial capacity
private static final int DEFAULT_CAPACITY = 10;
// Growth formula (Java 11+)
int newCapacity = oldCapacity + (oldCapacity >> 1); // 1.5x growth
// 10 → 15 → 22 → 33 → 49 → 73 → 109 → ...
// Memory for ArrayList of n elements
// = 12 (object header) + 4 (size) + 4 (array ref) + padding
// + 16 (array header) + (capacity × 4) bytes for referencesHashMap Capacity
// Default initial capacity
static final int DEFAULT_INITIAL_CAPACITY = 16; // Must be power of 2
// Default load factor
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// Resize threshold
threshold = capacity × loadFactor;
// 16 × 0.75 = 12 → resize to 32 when 13th entry added
// Capacity sequence: 16 → 32 → 64 → 128 → 256 → ...
// Optimal initial capacity to avoid resizing:
initialCapacity = (int)(expectedSize / loadFactor) + 1;
// For 100 entries: (100 / 0.75) + 1 = 134 → rounds up to 256 (next power of 2)
// Memory per entry (approximate):
// Node: 12 (header) + 4 (hash) + 4 (key ref) + 4 (value ref) + 4 (next ref) = 32 bytes
// Total HashMap memory ≈ 48 + (capacity × 4) + (entries × 32) bytesHashSet
Thread & Concurrency Formulas
Thread States in Java
| NEW | RUNNABLE → (BLOCKED | WAITING | TIMED_WAITING) → TERMINATED |
| - new Thread() | NEW |
| - thread.start() | RUNNABLE |
| - waiting for monitor lock | BLOCKED |
| - Object.wait() / join() | WAITING |
| - Thread.sleep(ms) / wait(ms) | TIMED_WAITING |
| - run() completes / exception | TERMINATED |
Thread Pool Sizing Formulas
| Example: 8 cores | 9 threads |
| Example | 8 cores, task waits 80ms, computes 20ms |
| where | N_cpu = number of CPUs |
Concurrent Collection Performance
ConcurrentHashMap
Concurrency level = 16 (default segments)
Read: O(1) - no lock, uses volatile reads
Write: O(1) - locks only the segment (1/16 of map)
CopyOnWriteArrayList
Read: O(1) - no synchronization needed
Write: O(n) - copies entire array
Best when: reads >> writes
BlockingQueue capacity planning
Optimal size = producer_rate × max_acceptable_latency
Example: 1000 msgs/sec, 5 sec max wait = 5000 capacity
Bit Manipulation Formulas
Common Bit Operations
Bit Manipulation for Subsets
Mathematical Formulas for Programming
Number Theory
| // Time | O(√n) |
| return b == 0 ? a | gcd(b, a % b); |
| // Time | O(log(min(a,b))) |
| // OR | String.valueOf(n).length() |
| // Pascal's triangle | nCr = (n-1)C(r-1) + (n-1)Cr |
Array & Sequence Formulas
Recursion & Recurrence Relations
Common Recurrences and Solutions
| T(n) = T(n/2) + O(1) | O(log n) // Binary Search |
| T(n) = T(n/2) + O(n) | O(n) // Quickselect average |
| T(n) = 2T(n/2) + O(1) | O(n) // Tree traversal |
| T(n) = 2T(n/2) + O(n) | O(n log n) // Merge Sort |
| T(n) = 2T(n/2) + O(n²) | O(n²) // Bad divide and conquer |
| T(n) = T(n-1) + O(1) | O(n) // Linear recursion |
| T(n) = T(n-1) + O(n) | O(n²) // Selection Sort |
| T(n) = 2T(n-1) + O(1) | O(2^n) // Fibonacci (naive) |
| T(n) = T(n-1) + T(n-2) + O(1) | O(1.618^n) // Fibonacci recurrence |
Master Theorem
For recurrences of the form: T(n) = a × T(n/b) + O(n^d)
| If log_b(a) < d | T(n) = O(n^d) |
| If log_b(a) = d | T(n) = O(n^d × log n) |
| If log_b(a) > d | T(n) = O(n^(log_b(a))) |
| - Merge Sort: a=2, b=2, d=1 | log₂(2) = 1 = d → O(n log n) ✓ |
| - Binary Search: a=1, b=2, d=0 | log₂(1) = 0 = d → O(log n) ✓ |
| - Strassen's: a=7, b=2, d=2 | log₂(7) ≈ 2.81 > 2 → O(n^2.81) ✓ |
Hashing Formulas
Hash Function Properties
Load Factor and Performance
Expected number of comparisons for successful search
= 1 + α/2 (where α = load factor)
Example: α = 0.75 → 1.375 comparisons on average
Expected number of comparisons for unsuccessful search
= 1 + α
Example: α = 0.75 → 1.75 comparisons on average
When load factor > 0.75, resize to maintain O(1) performance
Important Java-Specific Formulas
Primitive Type Ranges
| byte: -128 to 127 (2^7 - 1) | 1 byte |
| short: -32,768 to 32,767 (2^15 - 1) | 2 bytes |
| int: -2,147,483,648 to 2,147,483,647 (2^31 - 1) | 4 bytes |
| long: -9.2 × 10^18 to 9.2 × 10^18 (2^63 - 1) | 8 bytes |
| float: ±3.4 × 10^38 (7 decimal digits) | 4 bytes |
| double: ±1.7 × 10^308 (15 decimal digits) | 8 bytes |
| char: 0 to 65,535 (2^16 - 1) | 2 bytes |
| boolean: true/false | 1 byte (JVM dependent) |
| Formula | For signed n-bit integer: |
| Math.addExact(a, b) | throws ArithmeticException on overflow |
Array Memory Calculation
Collections Memory Estimates
Interview Quick Reference
Complexity Cheat Sheet for Java Collections
When to Use Which Data Structure
| Need fast lookup by key | HashMap (O(1)) |
| Need sorted keys | TreeMap (O(log n)) |
| Need insertion order preserved | LinkedHashMap (O(1)) |
| Need fast add/remove at both ends | ArrayDeque (O(1)) |
| Need thread-safe map | ConcurrentHashMap |
| Need priority access | PriorityQueue (O(log n)) |
| Need unique elements | HashSet (O(1)) |
| Need sorted unique elements | TreeSet (O(log n)) |
| Need fast random access | ArrayList (O(1)) |
| Need fast insert/delete middle | LinkedList (O(1) if iterator) |
Space Complexity Rules
| - Primitive variable | O(1) |
| - Array of size n | O(n) |
| - 2D array m×n | O(m×n) |
| - HashMap with n entries | O(n) |
| - Recursive call stack depth d | O(d) |
| - Binary tree with n nodes | O(n) storage, O(h) for operations |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Important Formulas & Concepts.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, notes, important, formulas
Related Java Master Course Topics