← all cheatsheets

cheatsheet · while you code

Java traps

Use it when: Before you press Submit, or when the output looks impossible.

One line per trap: the rule to remember. Want to feel each one? Drill them →

Integer, Long and ==

  • == on IntegerCompare wrappers with .equals(), or unbox to int first. Never == on Integer.
  • Comparing HashMap countscount.get(a).equals(count.get(b)), or Objects.equals(x, y) if a value can be null.
  • Long.equals(int)Match the types: total.equals(10L), or compare primitives: total.longValue() == 10.
  • Missing key into an intfreq.getOrDefault('z', 0) — the safe way to read a count.
  • new String vs literalAlways compare strings with .equals().
  • Strings built at runtime.equals() for strings, every time — even when == seemed to work in a small test.
  • StringBuilder.equalsTurn them into strings first: x.toString().equals(y.toString()).
  • Comparing arraysArrays.equals(a, b) for 1-D arrays, Arrays.deepEquals(a, b) for 2-D.

Numbers and overflow

  • int overflowUse long when a sum can pass about 2 × 10⁹, or Math.addExact to fail loudly.
  • Binary search midWrite int mid = lo + (hi - lo) / 2; in every binary search. Bas itna yaad rakho.
  • int × int into a longCast before you multiply: (long) a * b, not (long) (a * b).
  • "Infinity" + 1Skip unreachable states before adding (if (dist[u] == Integer.MAX_VALUE) continue;), or use a safe infinity like 1_000_000_000.
  • % with negativesUse Math.floorMod(x, k) (or ((x % k) + k) % k) whenever x can be negative.
  • Math.abs(MIN_VALUE)Go to long first: Math.abs((long) x). Watch for it in "reverse integer" and "divide two integers".
  • Comparator a - bInteger.compare(a, b) or Comparator.comparingInt(...) — they never overflow.
  • int / int into a doubleMake one side a double before dividing: (double) total / count.
  • 0.1 + 0.2 == 0.3Compare with a tolerance, Math.abs(a - b) < 1e-9, or keep money in whole paise as a long, not rupees as a double.
  • << and +Always bracket shifts and masks: (1 << k) + 1, (n & 1) == 0.
  • Math.round on halvesIf the problem states a rounding rule, write that rule yourself instead of assuming what round does.

Strings and chars

  • char + 1When you want a letter, cast: (char) (c + 1).
  • Digit char to intc - '0' for a digit, c - 'a' for a letter's index.
  • 'a' + 'b' + "c"Start with a String ("" + a + b) or use StringBuilder.append.
  • toUpperCase() thrown awayKeep the result: s = s.toUpperCase();
  • substring(begin, end)Think substring(i, i + len) for exactly len characters.
  • split and empty partssplit(",", -1) keeps the trailing empty parts too.
  • char[].toString()new String(chars) or String.valueOf(chars); Arrays.toString(chars) only for debugging.
  • count[ch - 'a'] with capitalsCheck the constraints. If capitals can appear, use Character.toLowerCase(ch) first, or an int[128] indexed by the char itself.

Collections

  • Arrays.asList then addnew ArrayList<>(Arrays.asList(1, 2, 3)) when the list must grow.
  • Arrays.asList(int[])Box it: Arrays.stream(nums).boxed().collect(Collectors.toList()), or start from an Integer[].
  • list.remove(1)To remove a value from a List<Integer>, pass an object: list.remove(Integer.valueOf(x)).
  • Removing inside for-eachlist.removeIf(x -> x % 2 == 0), or an explicit Iterator with it.remove().
  • Printing a PriorityQueueNeed sorted order? Poll in a loop. Never trust toString or for-each on a heap.
  • Which end is the top?Say it out loud while coding: "min-heap by default; reverseOrder for max".
  • Changing a HashMap keyNever change an object after using it as a key. Use immutable keys: List.of(...), a String, or a number.
  • HashSet<int[]>For a grid BFS, use boolean[][] visited, or encode a cell as r * cols + c.
  • Arrays.fill with a rowMake each row separately: for (int i = 0; i < n; i++) grid[i] = new int[m];
  • push and offer on one dequeOne style per deque: stack = push / pop / peek, queue = offer / poll / peek.
  • Stack vs ArrayDeque orderUse ArrayDeque (even Stack's Javadoc recommends Deque), and pop when you need top-first order.
  • TreeSet with tiesBreak ties in the comparator (compare the node id next), or use a PriorityQueue, which allows duplicates.
  • Sorting List.ofnew ArrayList<>(List.of(...)) when you will change it.

Methods and recursion

  • Reassign vs mutateTo give back a new array, return it. To change the caller's data, change the object, not the variable.
  • result.add(path)Add a copy: result.add(new ArrayList<>(path));
  • Very deep recursionIf the depth can reach ~10⁴–10⁵ (a long linked list, a skewed tree), use a loop or your own ArrayDeque stack.