Lesson 0.2 · Java for DSA
Arrays and Strings in Java
Creating and walking arrays, the helper methods in Arrays, 2D arrays, and why strings are compared with equals and built with StringBuilder.
18 min
Think of it like this
An array is a row of numbered lockers bolted to the floor. You can open any locker instantly if you know its number, but you can't add a locker in the middle without moving everything after it.
A Java String is a printed label: you can read it, but to change it you print a new label. StringBuilder is a whiteboard you can keep writing on.
1.Creating and using arrays
An array has a fixed length, set when it's created. Indexes go from 0 to length - 1. New arrays are filled with default values: 0 for numbers, false for booleans, null for objects.
Arrays.toString prints an array (printing the array directly shows a memory reference like [I@1b6d3586). Arrays.sort sorts in place, and Arrays.fill sets every element.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {5, 2, 9, 1};
int[] b = new int[3]; // [0, 0, 0]
System.out.println(a.length); // 4
System.out.println(Arrays.toString(a));
Arrays.sort(a);
System.out.println(Arrays.toString(a));
Arrays.fill(b, -1);
System.out.println(Arrays.toString(b));
int[] copy = Arrays.copyOf(a, a.length); // a real copy, not a second name
copy[0] = 100;
System.out.println(a[0] + " " + copy[0]);
}
}Output
4
[5, 2, 9, 1]
[1, 2, 5, 9]
[-1, -1, -1]
1 1002.2D arrays (grids and matrices)
A 2D array is an array of rows. grid.length is the number of rows and grid[0].length is the number of columns. grid[r][c] is the cell in row r, column c.
Grids appear in many problems (islands, paths, matrices). Always check r and c stay inside 0..rows-1 and 0..cols-1 before reading a cell.
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
int rows = grid.length, cols = grid[0].length;
int sum = 0;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
sum += grid[r][c];
System.out.println(rows + "x" + cols + " sum=" + sum);
}
}Output
2x3 sum=213.Strings: reading characters and comparing
s.length() (with brackets, unlike arrays) gives the length, s.charAt(i) reads one character, and s.toCharArray() gives a char[] you can modify and sort.
Compare strings with a.equals(b), never a == b. == checks whether both names point to the same object in memory, which can be true or false for equal text depending on how the strings were created.
A char is a small number underneath: 'a' is 97, 'b' is 98. So c - 'a' turns a lowercase letter into 0–25, which is perfect as an index into an array of 26 counts.
public class Main {
public static void main(String[] args) {
String s = "hello";
String t = new String("hello");
System.out.println(s.charAt(1)); // e
System.out.println(s == t); // false: different objects
System.out.println(s.equals(t)); // true: same text
System.out.println('c' - 'a'); // 2
char[] cs = s.toCharArray();
java.util.Arrays.sort(cs);
System.out.println(new String(cs)); // ehllo
}
}Output
e
false
true
2
ehllo4.Building strings with StringBuilder
Strings are immutable: s += "x" creates a brand-new string and copies all the old characters. Doing that inside a loop of n steps copies 1 + 2 + ... + n characters, which is O(n²).
StringBuilder keeps a growable buffer. append is O(1) on average, and toString() makes the final string once.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i).append(',');
sb.setLength(sb.length() - 1); // drop the last comma
System.out.println(sb.toString());
System.out.println(sb.reverse()); // StringBuilder can reverse in place
}
}Output
0,1,2,3,4
4,3,2,1,0Quick check
Why is result += word inside a loop over 100,000 words slow?
Remember
- Arrays have fixed length; indexes run from 0 to length − 1.
- Print arrays with
Arrays.toString; copy them withArrays.copyOf, not=. - Compare strings with
equals;==compares object identity. c - 'a'maps a lowercase letter to 0–25.- Build strings in loops with
StringBuilder.
Common mistakes
- Using
s.length(no brackets) on a String orarr.length()on an array. - Assigning
int[] b = aand expecting a copy (both names share one array). - Comparing strings with
==. - Concatenating strings in a loop.
Words used in this lesson
- Index
- The position number of an element, starting from 0.
- Immutable
- Cannot be changed after creation.
- char
- A single character, stored as a small number (its code).
- In place
- Changing the input itself rather than creating a new copy.