Core Java and OOP · Write code
Does Java pass objects by reference?
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- Why didn't
acc = new Account(999)changea? - Can you write a swap(Integer x, Integer y) that works?
- Why didn't note change, even though String is an object?
- 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 = 0changes 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 voicePractise 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.