Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Variables, Data Types & Operators

Java is often described as 'pass-by-value' even for objects. Explain what that actually means and a bug it commonly causes.

Level II · JuniorVariables, Data Types & Operators
Short answer

Java always copies the value of the argument; for reference types the value being copied is the reference (the pointer), not the object.

Explanation

So a method can mutate the object's fields and the caller sees it, but reassigning the parameter inside the method does not change which object the caller's variable points to. The classic bug is a 'swap(a, b)' method that swaps the local references and has no effect on the caller's variables.

Common mistakes
  • Saying Java passes objects by reference — it passes the reference by value.
  • Expecting reassigning a parameter inside a method to change the caller's variable.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Variables, Data Types & Operators.

Practise free

More on Variables, Data Types & Operators