Sobes.tech
Junior — Middle

How is argument passing implemented in Java when calling methods?

sobes.tech AI

Answer from AI

In Java, arguments to methods are passed by value. This means that a copy of the variable's value is passed to the method, not the variable itself.

  • For primitive types (int, double, boolean, etc.), the actual value is copied.
  • For reference types (objects), the value of the reference (the address of the object in memory) is copied. As a result, the method receives a copy of the reference to the same object, so changes to the object's state inside the method will be visible outside, but reassigning the reference inside the method will not affect the original.

Example:

void modify(int x, List<String> list) {
    x = 10; // change to local copy
    list.add("new item"); // change the object that the copied reference points to
}

int a = 5;
List<String> myList = new ArrayList<>();
modify(a, myList);
// a will remain 5
// myList now contains "new item"