Junior — Middle
How are variables passed to functions: by value or by reference?
sobes.tech AI
Answer from AI
In Java, parameter passing to methods occurs only by value. This means that when a method is called, the value of the argument is copied and passed to the function parameter.
For primitive types (int, boolean, etc.), the actual value is copied.
For objects, the reference value is copied, meaning the pointer is copied, but not the object itself. Therefore, inside the method, you can change the state of the object the reference points to, but you cannot change the reference itself to point to another object outside the method.
Example:
public void modifyList(List<String> list) {
list.add("new item"); // modifies the object
list = new ArrayList<>(); // changes the local copy of the reference, does not affect the original
}