ProgrammingBackend Developer

How does the parameter passing mechanism work in Java methods (pass-by-value), and how can it differ from other programming languages?

Pass interviews with Hintsage AI assistant

Answer

In Java, always uses the pass-by-value mechanism, but there is a peculiarity for objects:

  • For primitive types, the value itself is copied.
  • For objects, the value of the reference to the object is copied, but not the object itself.

Therefore, modifying the fields of an object inside a method affects the original object, but attempting to assign a new reference to a variable inside the method does not affect the original object. This is often confused with pass-by-reference, but Java does not support pass-by-reference!

Example:

void changePrimitive(int a) { a = 10; } void changeObject(Point p) { p.x = 10; } int num = 5; changePrimitive(num); // num is still 5 Point pt = new Point(1, 2); changeObject(pt); // now pt.x == 10

Important! If inside the method you assign p = new Point(100, 200), the original object outside the method will not change. The field of the object changes, not its reference!

Trick Question

Question: Can you change the object passed in as an argument in a method so that outside the method the reference variable points to a new object?

Answer: No, you cannot. Assigning a new reference to the argument inside the method only affects the copy of the reference, which goes away after the method exits. Outside the method, the argument variable points to the original object.

void reassign(Point p) { p = new Point(100, 200); // only locally! } Point pt = new Point(5, 5); reassign(pt); // pt is still (5, 5)

Examples of real mistakes due to ignorance of the subtleties of the topic


Story

In a large financial system, an API was implemented that "returned" changes to an object by modifying the reference inside the method. As a result, after exiting the method, the changes were not reflected. It was necessary to completely redesign part of the logic to clearly delineate mutation and returning new objects.


Story

When trying to implement a swap for two objects in Java with the method swap(A a, B b), the developer passed references and swapped them inside the method. It did not work. It is necessary to either return the result or use container arrays. Ignorance of pass-by-value led to incorrect object swapping.


Story

One of the project members migrated logic from C++ and expected pass-by-reference behavior. As a result, methods stopped working properly: changes inside the method did not "go out". It was urgently necessary to rewrite critical parts of the code, which took a considerable amount of time.