Sobes.tech
Junior — Middle

How is argument passing implemented in Java methods?

sobes.tech AI

Answer from AI

In Java, arguments to methods are passed by value. This means that when a method is called, a copy of the argument's value is passed to the method's parameter.

For primitive types (int, double, boolean, etc.), the actual value is copied. Changes to the parameter inside the method do not affect the original variable.

For reference types (objects), the value of the reference (the address of the object) is copied. As a result, the method receives a copy of the reference to the same object. Changes to the object's state inside the method will be visible outside, but reassigning the parameter to a different object will not affect the original reference.

Example:

void modify(int x, List<String> list) {
    x = 10; // does not affect the external argument
    list.add("new item"); // modifies the object, visible outside
}