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.
- 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. - 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]. - template
int[] count = new int[26]; for (char c : s.toCharArray()) count[c - 'a']++; - cost
s += cn times copies 1 + 2 + … + n chars: O(n²).sb.append(c)is O(1) amortised: O(n).substring,split,toCharArraycopy: O(n). - trap
arr.length·s.length()·list.size(). And==on arrays or strings compares references — useArrays.equals/equals. - trap
Arrays.asList(int[])is aList<int[]>of ONE element.split(".")splits on every char — escape it:split("\\."). - pro tip
Print with
Arrays.toString(a)(2D:deepToString). Plainprintln(a)shows junk like[I@1b6d3586. - pro tip
'a' + 1is the int 98;(char) ('a' + 1)is 'b'. Digit chars:c - '0'.
Shaky on a card? Open the chapter or flip its recall cards.