Sobes.tech
Junior

How are variables passed to methods?

sobes.tech AI

Answer from AI

In Java, variables are passed by value to methods.

This means that when a method is called, a copy of the variable's value is created and that copy is passed to the method. Changes made to the parameter inside the method only affect this copy and do not impact the original variable.

For primitive data types (int, float, boolean, etc.), the actual value is passed.

// Primitive data type
int a = 10;

void changeValue(int x) {
  x = 20; // Changes the copy, not the original variable 'a'
}

changeValue(a);
// After the method call, 'a' still equals 10

For reference data types (objects, arrays), a copy of the reference to the object is passed. The reference itself is copied, but both references point to the same object in memory. Changes to the object's state made inside the method via the passed reference will be visible outside the method. However, reassigning the reference inside the method does not affect the original reference.

// Reference data type
class MyObject {
    int value;
}

MyObject obj = new MyObject();
obj.value = 10;

void changeObjectValue(MyObject o) {
  o.value = 20; // Changes the object's state, visible outside
}

void reassignObject(MyObject o) {
  o = new MyObject(); // Reassigns the local reference, does not affect the original 'obj'
  o.value = 30;
}

changeObjectValue(obj);
// After the call, obj.value equals 20

reassignObject(obj);
// After the call, 'obj' still points to the same object, obj.value is 20
// The new MyObject created inside reassignObject is not accessible outside

Thus, Java always uses pass-by-value, but for reference types, the value of the reference is copied, not the object itself.

How are variables passed to methods? — Java - sobes.tech