SteelReed

Search

Search posts, questions…

1. Java Core

Java basics: loops, methods, the call stack and pass-by-value

Why a method can change the caller's array but reassigning a parameter changes nothing: the call stack, stack frames and pass-by-value in language-neutral terms, then loops, methods and how to review AI-written code for hidden side effects and deep recursion.

17 Nov 20268 min readJunior

–

1. The problem

An invoicing service calls applyVat(prices) to print a VAT version, then saves prices to the database. The method modifies its input array in place, so 3,000 invoices store 110,000 instead of 100,000. The same week, clear(cart) does cart = new ArrayList<>() and the cart still has 3 items.

2. Key idea

Calling a method creates a new frame and copies the argument values into it. For objects that value is a reference: caller and callee see one object through two separate variables. It's like handing someone a photocopy of your address: if they repaint the house you see it; if they edit the address on the paper, the house doesn't move.

Inside the method Does the caller see it? Example
Reassign a primitive parameter no swap(int a, int b)
Change an object through the reference yes prices[i] = ..., list.sort(...)
Point the parameter at another object no cart = new ArrayList<>()
Return a new value only if the caller uses it return withVat(prices)

JavaScript and Python behave the same. Each thread's stack has a fixed size (often 1 MB), so recursion that deepens with input will overflow.

2.1 What to ask of each method and loop?

Parameters: read, modify in place, or return a new one? Let the name answer. Loops and recursion: what guarantees they stop?

Choice Use when Don't use when
Modify input in place large data, the name says so (sortInPlace) the caller still needs the original; input may be List.of(...)
Return a new object the default for business code million-element arrays on a measured hot path
Recursion small, bounded depth (balanced trees) depth grows with input, data may contain cycles
Two nested loops n in the thousands n = 10⁵: 10¹⁰ operations, use a HashMap or sorting

3. In Java

Three small methods prove pass-by-value.

JAVA
static void swap(int a, int b) { int t = a; a = b; b = t; }                       // only swaps the copies
static void swapFirstTwo(int[] arr) { int t = arr[0]; arr[0] = arr[1]; arr[1] = t; } // changes the shared object
static void reassign(int[] arr) { arr = new int[]{0, 0}; }                          // only changes the copied address
 
int x = 1, y = 2;
swap(x, y);              // x = 1, y = 2: unchanged
 
int[] data = {10, 20};
swapFirstTwo(data);      // data = [20, 10]
reassign(data);          // data is still [20, 10]
 
int i = 0;
while (i < 10) {
    if (i % 2 == 0) continue;   // BUG: i never increments again, infinite loop
    i++;
}
Call stacks, labelled break/continue and nested loops
  • Each call pushes a frame (parameters, locals, return address) onto the thread's stack and pops it on return, LIFO. Locals live only in their frame.
  • break exits the nearest loop; continue skips the rest of the iteration. With nested loops, outer: for (...) { for (...) { break outer; } } exits both.
  • do-while runs at least once, handy for "ask again until the input is valid".
  • Removing from a List inside for-each throws ConcurrentModificationException; use removeIf or Iterator.remove().
  • Recursion uses one frame per level. 100,000 levels usually overflow a 1 MB stack; raising -Xss only moves the limit, rewriting as a loop fixes it.

4. Working with AI

Hand to AI: tests for edge cases (empty arrays, one element, immutable inputs), turning deep recursion into loops.

Check in AI-written code:

  • Methods don't silently modify parameters; if they do, the name says so.
  • No param = new ... intended to change the caller's object.
  • Every while changes its condition on every path, including after continue.
  • Recursion has an explicit maximum depth, not one driven by input size.

5. Exercises

Exercise 1: Review a "computes only, changes nothing" method

The AI wrote this, calling it "a pure function, input untouched". Find the bug, name a test that proves it, fix it.

JAVA
static long[] withVat(long[] prices) {
    for (int i = 0; i < prices.length; i++) prices[i] = prices[i] * 110 / 100;
    return prices;
}
Solution to Exercise 1

It modifies the input array and returns that same array: a caller that prints the VAT version and then saves the original prices saves VAT-inclusive prices. It's exactly the bug from section 1.

Test: long[] p = {100_000}; withVat(p); assertEquals(100_000, p[0]); fails (it's 110,000).

Fix: create a new array long[] out = new long[prices.length]; and write into out; or Arrays.stream(prices).map(v -> v * 110 / 100).toArray(). If you must modify in place for performance, name it applyVatInPlace and return void.

Exercise 2: Read a StackOverflowError incident

A category-tree job ran fine for 6 months and died today with java.lang.StackOverflowError, the stack trace repeating CategoryService.depth(CategoryService.java:42) thousands of times. Yesterday an admin imported 20,000 categories from a partner file. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: depth recurses up the parents. Either the new file has a very deep parent chain (depth driven by input) or a cycle (A is B's parent, B is A's), so the recursion never stops.
  • 15 minutes: find cycles in SQL (WITH RECURSIVE with a depth cap); remove the bad data or pause the job.
  • Root fix: rewrite as a loop with an ArrayDeque and a visited set to detect cycles; validate on import (no cycles, a depth limit such as 10).

Summary

  • Java is only pass-by-value; for objects the copy is a reference.
  • Changing an object's contents is visible to the caller; reassigning the parameter isn't.
  • Methods that modify input say so in their name; by default, return a new value.
  • Every loop and recursion needs a guaranteed stopping condition.

Read more: Part 6: Arrays and strings.

Introduction to Java Programming and Data Structures by Y. Daniel Liang (11th edition) is a good book if you want to read further.

Practice interview questions on this topic

All Java Core questions →

Loading comments…