Junior
Are data in Java passed by reference or by value?
sobes.tech AI
Answer from AI
In Java, primitive types (byte, short, int, long, float, double, boolean, char) are passed by value. A copy of the variable's value is passed to the method.
Objects (including arrays) are passed by value of the reference. This means that a copy of the reference is passed, not the actual object. Using this copy, you can access and modify the original object, but changing the reference itself inside the method will not affect the original reference outside.
Example with a primitive type:
// Primitive type int is passed by value
int x = 10;
void modifyPrimitive(int value) {
value = 20; // Modifies the copy of the value
}
// After calling modifyPrimitive(x), x still equals 10.
Example with an object:
// Object is passed by the value of the reference
class MyObject {
int value;
}
MyObject obj = new MyObject();
obj.value = 10;
void modifyObject(MyObject objRef) {
objRef.value = 20; // Changes the state of the original object
objRef = new MyObject(); // Reassigns the local copy of the reference
objRef.value = 30;
}
// After calling modifyObject(obj), obj.value equals 20.
// The reference obj still points to the original object.