Junior — Middle
Explain how data is passed to a function when parameters are passed by value.
sobes.tech AI
Answer from AI
In Java, parameters are passed to methods 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 reference types, the value of the reference (the address of the object) is copied, but not the object itself. Therefore, inside the method, you can modify the state of the object that the reference points to, but you cannot change the reference itself to point to another object outside the method.
Example:
void modify(int x, StringBuilder sb) {
x = 10; // only the local copy is changed
sb.append(" world"); // the object that sb references is modified
}
int a = 5;
StringBuilder str = new StringBuilder("Hello");
modify(a, str);
System.out.println(a); // 5
System.out.println(str.toString()); // Hello world
Here, the value of a will not change, but the object str will be modified.