synopsis · Java for DSA · chapter 2

Arrays & Strings in Java

8 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.

  1. what it is

    int[] = fixed row of slots, pre-filled with 0/false/null. String = text you read but never change. StringBuilder = text you build.

  2. use it when

    Size known → int[]. Size unknown or a List is returned → ArrayList<Integer>. Text in a loop → StringBuilder. Only a–z → int[26].

  3. template

    int[] count = new int[26]; for (char c : s.toCharArray()) count[c - 'a']++;

  4. cost

    s += c n times copies 1 + 2 + … + n chars: O(n²). sb.append(c) is O(1) amortised: O(n). substring, split, toCharArray copy: O(n).

  5. trap

    arr.length · s.length() · list.size(). And == on arrays or strings compares references — use Arrays.equals / equals.

  6. trap

    Arrays.asList(int[]) is a List<int[]> of ONE element. split(".") splits on every char — escape it: split("\\.").

  7. pro tip

    Print with Arrays.toString(a) (2D: deepToString). Plain println(a) shows junk like [I@1b6d3586.

  8. pro tip

    'a' + 1 is the int 98; (char) ('a' + 1) is 'b'. Digit chars: c - '0'.

Shaky on a card? Open the chapter or flip its recall cards.