Is Java "pass-by-reference" or "pass-by-value"?
In Java, arguments are passed to methods by value. This means that when you pass an argument to a method, the method receives a copy of the argument rather than a reference to the original object.
In Java, arguments are passed to methods by value. This means that when you pass an argument to a method, the method receives a copy of the argument rather than a reference to the original object.
For example, consider the following code:
public class Main {
public static void main(String[] args) {
int x = 10;
foo(x);
System.out.println(x); // Outputs 10
}
public static void foo(int y) {
y = 20;
}
}In this code, the foo method is called with the argument x, which has a value of 10. Inside the foo method, the value of y is changed to 20. However, this change does not affect the value of x in the main method, because y is just a copy of x and the main method and the foo method operate on separate copies of the data.
It's worth noting that Java uses pass-by-value for all data types, including objects. When you pass an object to a method, the method receives a copy of the reference value, not a copy of the object itself. This means both the original variable and the method parameter point to the same object in memory, but they hold separate copies of the reference.
For example:
public class Main {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.x = 10;
foo(obj);
System.out.println(obj.x); // Outputs 20
}
public static void foo(MyObject y) {
y.x = 20;
}
}
class MyObject {
int x;
}In this code, the foo method is called with the argument obj, which is an instance of the MyObject class. Inside the foo method, the value of y.x is changed to 20. This change is reflected in the main method because y holds a copy of the reference to the same object as obj. Both variables point to the same object in memory, allowing the method to modify its state. However, since the reference itself is passed by value, reassigning y to a different object inside foo would not affect obj in the main method.