Sobes.tech
Junior — Middle

Are arguments in Java passed by value or by reference?

sobes.tech AI

Answer from AI

In Java, all arguments are passed by value. This means that when a method is called, the value of the argument is copied.

For primitive types (int, double, etc.), the actual value is copied.

For objects, the value of the reference to the object is copied, meaning the pointer is copied, but not the object itself. Therefore, inside the method, you can change the state of the object that the parameter refers to, but you cannot change the reference itself to point to another object.

Example:

void modify(Integer a, MyObject obj) {
    a = 10; // changes the local copy, does not affect the original
    obj.field = 20; // changes the object's field, visible outside
}
Are arguments in Java passed by value or by… - sobes.tech