SteelReed

Search

Search posts, questions…

1. Java Core

Java basics: arrays and strings

Why comparing or copying an address instead of the content causes bugs that only show in production: arrays as contiguous slots, immutable strings, ==/equals, shallow copies, StringBuilder, split and locales; how to review AI-written code with arrays and strings.

17 Nov 20267 min readJunior

–

1. The problem

Tests are green, but in production 3,200 orders are stuck in PENDING: the code checks status == "ACTIVE", and the string read from JSON is a different object from the literal in the code. The same month, a 50,000-line CSV built with += takes 3 seconds per export.

2. Key idea

Arrays and strings are objects; variables hold only addresses. Comparing, copying or "modifying" without separating address from content produces bugs that only show up with real data.

Question Java Other languages
Compare address or content == compares addresses, equals content Python is / ==; JavaScript compares arrays by address
Shallow or deep copy clone() copies only the outer layer JavaScript [...a], Python list(a) are shallow too
Immutable strings every String Python, JavaScript, Go, C#: repeated concatenation is O(n²)

An array is contiguous, so the address of element i is computed directly: O(1), and sequential scans use the CPU cache well. The price is a fixed size. A 2D array in Java is an array of arrays: each row is its own object, so clone() copies only the outer layer.

== between strings is sometimes "accidentally" true because the JVM shares one object for identical literals (the string pool). Strings read from requests, JSON or the DB aren't pooled.

2.1 What to use when?

Choice Use when Don't use when
Arrays (int[]) known size, large numeric data, hot loops the element count changes
ArrayList growable lists, API return values millions of ints on a hot path (boxing)
== comparing to null, enums, primitives comparing string or array content
clone(), Arrays.copyOf one-dimensional primitive arrays 2D arrays, arrays of mutable objects
StringBuilder concatenation in loops a few strings on one line (+ reads better)
Hand-written split simple formats you control CSV, logs with separators inside values

3. In Java

JAVA
String status = new String("ACTIVE");          // like a string read from JSON
status == "ACTIVE";                            // false: two objects
"ACTIVE".equals(status);                       // true; constant on the left avoids NPE
 
int[][] grid = {{1, 2}, {3, 4}};
int[][] shallow = grid.clone();                // shares rows: changing shallow[0][0] changes grid
int[][] deep = Arrays.stream(grid).map(int[]::clone).toArray(int[][]::new);
Arrays.deepToString(grid);                     // "[[1, 2], [3, 4]]"; printing directly gives "[[I@..."
 
StringBuilder sb = new StringBuilder();
for (String line : lines) sb.append(line).append('\n');
 
"a,b,,c,,".split(",");                         // [a, b, , c]: trailing empty strings dropped
"a,b,,c,,".split(",", -1);                     // [a, b, , c, , ]
"a.b".split(".");                              // empty array: "." is a regex, use "\\."
"title".toUpperCase(Locale.ROOT);              // "TITLE" on every machine

Other languages: Go uses strings.Builder and slices.Clone; C# has StringBuilder and StringComparison.Ordinal.

A few details on arrays and String
  • Defaults: array elements start as 0, false, '\u0000' or null. array.length is a field; string.length() is a method. Outside [0, length) you get ArrayIndexOutOfBoundsException.
  • Jagged arrays: rows can differ in length (new int[4][]), so loops use grid[r].length. Row-wise traversal beats column-wise.
  • Methods that receive an array and change its elements are visible to the caller: the variable is passed by value, but that value is an address.
  • strip() (Java 11) understands Unicode whitespace, so prefer it to trim(); isBlank() and repeat() are also Java 11.
  • toUpperCase() without arguments uses the JVM locale: a Turkish locale turns "title".toUpperCase() into "TİTLE". For keys, HTTP headers and enum names always use Locale.ROOT.
  • length() counts UTF-16 units: one emoji is 2.
  • StringBuffer is StringBuilder with every method synchronized; you almost never need it.

4. Working with AI

Delegate to AI: generating hard test inputs (empty, whitespace-only, emoji, values with commas, tr-TR locale), writing deep-copy helpers.

Check yourself:

  • No == or != between two Strings or two arrays; grep the repo for == ".
  • Every clone() or Arrays.copyOf on 2D or object arrays has a stated reason.
  • No string += in loops that can run thousands of times.
  • Every split accounts for regex characters (., |) and trailing empty strings.
  • CSV, JSON and URLs are parsed with libraries, not hand-written split.

5. Exercises

Exercise 1: Review "undo" for tic-tac-toe

AI describes it as "stores an independent copy of the board on every move". After undo, the board still has the last move. Find the bug, name a test, fix it.

JAVA
void play(int r, int c, char who) {
    history.push(board.clone());   // char[3][3] board
    board[r][c] = who;
}
void undo() { board = history.pop(); }
Solution to Exercise 1

board.clone() on a char[][] copies only the outer array: the copy and board share the three rows. board[r][c] = who also changes the copy in history.

Test: empty board, play(0, 0, 'X'), undo(), assert board[0][0] == ' ': red with the current code.

Fix: history.push(Arrays.stream(board).map(char[]::clone).toArray(char[][]::new)). Or store only moves (record Move(int r, int c)) and undo by clearing that cell: less memory, no shallow-or-deep question.

Exercise 2: Read a locale incident

The service works on staging; on the new server every request with header X-Title-Mode: title is rejected. Code: if (mode.toUpperCase().equals("TITLE")). The new server has locale tr_TR. Diagnose and fix.

Solution to Exercise 2
  • With a Turkish locale, "title".toUpperCase() gives "TİTLE" (dotted capital I), which isn't "TITLE".
  • 15 minutes: set -Duser.language=en or the container's LANG to C.UTF-8, restart.
  • Root fix: mode.equalsIgnoreCase("title") or toUpperCase(Locale.ROOT); add a test that runs with Locale.setDefault(Locale.forLanguageTag("tr-TR")).

Summary

  • == compares addresses, equals content; constant on the left.
  • Arrays are O(1) by index and fixed-size; use ArrayList to grow.
  • clone() is shallow; 2D arrays need a row-by-row copy.
  • Build strings in loops with StringBuilder.
  • split takes a regex; technical strings use Locale.ROOT.

Next: Wrappers, BigDecimal and String.

For further reading, Introduction to Java Programming and Data Structures by Y. Daniel Liang (11th edition) is a good book.

Practice interview questions on this topic

All Java Core questions →All Collections & DSA questions →All Concurrency questions →

Loading comments…
Next on the roadmapClasses, objects and access boundaries: keeping every object valid