Skip to content
notes.vinhnq.com

Search

Java CoreJunior19 min read

Java basics: arrays and strings

Review 11 cards
On this page

Java basics series: 1. JVM and JDK · 2. Hello World and the three kinds of errors · 3. Variables and types · 4. Operators and branching · 5. Loops and methods · 6. Arrays and strings · 7. Console and text files · 8. Byte streams and serialization

To read 100 scores and average them you can’t declare 100 variables; you need an array to hold many values of the same type. Strings are the data a backend handles most (names, emails, JSON, SQL), and comparing and concatenating them has a few traps worth knowing. Read loops and methods first (especially pass-by-value); next up is console I/O and text files.

1. Arrays

Key idea: an array is one contiguous block of fixed size, every slot the same type, indexed from 0. Because the slots sit side by side, access by index is O(1).

One-dimensional arrays

double[] scores;                 // declaration (preferred style)
double scores2[];                // also legal (C style), but avoid it
scores = new double[5];          // allocate 5 elements, all 0.0

int[] ids = new int[3];          // declare + allocate
ids[0] = 7;                      // assign by index, 0 <= index < length
int[] primes = {2, 3, 5, 7};     // declare + fill in one go

for (int i = 0; i < ids.length; i++) ids[i] = i * 10;   // fill with a loop
for (int id : ids) System.out.println(id);              // read
  • Default element values: 0 for numeric types, false for boolean, '\u0000' for char, null for references.
  • length is a field, not a method (unlike String.length() and List.size()).
  • Accessing anything outside [0, length) throws ArrayIndexOutOfBoundsException. The JVM always checks bounds, so Java has no C-style buffer overflows.
  • The size is fixed once created. For a growable array use ArrayList: internally also an array, and when it fills up it allocates one about 1.5 times larger and copies the data over.
  • One slide example says “assign 0 … 5 to a 5-element array”. A 5-element array only has indexes 0 … 4.

Arrays and methods

static int[] range(int n) {            // returns an array
    int[] result = new int[n];
    for (int i = 0; i < n; i++) result[i] = i;
    return result;
}

static void print(int[] array) {       // takes an array
    for (int i = 0; i < array.length; i++) {
        System.out.printf("a[%d] = %d%n", i, array[i]);
    }
}

If a method changes the elements of an array it receives, the caller sees the change (see pass-by-value). The two copies of the slides word this differently (the changes are “applied” vs “kept”), but they mean the same thing: changes made inside the method persist after it returns.

Handy Arrays utilities:

int[] copy = Arrays.copyOf(src, src.length);   // shallow copy
Arrays.sort(copy);                             // primitives: dual-pivot quicksort; objects: TimSort (stable)
int pos = Arrays.binarySearch(copy, 42);       // the array must already be sorted
System.out.println(Arrays.toString(copy));     // printing the array directly gives "[I@1b6d3586"
Arrays.equals(a, b);                           // compares contents; a == b only compares references

Two-dimensional and jagged arrays

2D arrays model tabular data: matrices, game boards, a table of distances between cities. In Java it is an array of arrays: each row is its own array object.

int[][] matrix = new int[2][3];          // 2 rows, 3 columns
matrix[1][2] = 9;
int[][] grid = {{1, 2}, {3, 4}, {5, 6}};

for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {   // use grid[r].length; don't assume equal rows
        System.out.print(grid[r][c] + " ");
    }
    System.out.println();
}

Because each row is a separate array, rows can have different lengths. That is a jagged array:

int[][] triangle = new int[4][];        // 4 rows, no columns yet
for (int r = 0; r < triangle.length; r++) {
    triangle[r] = new int[r + 1];       // row r has r+1 elements
}
flowchart LR
  T[triangle] --> R0[row 0: 1 cell]
  T --> R1[row 1: 2 cells]
  T --> R2[row 2: 3 cells]
  T --> R3[row 3: 4 cells]
  • Iterating row by row ([r][c] with c in the inner loop) is faster than column by column, because a row’s elements are contiguous.
  • For a quick print of a 2D array: Arrays.deepToString(grid).

Multi-dimensional arrays

An n-dimensional array has n pairs of [], e.g. int[][][] cube = new int[2][3][4];. The slide’s syntax new [size1]...[sizeN] is missing the element type; it should read new int[size1]...[sizeN].

2. Strings

Key idea: String is an immutable class: every method that “changes” a string returns a new one. Two rules follow: compare with equals, and build repeatedly with StringBuilder.

String is not a primitive. Internally it is a byte array plus an encoding flag (Latin-1 or UTF-16, the “compact strings” optimisation since Java 9). So many operations mirror arrays: it has a length, zero-based indexes, and an out-of-range index throws StringIndexOutOfBoundsException.

Everyday methods

String s = " Java Basic ";
s.length();                 // 12: both surrounding spaces count
s.trim();                   // "Java Basic": strips leading and trailing whitespace
s.strip();                  // "Java Basic" (Java 11): Unicode-aware, prefer it over trim
s.isBlank();                // false (Java 11): true if empty or whitespace only
s.charAt(1);                // 'J'
s.indexOf("a");             // 2; -1 if not found
s.lastIndexOf('a');         // 7
s.trim().substring(5);      // "Basic"
s.trim().substring(0, 4);   // "Java": the end index is exclusive
s.toUpperCase();            // " JAVA BASIC "
s.contains("Bas");          // true; there are also startsWith and endsWith
s.replace("Basic", "Core"); // " Java Core "
"a,b,,c,,".split(",");      // [a, b, , c]: trailing empty strings are dropped
String.join("-", "a", "b"); // "a-b"
"ab".repeat(3);             // "ababab" (Java 11)
"Java".equalsIgnoreCase("JAVA"); // true
char[] chars = s.toCharArray();  // string -> char array; new String(chars) goes back

split, replaceAll and matches take a regex (a pattern), not a plain string:

  • "a.b".split(".") returns an empty array because . matches any character; you need split("\\.").
  • replaceAll/matches compile the pattern again on every call. split has a fast path for one-character separators such as "," or "\\.".
  • Details in Regex: syntax, the Java API and exercises.

Some material claims " Java Basic ".length() is 13. Count again: 1 space + 4 letters + 1 space + 5 letters + 1 space = 12.

Comparing strings: == vs equals

String a = "hello";
String b = new String("hello");
String c = "hel" + "lo";      // a compile-time constant, folded into "hello"
a == b;                       // false: two different objects
a.equals(b);                  // true: same content
a == c;                       // true: both are the same literal in the string pool

The JVM shares one object for identical literals (the string pool), so == is sometimes “accidentally” true. Don’t rely on it: always compare content with equals. Put the constant on the left ("ACTIVE".equals(status)) so a null status doesn’t throw NullPointerException.

Concatenation in a loop and StringBuilder

result = result + i in a loop creates a new string each time and copies all the old content, for O(n²) in total. StringBuilder keeps a growable array, so append is amortized O(1) (it occasionally has to grow the array, but spread over all calls the cost per call is constant):

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10_000; i++) sb.append(i).append(',');
sb.setLength(sb.length() - 1);   // drop the trailing comma
sb.insert(0, ">> ");             // insert at the front
sb.reverse();                    // reverse; there are also delete(start, end) and replace(start, end, str)
String result = sb.toString();
  • For a few values on one line ("Hello " + name + "!"), just use +; the compiler optimises it.
  • StringBuffer is like StringBuilder but every method is synchronized. Older material recommends it “for multithreaded code”, but that’s rarely right: each thread should build its own string.
  • The string pool, intern() and a fuller comparison of the options are in wrapper classes, BigDecimal and String.

Exercises

Each prompt is a short paraphrase. All solutions were run on JDK 21.

  1. Sum the elements of an array.
  2. Return the index of n in an array, or -1 if it’s missing.
  3. Largest element of a 2D array.
  4. Symmetric array (reads the same both ways, e.g. [1, 2, 3, 2, 1]), printing YES/NO.
  5. Find the value that appears more than once and whose first occurrence comes earliest; print NO if there is none. N can be 100,000. Input: the first line is the number of test cases T, and each test has a line with N followed by a line of N numbers. Sample: 10 5 3 4 3 5 6 gives 5, 1 2 3 4 gives NO.
  6. Multiply an N×M matrix A by its transpose. Read several test cases (the first line is the count, then each test has n m followed by n rows of the matrix) and print Test k: before each result matrix, with exactly one space between numbers.
  7. Read 5 integers into an array and print their sum and the largest one.
  8. Compute the total and average of {8.5, 7.0, 9.0, 6.5, 8.0} with for-each.
  9. Find the winner on a 3×3 tic-tac-toe board (a char[3][3], empty cells are ' '): a player wins with three identical marks in a row, a column or a diagonal.
Solutions 1–5: sum, search, 2D max, symmetry, first repeated value

1. Use a long accumulator to avoid overflow:

static long sum(int[] a) {
    long s = 0;
    for (int x : a) s += x;
    return s;               // or Arrays.stream(a).asLongStream().sum()
}

2. Linear search, O(n):

static int indexOf(int[] a, int target) {
    for (int i = 0; i < a.length; i++) if (a[i] == target) return i;
    return -1;
}

3. Start from Integer.MIN_VALUE, not 0, because the array might be all negative, and handle empty rows:

static int max2D(int[][] m) {
    int max = Integer.MIN_VALUE;
    boolean any = false;
    for (int[] row : m) for (int x : row) { max = Math.max(max, x); any = true; }
    if (!any) throw new IllegalArgumentException("Empty matrix");
    return max;
}

4. Same two-pointer idea as the palindrome exercise in the loops and methods post:

static boolean isSymmetric(int[] a) {
    for (int i = 0, j = a.length - 1; i < j; i++, j--) if (a[i] != a[j]) return false;
    return true;
}

5. With N up to 100,000, O(n²) is out. Count frequencies with a HashMap, then scan the array again from the start; O(n) time and O(n) memory:

static String firstRepeated(int[] a) {
    Map<Integer, Integer> count = new HashMap<>();
    for (int x : a) count.merge(x, 1, Integer::sum);
    for (int x : a) if (count.get(x) > 1) return String.valueOf(x);
    return "NO";
}
// [1, 5, 3, 4, 5, 3] -> 5 (both 5 and 3 repeat, but 5 appears first)

The sample 10 5 3 4 3 5 6 works the same way: both 5 and 3 repeat, but 5 appears first.

Solution 6: matrix times its transpose, reading several test cases

The result is N×N, with C[i][j] = Σₖ A[i][k] · A[j][k]. There’s no need to build the transpose, because Aᵀ[k][j] = A[j][k]:

static long[][] timesTranspose(int[][] a) {
    int n = a.length, m = a[0].length;
    long[][] c = new long[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            long s = 0;
            for (int k = 0; k < m; k++) s += (long) a[i][k] * a[j][k];
            c[i][j] = s;
        }
    return c;   // [[1,2],[3,4]] -> [[5,11],[11,25]]
}

The result is always symmetric (C[i][j] == C[j][i]), so you can compute just the upper triangle and mirror it, halving the work.

Reading the test cases and printing the output:

// import java.io.*; import java.util.StringJoiner;
public static void main(String[] args) throws IOException {
    StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    in.nextToken(); int t = (int) in.nval;
    StringBuilder out = new StringBuilder();
    for (int test = 1; test <= t; test++) {
        in.nextToken(); int n = (int) in.nval;
        in.nextToken(); int m = (int) in.nval;
        int[][] a = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) { in.nextToken(); a[i][j] = (int) in.nval; }
        out.append("Test ").append(test).append(":\n");
        for (long[] row : timesTranspose(a)) {
            StringJoiner line = new StringJoiner(" ");
            for (long v : row) line.add(Long.toString(v));
            out.append(line).append('\n');
        }
    }
    System.out.print(out);
}

The sample 1 / 2 2 / 1 2 / 3 4 prints Test 1: / 5 11 / 11 25. StringJoiner takes care of “exactly one space, nothing trailing”, a classic reason for wrong-answer verdicts on judge sites.

Solutions 7–9: reading an array, for-each, tic-tac-toe

7. Use the first element as the starting max, not 0:

Scanner in = new Scanner(System.in);
int[] a = new int[5];
for (int i = 0; i < a.length; i++) {
    System.out.print("Number " + (i + 1) + ": ");
    a[i] = Integer.parseInt(in.nextLine().trim());
}
long sum = 0;
int max = a[0];                       // start from the first element, not 0 (all values might be negative)
for (int x : a) {
    sum += x;
    if (x > max) max = x;
}
System.out.println("Sum: " + sum + ", largest: " + max);   // {3, 15, 7, 12, 15} -> 52 and 15

8.

double[] scores = {8.5, 7.0, 9.0, 6.5, 8.0};
double total = 0;
for (double s : scores) total += s;
System.out.printf("Total: %.1f, average: %.2f%n", total, total / scores.length);   // 39.0 and 7.80

For-each doesn’t give you the index. If you need to print “subject i”, go back to an indexed for.

9.

static char winner(char[][] b) {
    for (int i = 0; i < 3; i++) {
        if (b[i][0] != ' ' && b[i][0] == b[i][1] && b[i][1] == b[i][2]) return b[i][0];   // row i
        if (b[0][i] != ' ' && b[0][i] == b[1][i] && b[1][i] == b[2][i]) return b[0][i];   // column i
    }
    char c = b[1][1];                                                                    // both diagonals go through the centre
    if (c != ' ' && ((b[0][0] == c && b[2][2] == c) || (b[0][2] == c && b[2][0] == c))) return c;
    return ' ';                                                                          // no winner yet
}
// {{'X','O','X'}, {' ','X','O'}, {'O',' ','X'}} -> 'X' (main diagonal)

The same thinking applies to digital images: a greyscale image is an int[height][width], a colour image an int[height][width][3] (R, G, B). The original material writes Int[][] (a capital I doesn’t compile) and claims arr[0][1] of a freshly created array prints 20; a new array is all zeros.

Lab 03: a score list with two parallel arrays

The task, paraphrased: read the names and scores of 3 students, store names in a String[] and scores in a double[]; print the list, print the class average, then print the students scoring 8 or more.

Parallel arrays suit this chapter (classes come later), but they’re fragile: sort one array and forget the other, and names and scores no longer match. A senior would group each student into a record and use a List.

Lab 03 solution and the record-based rewrite
import java.util.Scanner;

public class Lab03 {
    public static void main(String[] args) {
        final int n = 3;
        String[] names = new String[n];
        double[] scores = new double[n];          // names[i] and scores[i] belong to the same student
        Scanner in = new Scanner(System.in);

        for (int i = 0; i < n; i++) {
            System.out.printf("Student %d name: ", i + 1);
            names[i] = in.nextLine().strip();
            System.out.print("Score: ");
            scores[i] = Double.parseDouble(in.nextLine().trim());
        }

        System.out.println("Students:");
        double sum = 0;
        for (int i = 0; i < n; i++) {
            System.out.printf("%s - %.1f%n", names[i], scores[i]);
            sum += scores[i];
        }
        System.out.printf("Class average: %.2f%n", sum / n);

        System.out.println("Students scoring 8 or more:");
        boolean found = false;
        for (int i = 0; i < n; i++) {
            if (scores[i] >= 8) {
                System.out.printf("%s - %.1f%n", names[i], scores[i]);
                found = true;
            }
        }
        if (!found) System.out.println("(none)");
    }
}

With the input Nam 8.5, An 6, Huy 9: the average is 7.83, and the students with 8 or more are Nam - 8.5 and Huy - 9.0. The sample output in the original material shows “Linh - 8.5”, but nobody called Linh is in the input; it should be Nam.

The rewrite with a record and a List:

record Student(String name, double score) {}

List<Student> students = List.of(new Student("Nam", 8.5), new Student("An", 6), new Student("Huy", 9));
double average = students.stream().mapToDouble(Student::score).average().orElse(Double.NaN);   // 7.83...
List<String> good = students.stream().filter(s -> s.score() >= 8).map(Student::name).toList(); // [Nam, Huy]

average() returns an OptionalDouble, so the empty-list case has to be handled explicitly instead of silently dividing by zero.

Remember

  • Can you explain why array access is O(1) and why row-by-row iteration beats column-by-column?
  • Can you tell length, length() and size() apart, and compare, print and deep-copy a 2D array?
  • Can you explain why == on strings is sometimes true, and why you still need equals?
  • Do you know when to use +, when to use StringBuilder, and why StringBuffer is almost never needed?
  • Do you remember the three String traps: split takes a regex, toUpperCase() depends on the locale, length() counts UTF-16 units?

Interview questions

Junior

What are the default element values of new int[3], new boolean[2] and new String[2]?

0, false and null.

Local variables have no default value; reading one before assignment is a compile error.

What is the difference between length, length() and size()?

array.length is a field of an array, string.length() is a method on String, list.size() is a method on collections.

string.length() returns the number of UTF-16 units (an emoji can count as 2). They differ because arrays are a special JVM type, while String and List are ordinary classes.

How do you compare two strings, and two arrays, correctly?

Strings with equals; arrays with Arrays.equals (or Arrays.deepEquals for multi-dimensional arrays).

  • Strings: a == b only compares references (sometimes true thanks to the string pool, never rely on it). Write "CONST".equals(x) or Objects.equals(a, b) to be null-safe.
  • Arrays: an array’s own equals also only compares references.

Mid

How is a 2D array stored in Java? Why is row-by-row iteration faster than column-by-column?

A 2D array is an array of references, each row a separate 1D array; row-by-row iteration reads neighbouring cells, so it uses the cache well.

Rows can have different lengths. Elements within a row are contiguous, so row-major iteration uses CPU cache lines (the block of data the CPU loads at once) well. Column-major iteration hops between different objects and causes cache misses.

Why is + concatenation in a loop slow? How do StringBuilder and StringBuffer differ?

Each s = s + x creates a new string and copies all the old content, so n concatenations cost O(n²); StringBuilder appends in amortized O(1), and StringBuffer does the same but synchronized.

  • StringBuilder keeps a growable array.
  • StringBuffer has the same API with every method synchronized, which is slightly slower and almost never needed, because a string under construction usually belongs to one thread.
  • For a few values on one line, just use +; since Java 9 the compiler emits an optimised invokedynamic call for it.
What does it mean that Arrays.copyOf makes a shallow copy? How do you copy a 2D array?

A shallow copy copies each cell’s value; in an object array or a 2D array the cells are references, so the copy still shares the underlying objects. To deep-copy a 2D array, copy each row.

Arrays.copyOf, clone() and System.arraycopy all copy shallowly. For a primitive array that’s a real copy. For a 2D array, changing copy[0][0] changes original[0][0] too. Deep copy: int[][] copy = new int[m.length][]; for (int i = 0; i < m.length; i++) copy[i] = m[i].clone();.

Senior

Why is ArrayList.add amortized O(1) when it sits on top of a fixed-size array?

Because each time it fills up, capacity grows by about 1.5 times, so the total copying across n adds is only O(n), or O(1) per add.

A single resize costs O(n), but it happens rarely. If you know the size up front, use new ArrayList<>(expectedSize) to avoid repeated copies and the extra garbage they create.

Which algorithms does Arrays.sort use for primitive and object arrays, and why do they differ?

Primitives use dual-pivot quicksort (fast, memory-light, not stable); objects use TimSort (stable). They differ because only objects need equal elements to keep their order.

  • Two identical 5s can’t be told apart, so instability doesn’t matter for primitives.
  • TimSort is stable (equal elements keep their original order, which matters when you sort by several criteria in turn), very fast on partially ordered data, at the cost of up to n/2 extra memory.
  • For very large arrays there’s Arrays.parallelSort, which runs on the ForkJoinPool.

Useful phrases for interviews

  • “Arrays are contiguous in memory, which makes them cache-friendly.”
  • “Array indexes run from zero to length minus one; anything else throws an out-of-bounds exception.”
  • “Arrays.copyOf makes a shallow copy, so the rows of a 2D array are still shared.”
  • “Strings are immutable, so I build long strings with a StringBuilder.”
  • “I always compare strings with equals, putting the constant on the left to be null-safe.”
  • “For technical strings I pass Locale.ROOT to toUpperCase so the result doesn’t depend on the server’s locale.”
  • “I iterate in row-major order because each row is a contiguous block in memory.”
  • “I’d replace these parallel arrays with a list of records so the data can’t get out of sync.”

Most of the diagrams in the slides come from Introduction to Java Programming and Data Structures by Y. Daniel Liang (11th edition), a good book if you want to read further.


Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.