Java Cheat Sheet

Everything you actually need when writing Java solutions.


Useful Constants

Integer.MAX_VALUE    //  2147483647
Integer.MIN_VALUE    // -2147483648
Long.MAX_VALUE       //  9223372036854775807
Long.MIN_VALUE       // -9223372036854775808

// Safe infinity for DP / Dijkstra
int INF = (int) 1e9;
long LINF = (long) 1e18;

Array

int[] arr = new int[n];               // default: all zeros
int[] arr = {1, 2, 3};
int[][] grid = new int[m][n];         // 2D array, all zeros

arr.length                            // size (not a method, no parentheses!)
grid.length                           // rows
grid[0].length                        // columns

// Fill
Arrays.fill(arr, 0);                  // fill entire array
Arrays.fill(arr, l, r, 0);           // fill index [l, r)

// Sort
Arrays.sort(arr);                     // ascending O(n log n)
Arrays.sort(arr, l, r);              // sort subarray [l, r)

// Sort object array descending (doesn't work on int[], use Integer[])
Integer[] arr2 = {3, 1, 2};
Arrays.sort(arr2, (a, b) -> b - a);  // descending

// Copy
int[] copy = Arrays.copyOf(arr, n);          // copy first n elements
int[] copy = Arrays.copyOfRange(arr, l, r);  // copy [l, r)

// Convert to String (for printing/debugging)
Arrays.toString(arr)                  // "[1, 2, 3]"
Arrays.deepToString(grid)            // for 2D arrays

ArrayList (dynamic array)

List<Integer> list = new ArrayList<>();
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

list.add(x)                          // append to end        O(1) amortized
list.add(i, x)                       // insert at index i    O(n)
list.get(i)                          // access               O(1)
list.set(i, x)                       // update at index i    O(1)
list.remove(i)                       // remove by index      O(n)
list.remove(Integer.valueOf(x))      // remove by value      O(n)
list.size()
list.isEmpty()
list.clear()
list.contains(x)                     // O(n)
list.indexOf(x)                      // first index of x, or -1

// Sort
Collections.sort(list);              // ascending
Collections.sort(list, (a, b) -> b - a);  // descending

// Reverse
Collections.reverse(list);

// Min / Max
Collections.min(list)
Collections.max(list)

// Iteration
for (int x : list) { }
for (int i = 0; i < list.size(); i++) { }

// Convert array → list
List<Integer> list = new ArrayList<>(Arrays.asList(arr));  // Integer[] only

// Convert list → array
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

String

String s = "hello";
s.length()
s.charAt(i)                          // character at index i
s.isEmpty()
s.equals("hello")                    // compare content (NOT ==)
s.equalsIgnoreCase("HELLO")
s.compareTo("world")                 // lexicographic comparison

s.substring(i)                       // from i to end
s.substring(i, j)                    // from i to j (exclusive)
s.indexOf("bc")                      // first occurrence index, or -1
s.lastIndexOf("bc")
s.contains("bc")                     // true/false
s.startsWith("he")
s.endsWith("lo")

s.toLowerCase()
s.toUpperCase()
s.trim()                             // remove leading/trailing whitespace
s.strip()                            // same but Unicode-aware (Java 11+)

s.replace('a', 'b')                  // replace all char occurrences
s.replace("ab", "cd")               // replace all string occurrences
s.replaceAll("[aeiou]", "*")        // regex replace

s.split(" ")                         // split by space → String[]
s.split("")                          // split into individual chars
String.join("-", "a", "b", "c")     // "a-b-c"
String.join("-", list)               // join a list

// String ↔ number
String.valueOf(42)                   // int → String
Integer.parseInt("42")              // String → int
Long.parseLong("42")                // String → long
Double.parseDouble("3.14")          // String → double

// Char utilities
Character.isLetter(c)
Character.isDigit(c)
Character.isLetterOrDigit(c)
Character.isWhitespace(c)
Character.toLowerCase(c)
Character.toUpperCase(c)
c - '0'                              // char digit → int
c - 'a'                              // char letter → 0-based index

// Sort a string
char[] ch = s.toCharArray();
Arrays.sort(ch);
String sorted = new String(ch);

StringBuilder (mutable string — use in loops!)

StringBuilder sb = new StringBuilder();
sb.append("hello")                   // append string
sb.append('a')                       // append char
sb.append(42)                        // append number
sb.insert(i, "abc")                 // insert at index
sb.delete(i, j)                      // delete [i, j)
sb.deleteCharAt(i)
sb.reverse()                         // reverse in place
sb.charAt(i)
sb.length()
sb.toString()                        // convert to String

// Common pattern: build result string
StringBuilder sb = new StringBuilder();
for (char c : chars) sb.append(c);
return sb.toString();

Stack

Deque<Integer> stack = new ArrayDeque<>();  // preferred over Stack<>

stack.push(x)                        // push to top      O(1)
stack.pop()                          // remove & return top   O(1)
stack.peek()                         // peek top         O(1)
stack.isEmpty()
stack.size()

// Common pattern
while (!stack.isEmpty()) {
    int x = stack.pop();
    // process x
}

Queue (FIFO)

Queue<Integer> q = new LinkedList<>();

q.offer(x)                           // enqueue          O(1)
q.poll()                             // dequeue          O(1)  — returns null if empty
q.peek()                             // front element    O(1)  — returns null if empty
q.isEmpty()
q.size()

// BFS pattern
Queue<Integer> q = new LinkedList<>();
q.offer(start);
while (!q.isEmpty()) {
    int node = q.poll();
    for (int neighbor : graph[node]) {
        q.offer(neighbor);
    }
}

Deque (double-ended queue)

Deque<Integer> dq = new ArrayDeque<>();

dq.offerFirst(x)  /  dq.offerLast(x)    // add front / back   O(1)
dq.pollFirst()    /  dq.pollLast()       // remove front / back O(1)
dq.peekFirst()    /  dq.peekLast()       // peek front / back   O(1)
dq.isEmpty()
dq.size()

// Use for: sliding window maximum (monotonic deque)

Priority Queue (heap)

PriorityQueue<Integer> minH = new PriorityQueue<>();              // min-heap (default)
PriorityQueue<Integer> maxH = new PriorityQueue<>((a, b) -> b - a);  // max-heap

minH.offer(x)                        // insert           O(log n)
minH.poll()                          // remove top       O(log n)
minH.peek()                          // peek top         O(1)
minH.isEmpty()
minH.size()

// Min-heap of int[] (sort by first element)
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);

// Max-heap of pairs sorted by second element
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]);

HashSet (unordered, unique elements)

Set<Integer> set = new HashSet<>();

set.add(x)                           // O(1) average
set.remove(x)                        // O(1) average
set.contains(x)                      // O(1) average
set.size()
set.isEmpty()
set.clear()

for (int x : set) { }               // no guaranteed order

// Convert array → set
Set<Integer> set = new HashSet<>(Arrays.asList(arr));  // Integer[] only

TreeSet (sorted, unique elements)

TreeSet<Integer> ts = new TreeSet<>();

ts.add(x)                            // O(log n)
ts.remove(x)                         // O(log n)
ts.contains(x)                       // O(log n)
ts.first()                           // smallest element
ts.last()                            // largest element
ts.floor(x)                          // largest element <= x
ts.ceiling(x)                        // smallest element >= x
ts.lower(x)                          // largest element < x
ts.higher(x)                         // smallest element > x
ts.size()
ts.isEmpty()

HashMap (unordered key-value)

Map<Integer, Integer> map = new HashMap<>();

map.put(key, val)                    // insert / update      O(1) avg
map.get(key)                         // returns null if missing
map.getOrDefault(key, 0)            // safe get with default
map.containsKey(key)                 // O(1) avg
map.containsValue(val)              // O(n)
map.remove(key)                      // O(1) avg
map.size()
map.isEmpty()

// Frequency count pattern
for (int x : nums) map.put(x, map.getOrDefault(x, 0) + 1);

// Iteration
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
    int key = e.getKey();
    int val = e.getValue();
}
for (int key : map.keySet()) { }
for (int val : map.values()) { }

TreeMap (sorted key-value)

TreeMap<Integer, Integer> tm = new TreeMap<>();

tm.put(key, val)                     // O(log n)
tm.get(key)                          // O(log n)
tm.containsKey(key)                  // O(log n)
tm.firstKey()                        // smallest key
tm.lastKey()                         // largest key
tm.floorKey(x)                       // largest key <= x
tm.ceilingKey(x)                     // smallest key >= x
tm.lowerKey(x)                       // largest key < x
tm.higherKey(x)                      // smallest key > x

// Iteration always in sorted key order
for (Map.Entry<Integer, Integer> e : tm.entrySet()) { }

Math Utilities

Math.max(a, b)
Math.min(a, b)
Math.abs(x)
Math.pow(base, exp)                  // returns double
Math.sqrt(x)                         // returns double
Math.ceil(x)                         // returns double
Math.floor(x)
Math.round(x)
Math.log(x)                          // natural log
Math.log10(x)

// Integer ceiling division (no float)
(a + b - 1) / b                      // ceil(a / b) for positive integers

// GCD (no built-in — write helper)
int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

// LCM
long lcm(long a, long b) {
    return a / gcd(a, b) * b;
}

// Overflow-safe addition check
if ((long) a + b > Integer.MAX_VALUE) { /* overflow */ }

Bit Manipulation

Integer.bitCount(x)                  // count set bits (1s)
Integer.highestOneBit(x)            // highest set bit value
Integer.numberOfLeadingZeros(x)
Integer.numberOfTrailingZeros(x)
Integer.toBinaryString(x)           // int → binary string

x & 1                                // check if odd
x >> 1                               // divide by 2
x << 1                               // multiply by 2
x & (x - 1)                          // clear lowest set bit
x & (-x)                             // isolate lowest set bit
(x >> i) & 1                         // check if i-th bit is set
x | (1 << i)                         // set i-th bit
x & ~(1 << i)                        // clear i-th bit
x ^ (1 << i)                         // toggle i-th bit

Sorting with Custom Comparator

// Sort int[] — must use Integer[] for lambda
Integer[] arr = {3, 1, 2};
Arrays.sort(arr, (a, b) -> b - a);                     // descending

// Sort 2D array by first column
int[][] intervals = {{1,3},{2,6},{8,10}};
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);

// Sort 2D array by second column
Arrays.sort(intervals, (a, b) -> a[1] - b[1]);

// Sort list of strings by length
List<String> words = new ArrayList<>();
Collections.sort(words, (a, b) -> a.length() - b.length());

// Multi-key sort
Arrays.sort(intervals, (a, b) -> {
    if (a[0] != b[0]) return a[0] - b[0];
    return a[1] - b[1];
});

Common Patterns — Quick Reference

// Frequency map
Map<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);

// 2D visited array
boolean[][] visited = new boolean[m][n];

// 4-directional grid traversal
int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};
for (int[] d : dirs) {
    int nr = r + d[0], nc = c + d[1];
    if (nr >= 0 && nr < m && nc >= 0 && nc < n) { }
}

// Prefix sum
int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++) prefix[i+1] = prefix[i] + nums[i];
// sum of [l, r] = prefix[r+1] - prefix[l]

// Sliding window skeleton
int l = 0, res = 0;
for (int r = 0; r < n; r++) {
    // expand window with nums[r]
    while (/* window invalid */) { l++; }
    res = Math.max(res, r - l + 1);
}

// Binary search template
int lo = 0, hi = n - 1;
while (lo <= hi) {
    int mid = lo + (hi - lo) / 2;   // avoids overflow
    if (nums[mid] == target) return mid;
    else if (nums[mid] < target) lo = mid + 1;
    else hi = mid - 1;
}

// BFS level-order traversal
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
    int size = q.size();             // current level size
    for (int i = 0; i < size; i++) {
        TreeNode node = q.poll();
        if (node.left != null)  q.offer(node.left);
        if (node.right != null) q.offer(node.right);
    }
}

Which Collection to Use — Decision Guide

NeedUse
Fast random accessArrayList
LIFO (stack)ArrayDeque (as stack)
FIFO (queue / BFS)LinkedList or ArrayDeque
Smallest/largest quicklyPriorityQueue
Fast exists check (unordered)HashSet
Sorted unique elements + floor/ceilingTreeSet
Fast key-value lookup (unordered)HashMap
Sorted key-value + floor/ceiling keysTreeMap
Duplicates + sortedPriorityQueue or sorted List
Sliding window / monotonic dequeArrayDeque

Time Complexities — Quick Reference

Collection / OperationComplexity
ArrayList get / setO(1)
ArrayList add (end)O(1) amortized
ArrayList add / remove (middle)O(n)
ArrayDeque push / pop / peekO(1)
PriorityQueue offer / pollO(log n)
PriorityQueue peekO(1)
HashSet / HashMap add / get / removeO(1) avg
TreeSet / TreeMap add / get / removeO(log n)
TreeSet floor / ceilingO(log n)
Arrays.sortO(n log n)
Collections.sortO(n log n)
Binary searchO(log n) — sorted only

Common Gotchas

// 1. Integer comparison — always use .equals(), not ==
Integer a = 127, b = 127;  a == b  // true  (cached)
Integer a = 200, b = 200;  a == b  // false (not cached!)
a.equals(b)                         // always correct

// 2. int[] can't be directly used in generics
List<int[]> list = new ArrayList<>();   // this is fine
Set<int[]>  set  = new HashSet<>();     // keys compared by reference, not value!

// 3. Stack — prefer ArrayDeque over Stack class
Stack<Integer> st = new Stack<>();      // legacy, slower
Deque<Integer> st = new ArrayDeque<>(); // preferred

// 4. Avoid integer overflow in comparators
// WRONG:
Arrays.sort(arr, (a, b) -> a - b);     // can overflow if a is very negative
// SAFE:
Arrays.sort(arr, (a, b) -> Integer.compare(a, b));

// 5. String concatenation in a loop is O(n²) — use StringBuilder
String res = "";
for (char c : chars) res += c;         // SLOW — O(n²)

StringBuilder sb = new StringBuilder();
for (char c : chars) sb.append(c);     // FAST — O(n)
String res = sb.toString();
Comments (2)