Skip to the page

Core Java and OOP · Write code

Does Java pass objects by reference?

The interviewer asks

What does this print? Then tell me: does Java pass objects by reference or by value?

class Account {
    int balance;
    Account(int balance) { this.balance = balance; }
}

static void update(Account acc, int amount, String note) {
    acc.balance += amount;
    amount = 0;
    note = note + " (updated)";
    acc = new Account(999);
    acc.balance = 1;
}

public static void main(String[] args) {
    Account a = new Account(100);
    int amt = 50;
    String note = "salary";
    update(a, amt, note);
    System.out.println(a.balance + " " + amt + " " + note);
}

Then

Follow-ups the interviewer asks next

  1. Why didn't acc = new Account(999) change a?
  2. Can you write a swap(Integer x, Integer y) that works?
  3. Why didn't note change, even though String is an object?
  4. How would you return two values from a method in modern Java?

The answer

What a strong answer covers

  • Prints 150 50 salary.
  • Java always passes by value. For objects, the value is a copy of the reference: the method can change the object through it (balance becomes 150) but reassigning the parameter only changes the local copy.
  • amount = 0 changes the local copy of the int. note + " (updated)" makes a new String; the caller's variable still points to the old one (and String is immutable anyway).
  • A swap of two parameters can't work. Return a new object instead, such as a small record (record Pair(int a, int b)).

The red pen

Common traps

Avoid:"objects are passed by reference, primitives by value"; expecting 1 or 999.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview