Junior — Middle
How do the methods of passing arguments to functions differ: by reference and by value?
sobes.tech AI
Answer from AI
In Java, arguments are passed to methods by value. This means that when a method is called, the value of the argument is copied, not the reference to the original object.
- For primitive types (int, double, etc.), the actual value is copied.
- For objects, the value of the reference is copied, meaning a pointer to the object is copied, but not the object itself.
Because of this, inside the method, you can change the state of the object that the copied reference points to, but you cannot reassign the reference itself to point to a different object, and expect this to affect the original.
Example:
public class Example {
public static void modify(int x, StringBuilder sb) {
x = 10; // local copy is changed
sb.append(" world"); // the object the reference points to is changed
}
public static void main(String[] args) {
int a = 5;
StringBuilder b = new StringBuilder("Hello");
modify(a, b);
System.out.println(a); // 5, value did not change
System.out.println(b.toString()); // Hello world, object was changed
}
}