Junior — Middle
How can you ensure passing an argument to a function by value rather than by reference?
sobes.tech AI
Answer from AI
In Java, all arguments are passed to methods by value. However, for objects, the value of the reference to the object is passed, not the object itself. To ensure pass-by-value semantics (i.e., so that changes inside the method do not affect the original object), you can:
- Use primitive types (int, double, etc.), which are passed by value directly.
- Create a copy of the object (clone the object) and pass the copy to the method.
Example with object copying:
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
Point(Point p) { this.x = p.x; this.y = p.y; } // copy constructor
}
void movePoint(Point p) {
p.x += 10;
p.y += 10;
}
Point original = new Point(5, 5);
Point copy = new Point(original); // create a copy
movePoint(copy); // modify the copy
// original remains unchanged
Thus, changes inside the method will not affect the original object.